/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/@tmcw/graphql-codegen-cli@1.11.2-pre/dist/index.cjs.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}function _interopNamespace(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach((function(n){var o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:function(){return e[n]}})})),t.default=e,t}Object.defineProperty(exports,"__esModule",{value:!0});const core=require("@graphql-codegen/core"),pluginHelpers=require("@graphql-codegen/plugin-helpers"),chalk=_interopDefault(require("chalk")),logUpdate=_interopDefault(require("log-update")),indentString=_interopDefault(require("indent-string")),logSymbols=_interopDefault(require("log-symbols")),commonTags=require("common-tags"),tsLog=require("ts-log"),graphql=require("graphql"),path=require("path"),common=require("@graphql-toolkit/common"),cosmiconfig=require("cosmiconfig"),commander=require("commander"),graphqlConfig=require("graphql-config"),apolloEngineLoader=require("@graphql-toolkit/apollo-engine-loader"),codeFileLoader=require("@graphql-toolkit/code-file-loader"),gitLoader=require("@graphql-toolkit/git-loader"),githubLoader=require("@graphql-toolkit/github-loader"),prismaLoader=require("@graphql-toolkit/prisma-loader"),core$1=require("@graphql-toolkit/core"),graphqlFileLoader=require("@graphql-toolkit/graphql-file-loader"),jsonFileLoader=require("@graphql-toolkit/json-file-loader"),urlLoader=require("@graphql-toolkit/url-loader"),child_process=require("child_process"),isGlob=_interopDefault(require("is-glob")),debounce=_interopDefault(require("debounce")),fs=require("fs"),mkdirp=require("mkdirp"),crypto=require("crypto"),inquirer=_interopDefault(require("inquirer")),detectIndent=_interopDefault(require("detect-indent"));let logger;function getLogger(){return logger||tsLog.dummyLogger}function useWinstonLogger(){logger&&logger.levels||(logger=console)}useWinstonLogger();let queue=[];function debugLog(e,...t){process.env.GQL_CODEGEN_NODEBUG||void 0===process.env.DEBUG||queue.push({message:e,meta:t})}function printLogs(){process.env.GQL_CODEGEN_NODEBUG||void 0===process.env.DEBUG||(queue.forEach((e=>{getLogger().info(e.message,...e.meta)})),resetLogs())}function resetLogs(){queue=[]}const UpdateRenderer=require("listr-update-renderer");class Renderer{constructor(e,t){this.updateRenderer=new UpdateRenderer(e,t)}render(){return this.updateRenderer.render()}end(e){if(this.updateRenderer.end(e),void 0!==typeof e){if(logUpdate.done(),e){const t=e.errors?e.errors.length:0;if(t>0){const n=indentString(chalk.red.bold(`Found ${t} error${t>1?"s":""}`),1),o=e.errors.map((e=>(debugLog("[CLI] Exited with an error",e),{msg:core.isDetailedError(e)?e.details:null,rawError:e}))).map((({msg:t,rawError:n},o)=>{const r=e.errors[o].source;t=t?chalk.gray(indentString(commonTags.stripIndent(`${t}`),4)):null;const a=n.stack?chalk.gray(indentString(commonTags.stripIndent(n.stack),4)):null;if(r){const e="string"==typeof r?r:r.name;return[indentString(`${logSymbols.error} ${e}`,2),t,a,a].filter(Boolean).join("\n")}return[t,a].filter(Boolean).join("\n")})).join("\n\n");logUpdate(["",n,o,""].join("\n\n"))}else{const t=e.details?e.details:"";logUpdate(`${chalk.red.bold(`${indentString(e.message,2)}`)}\n${t}\n${chalk.grey(e.stack)}`)}}logUpdate.done(),printLogs()}else logUpdate.clear()}}async function getPluginByName(e,t){const n=[`@graphql-codegen/${e}`,`@graphql-codegen/${e}-template`,`@graphql-codegen/${e}-plugin`,`graphql-codegen-${e}`,`graphql-codegen-${e}-template`,`graphql-codegen-${e}-plugin`,`codegen-${e}`,`codegen-${e}-template`,e],o=n.concat(path.resolve(process.cwd(),e));for(const n of o)try{return await t(n)}catch(t){if(-1===t.message.indexOf(`Cannot find module '${n}'`))throw new core.DetailedError(`Unable to load template plugin matching ${e}`,`\n              Unable to load template plugin matching '${e}'.\n              Reason: \n                ${t.message}\n            `)}const r=n.map((e=>`\n        - ${e}\n    `.trimRight())).join("");throw new core.DetailedError(`Unable to find template plugin matching ${e}`,`\n        Unable to find template plugin matching '${e}'\n        Install one of the following packages:\n        \n        ${r}\n      `)}async function getPresetByName(e,t){const n=[`@graphql-codegen/${e}`,`@graphql-codegen/${e}-preset`,e],o=n.concat(path.resolve(process.cwd(),e));for(const n of o)try{const e=await t(n);return e&&e.preset?e.preset:e&&e.default?e.default:e}catch(t){if(-1===t.message.indexOf(`Cannot find module '${n}'`))throw new core.DetailedError(`Unable to load preset matching ${e}`,`\n              Unable to load preset matching '${e}'.\n              Reason: \n                ${t.message}\n            `)}const r=n.map((e=>`\n        - ${e}\n    `.trimRight())).join("");throw new core.DetailedError(`Unable to find preset matching ${e}`,`\n        Unable to find preset matching '${e}'\n        Install one of the following packages:\n        \n        ${r}\n      `)}const CodegenExtension=e=>(e.loaders.schema.register(new codeFileLoader.CodeFileLoader),e.loaders.schema.register(new gitLoader.GitLoader),e.loaders.schema.register(new githubLoader.GithubLoader),e.loaders.schema.register(new apolloEngineLoader.ApolloEngineLoader),e.loaders.schema.register(new prismaLoader.PrismaLoader),e.loaders.documents.register(new codeFileLoader.CodeFileLoader),e.loaders.documents.register(new gitLoader.GitLoader),e.loaders.documents.register(new githubLoader.GithubLoader),{name:"codegen"});async function findAndLoadGraphQLConfig(e){const t=await graphqlConfig.loadConfig({filepath:e,rootDir:process.cwd(),extensions:[CodegenExtension],throwOnEmpty:!1,throwOnMissing:!1});if(isGraphQLConfig(t))return t}function isGraphQLConfig(e){if(!e)return!1;try{return e.getDefault().hasExtension("codegen")}catch(e){}try{for(const t in e.projects)if(e.projects.hasOwnProperty(t)){if(e.projects[t].hasExtension("codegen"))return!0}}catch(e){}return!1}const loadSchema=async(e,t)=>{try{const n=[new codeFileLoader.CodeFileLoader,new gitLoader.GitLoader,new githubLoader.GithubLoader,new graphqlFileLoader.GraphQLFileLoader,new jsonFileLoader.JsonFileLoader,new urlLoader.UrlLoader,new apolloEngineLoader.ApolloEngineLoader,new prismaLoader.PrismaLoader];return await core$1.loadSchema(e,{assumeValidSDL:!0,loaders:n,sort:!0,convertExtensions:!0,commentDescriptions:!0,...t})}catch(t){throw new core.DetailedError("Failed to load schema",`\n        Failed to load schema from ${Object.keys(e).join(",")}:\n\n        ${t.message||t}\n        ${t.stack||""}\n    \n        GraphQL Code Generator supports:\n          - ES Modules and CommonJS exports (export as default or named export "schema")\n          - Introspection JSON File\n          - URL of GraphQL endpoint\n          - Multiple files with type definitions (glob expression)\n          - String in config file\n    \n        Try to use one of above options and run codegen again.\n    \n      `)}},loadDocuments=async(e,t)=>{const n=[new codeFileLoader.CodeFileLoader,new gitLoader.GitLoader,new githubLoader.GithubLoader,new graphqlFileLoader.GraphQLFileLoader];return(await core$1.loadDocuments(e,{ignore:Object.keys(t.generates).map((e=>path.join(process.cwd(),e))),loaders:n,sort:!0,...t})).map((({location:e,document:t})=>({filePath:e,content:t}))).sort(((e,t)=>e.filePath<t.filePath?-1:e.filePath>t.filePath?1:0))};function generateSearchPlaces(e){const t=["json","yaml","yml","js","config.js"],n=t.map((t=>`${e}.${t}`)),o=t.filter((e=>"config.js"!==e)).map((t=>`.${e}rc.${t}`));return n.concat(o)}function customLoader(e){return function(t,n){return"undefined"!=typeof process&&"env"in process&&(n=n.replace(/\$\{(.*?)\}/g,((e,t,n)=>{let o=t,r="";if(t.includes(":")){const e=t.split(":");o=e.shift(),r=e.join(":")}return process.env[o]||r}))),"json"===e?cosmiconfig.defaultLoaders[".json"](t,n):"yaml"===e?cosmiconfig.defaultLoaders[".yaml"](t,n):"js"===e?cosmiconfig.defaultLoaders[".js"](t,n):void 0}}async function loadContext(e){const t="codegen",n=cosmiconfig.cosmiconfig(t,{searchPlaces:generateSearchPlaces(t),loaders:{".json":customLoader("json"),".yaml":customLoader("yaml"),".yml":customLoader("yaml"),".js":customLoader("js"),noExt:customLoader("yaml")}}),o=await findAndLoadGraphQLConfig(e);if(o)return new CodegenContext({graphqlConfig:o});const r=await(e?n.load(e):n.search(process.cwd()));if(!r){if(e)throw new core.DetailedError(`Config ${e} does not exist`,`\n        Config ${e} does not exist.\n  \n          $ graphql-codegen --config ${e}\n  \n        Please make sure the --config points to a correct file.\n      `);throw new core.DetailedError("Unable to find Codegen config file!","\n        Please make sure that you have a configuration file under the current directory! \n      ")}if(r.isEmpty)throw new core.DetailedError("Found Codegen config file but it was empty!","\n        Please make sure that you have a valid configuration file under the current directory!\n      ");return new CodegenContext({filepath:r.filepath,config:r.config})}function getCustomConfigPath(e){const t=e.config;return t?path.resolve(process.cwd(),t):null}function collect(e,t){return t.push(e),t}function setCommandOptions(e){return e.allowUnknownOption(!0).option("-c, --config <path>",'Path to GraphQL codegen YAML config file, defaults to "codegen.yml" on the current directory').option("-w, --watch","Watch for changes and execute generation automatically").option("-s, --silent","A flag to not print errors in case they occur").option("-r, --require [value]","Loads specific require.extensions before running the codegen and reading the configuration",collect,[]).option("-o, --overwrite","Overwrites existing files").option("-p, --project <name>","Name of a project in GraphQL Config")}function parseArgv(e=process.argv){return setCommandOptions((new commander.Command).usage("graphql-codegen [options]")).parse(e)}async function createContext(e=parseArgv(process.argv)){if(e.require&&e.require.length>0)for(const t of e.require)await new Promise((function(e){e(_interopNamespace(require(t)))}));const t=getCustomConfigPath(e),n=await loadContext(t);return updateContextWithCliFlags(n,e),n}function updateContextWithCliFlags(e,t){const n={configFilePath:e.filepath};!0===t.watch&&(n.watch=t.watch),!0===t.overwrite&&(n.overwrite=t.overwrite),!0===t.silent&&(n.silent=t.silent),t.project&&e.useProject(t.project),e.updateConfig(n)}class CodegenContext{constructor({config:e,graphqlConfig:t,filepath:n}){this._config=e,this._graphqlConfig=t,this.filepath=this._graphqlConfig?this._graphqlConfig.filepath:n,this.cwd=this._graphqlConfig?this._graphqlConfig.dirpath:process.cwd()}useProject(e){this._project=e}getConfig(){if(!this.config)if(this._graphqlConfig){const e=this._graphqlConfig.getProject(this._project);this.config={...e.extension("codegen"),schema:e.schema,documents:e.documents}}else this.config=this._config;return this.config}updateConfig(e){this.config={...this.getConfig(),...e}}async loadSchema(e){return this._graphqlConfig?await this._graphqlConfig.getProject(this._project).loadSchema(e):loadSchema(e,this.getConfig())}async loadDocuments(e){if(this._graphqlConfig){return(await this._graphqlConfig.getProject(this._project).loadDocuments(e)).map((e=>({filePath:e.location,content:e.document})))}return loadDocuments(e,this.getConfig())}}function ensureContext(e){return e instanceof CodegenContext?e:new CodegenContext({config:e})}const Listr=require("listr"),defaultLoader=e=>new Promise((function(t){t(_interopNamespace(require(e)))}));async function executeCodegen(e){function t(e,t){return async()=>{try{await Promise.resolve().then((()=>e()))}catch(e){throw!t||e instanceof graphql.GraphQLError||(e.source=t),e}}}const n=ensureContext(e),o=n.getConfig(),r=[],a={exitOnError:!0};let i;i=process.env.VERBOSE?new Listr({...a,renderer:"verbose",nonTTYRenderer:"verbose"}):"test"===process.env.NODE_ENV?new Listr({...a,renderer:"silent",nonTTYRenderer:"silent"}):new Listr({...a,renderer:o.silent?"silent":Renderer,nonTTYRenderer:o.silent?"silent":"default",collapse:!0,clearOutput:!1});let s,l,c={},g={};return i.add({title:"Parse configuration",task:()=>async function(){const e=pluginHelpers.normalizeInstanceOrArray(o.require);for(const t of e)await new Promise((function(e){e(_interopNamespace(require(t)))}));c=o.config||{},s=pluginHelpers.normalizeInstanceOrArray(o.schema),l=pluginHelpers.normalizeInstanceOrArray(o.documents);const t=Object.keys(o.generates);if(0===t.length)throw new core.DetailedError("Invalid Codegen Configuration!",'\n        Please make sure that your codegen config file contains the "generates" field, with a specification for the plugins you need.\n        \n        It should looks like that:\n\n        schema:\n          - my-schema.graphql\n        generates:\n          my-file.ts:\n            - plugin1\n            - plugin2\n            - plugin3\n        ');for(const e of t)if(g[e]=pluginHelpers.normalizeOutputParam(o.generates[e]),0===g[e].plugins.length)throw new core.DetailedError("Invalid Codegen Configuration!",`\n          Please make sure that your codegen config file has defined plugins list for output "${e}".\n          \n          It should looks like that:\n  \n          schema:\n            - my-schema.graphql\n          generates:\n            my-file.ts:\n              - plugin1\n              - plugin2\n              - plugin3\n          `);if(0===s.length&&Object.keys(g).some((e=>!g[e].schema||0===g[e].schema.length)))throw new core.DetailedError("Invalid Codegen Configuration!",'\n        Please make sure that your codegen config file contains either the "schema" field \n        or every generated file has its own "schema" field.\n        \n        It should looks like that:\n        schema:\n          - my-schema.graphql\n\n        or:\n        generates:\n          path/to/output:\n            schema: my-schema.graphql\n      ')}()}),i.add({title:"Generate outputs",task:()=>new Listr(Object.keys(g).map(((e,a)=>{const i=g[e],p=!!i.preset;return{title:p?`Generate to ${e} (using EXPERIMENTAL preset "${i.preset}")`:`Generate ${e}`,task:()=>{const a=i.config||{},g=[];let u,d;const f=pluginHelpers.normalizeInstanceOrArray(i.schema),h=pluginHelpers.normalizeInstanceOrArray(i.documents);return new Listr([{title:"Load GraphQL schemas",task:t((async()=>{debugLog("[CLI] Loading Schemas");const e={},t=[...s,...f];for(const n of t)"string"==typeof n?e[n]={}:"object"==typeof n&&Object.assign(e,n);u=await n.loadSchema(e),d=graphql.parse(common.printSchemaWithDirectives(u))}),e)},{title:"Load GraphQL documents",task:t((async()=>{debugLog("[CLI] Loading Documents");const e=[...l,...h],t=await n.loadDocuments(e);t.length>0&&g.push(...t)}),e)},{title:"Generate",task:t((async()=>{debugLog("[CLI] Generating output");const t=pluginHelpers.normalizeConfig(i.plugins),n=o.pluginLoader||defaultLoader,s=await Promise.all(t.map((e=>getPluginByName(Object.keys(e)[0],n)))),l={},f=p?"string"==typeof i.preset?await getPresetByName(i.preset,defaultLoader):i.preset:null;s.forEach(((e,n)=>{const o=t[n],r=Object.keys(o)[0];l[r]=e}));const h={...c,..."string"==typeof a?{value:a}:a};let m=[];m=p?await f.buildGeneratesSection({baseOutputDir:e,presetConfig:i.presetConfig||{},plugins:t,schema:d,schemaAst:u,documents:g,config:h,pluginMap:l}):[{filename:e,plugins:t,schema:d,schemaAst:u,documents:g,config:h,pluginMap:l}];await Promise.all(m.map((async e=>{const t=await core.codegen(e);r.push({filename:e.filename,content:t,hooks:i.hooks||{}})})))}),e)}],{exitOnError:!0})}}})),{exitOnError:!1,concurrent:4})}),await i.run(),r}const DEFAULT_HOOKS={afterStart:[],beforeDone:[],onWatchTriggered:[],onError:[],afterOneFileWrite:[],afterAllFileWrite:[],beforeOneFileWrite:[],beforeAllFileWrite:[]};function normalizeHooks(e){return Object.keys({...DEFAULT_HOOKS,...e||{}}).reduce(((t,n)=>"string"==typeof e[n]?{...t,[n]:[e[n]]}:Array.isArray(e[n])?{...t,[n]:e[n]}:t),{})}function execShellCommand(e){return new Promise(((t,n)=>{child_process.exec(e,{env:{...process.env,PATH:`${process.env.PATH}${path.delimiter}${process.cwd()}${path.sep}node_modules${path.sep}.bin`}},((e,o,r)=>{e?n(e):t(o||r)}))}))}async function executeHooks(e,t=[],n=[]){debugLog(`Running lifecycle hook "${e}" scripts...`);for(const o of t)debugLog(`Running lifecycle hook "${e}" script: ${o} with args: ${n.join(" ")}...`),await execShellCommand(`${o} ${n.join(" ")}`)}const lifecycleHooks=(e={})=>{const t=normalizeHooks(e);return{afterStart:async()=>executeHooks("afterStart",t.afterStart),onWatchTriggered:async(e,n)=>executeHooks("onWatchTriggered",t.onWatchTriggered,[e,n]),onError:async e=>executeHooks("onError",t.onError,[`"${e}"`]),afterOneFileWrite:async e=>executeHooks("afterOneFileWrite",t.afterOneFileWrite,[e]),afterAllFileWrite:async e=>executeHooks("afterAllFileWrite",t.afterAllFileWrite,e),beforeOneFileWrite:async e=>executeHooks("beforeOneFileWrite",t.beforeOneFileWrite,[e]),beforeAllFileWrite:async e=>executeHooks("beforeAllFileWrite",t.beforeAllFileWrite,e),beforeDone:async()=>executeHooks("beforeDone",t.beforeDone)}},isValidPath=require("is-valid-path");function log(e){getLogger().info(`  ${e}`)}function emitWatching(){log(`${logSymbols.info} Watching for changes...`)}const createWatcher=(e,t)=>{debugLog("[Watcher] Starting watcher...");let n=e.getConfig();const o=[e.filepath].filter((e=>e)),r=pluginHelpers.normalizeInstanceOrArray(n.documents),a=pluginHelpers.normalizeInstanceOrArray(n.schema);let i;Object.keys(n.generates).map((e=>pluginHelpers.normalizeOutputParam(n.generates[e]))).forEach((e=>{a.push(...pluginHelpers.normalizeInstanceOrArray(e.schema)),r.push(...pluginHelpers.normalizeInstanceOrArray(e.documents))})),r&&r.forEach((e=>{"string"==typeof e?o.push(e):o.push(...Object.keys(e))})),a.forEach((e=>{(isGlob(e)||isValidPath(e))&&o.push(e)})),"boolean"!=typeof n.watch&&o.push(...pluginHelpers.normalizeInstanceOrArray(n.watch));const s=async()=>{const r=await new Promise((function(e){e(_interopNamespace(require("chokidar")))}));let a=!1;const s=debounce((()=>{a||executeCodegen(e).then(t,(()=>Promise.resolve())).then((()=>emitWatching()))}),100);emitWatching();const l=[];Object.keys(n.generates).map((e=>({filename:e,config:pluginHelpers.normalizeOutputParam(n.generates[e])}))).forEach((e=>{if(e.config.preset){const t=e.config.presetConfig&&e.config.presetConfig.extension;t&&l.push(path.join(e.filename,"**","*"+t))}else l.push(e.filename)})),i=r.watch(o,{persistent:!0,ignoreInitial:!0,followSymlinks:!0,cwd:process.cwd(),disableGlobbing:!1,usePolling:!0,interval:100,binaryInterval:300,depth:99,awaitWriteFinish:!0,ignorePermissionErrors:!1,atomic:!0,ignored:l}),debugLog("[Watcher] Started");const c=async()=>{a=!0,debugLog("[Watcher] Shutting down"),log("Shutting down watch..."),i.close(),lifecycleHooks(n.hooks).beforeDone()};i.on("all",(async(e,t)=>{lifecycleHooks(n.hooks).onWatchTriggered(e,t),debugLog(`[Watcher] triggered due to a file ${e} event: ${t}`);const o=path.join(process.cwd(),t);if("change"===e&&n.configFilePath&&o===n.configFilePath){log(`${logSymbols.info} Config file has changed, reloading...`);const e=(await loadContext(n.configFilePath)).getConfig();e.watch=n.watch,e.silent=n.silent,e.overwrite=n.overwrite,e.configFilePath=n.configFilePath,n=e}s()})),process.once("SIGINT",c),process.once("SIGTERM",c)};return new Promise(((n,o)=>{executeCodegen(e).then(t,(()=>Promise.resolve())).then(s).catch((e=>{i.close(),o(e)}))}))};function writeSync(e,t){return fs.writeFileSync(e,t)}function readSync(e){return fs.readFileSync(e,"utf-8")}function fileExists(e){try{return fs.statSync(e).isFile()}catch(e){return!1}}const hash=e=>crypto.createHash("sha1").update(e).digest("base64");async function generate(e,t=!0){const n=ensureContext(e),o=n.getConfig();await lifecycleHooks(o.hooks).afterStart();let r=new Map;async function a(n){return t?(await lifecycleHooks(o.hooks).beforeAllFileWrite(n.map((e=>e.filename))),await Promise.all(n.map((async t=>{const n=fileExists(t.filename);if(!shouldOverwrite(o,t.filename)&&n)return;const a=t.content||"",i=hash(a);let s=r.get(t.filename);if(!s&&n&&(s=hash(readSync(t.filename))),s&&i===s)return void debugLog(`Skipping file (${t.filename}) writing due to indentical hash...`);if(0===a.length)return;r.set(t.filename,i);const l=path.dirname(t.filename);await lifecycleHooks(t.hooks).beforeOneFileWrite(t.filename),await lifecycleHooks(o.hooks).beforeOneFileWrite(t.filename),mkdirp.sync(l);writeSync(path.isAbsolute(t.filename)?t.filename:path.join(e.cwd||process.cwd(),t.filename),t.content),await lifecycleHooks(t.hooks).afterOneFileWrite(t.filename),await lifecycleHooks(o.hooks).afterOneFileWrite(t.filename)}))),await lifecycleHooks(o.hooks).afterAllFileWrite(n.map((e=>e.filename))),n):n}if(o.watch)return createWatcher(n,a);const i=await executeCodegen(n);return await a(i),lifecycleHooks(o.hooks).beforeDone(),i}function shouldOverwrite(e,t){const n=void 0===e.overwrite||!!e.overwrite,o=e.generates[t];return o?isConfiguredOutput(o)&&"boolean"==typeof o.overwrite?o.overwrite:n:(debugLog(`Couldn't find a config of ${t}`),n)}function isConfiguredOutput(e){return void 0!==e.plugins}const YAML=require("json-to-pretty-yaml");function writeConfig(e,t){const n="json"===(e.config.toLocaleLowerCase().endsWith(".json")?"json":"yml")?JSON.stringify(t):YAML.stringify(t),o=path.resolve(process.cwd(),e.config),r=path.relative(process.cwd(),e.config);return fs.writeFileSync(o,n,{encoding:"utf-8"}),{relativePath:r,fullPath:o}}function writePackage(e,t){const n=path.resolve(process.cwd(),"package.json"),o=fs.readFileSync(n,{encoding:"utf-8"}),r=JSON.parse(o),{indent:a}=detectIndent(o);let i;r.scripts||(r.scripts={}),r.scripts[e.script]=`graphql-codegen --config ${t}`,r.devDependencies||(r.devDependencies={});try{i=require("../../package.json").version}catch(e){i=require("./package.json").version}e.plugins.forEach((e=>{r.devDependencies[e.package]=i})),e.introspection&&(r.devDependencies["@graphql-codegen/introspection"]=i),fs.writeFileSync(n,JSON.stringify(r,null,a))}function bold(e){return chalk.bold(e)}function grey(e){return chalk.grey(e)}function italic(e){return chalk.italic(e)}var Tags;!function(e){e.browser="Browser",e.node="Node",e.typescript="TypeScript",e.flow="Flow",e.angular="Angular",e.stencil="Stencil",e.react="React"}(Tags||(Tags={}));const plugins=[{name:`TypeScript ${italic("(required by other typescript plugins)")}`,package:"@graphql-codegen/typescript",value:"typescript",pathInRepo:"typescript/typescript",available:hasTag(Tags.typescript),shouldBeSelected:e=>oneOf(e,Tags.angular,Tags.stencil)||allOf(e,Tags.typescript,Tags.react)||noneOf(e,Tags.flow),defaultExtension:".ts"},{name:`TypeScript Operations ${italic("(operations and fragments)")}`,package:"@graphql-codegen/typescript-operations",value:"typescript-operations",pathInRepo:"typescript/operations",available:e=>allOf(e,Tags.browser,Tags.typescript),shouldBeSelected:e=>oneOf(e,Tags.angular,Tags.stencil)||allOf(e,Tags.typescript,Tags.react),defaultExtension:".ts"},{name:`TypeScript Resolvers ${italic("(strongly typed resolve functions)")}`,package:"@graphql-codegen/typescript-resolvers",value:"typescript-resolvers",pathInRepo:"typescript/resolvers",available:e=>allOf(e,Tags.node,Tags.typescript),shouldBeSelected:e=>noneOf(e,Tags.flow),defaultExtension:".ts"},{name:`Flow ${italic("(required by other flow plugins)")}`,package:"@graphql-codegen/flow",value:"flow",pathInRepo:"flow/flow",available:hasTag(Tags.flow),shouldBeSelected:e=>noneOf(e,Tags.typescript),defaultExtension:".js"},{name:`Flow Operations ${italic("(operations and fragments)")}`,package:"@graphql-codegen/flow-operations",value:"flow-operations",pathInRepo:"flow/operations",available:e=>allOf(e,Tags.browser,Tags.flow),shouldBeSelected:e=>noneOf(e,Tags.typescript),defaultExtension:".js"},{name:`Flow Resolvers ${italic("(strongly typed resolve functions)")}`,package:"@graphql-codegen/flow-resolvers",value:"flow-resolvers",pathInRepo:"flow/resolvers",available:e=>allOf(e,Tags.node,Tags.flow),shouldBeSelected:e=>noneOf(e,Tags.typescript),defaultExtension:".js"},{name:`TypeScript Apollo Angular ${italic("(typed GQL services)")}`,package:"@graphql-codegen/typescript-apollo-angular",value:"typescript-apollo-angular",pathInRepo:"typescript/apollo-angular",available:hasTag(Tags.angular),shouldBeSelected:()=>!0,defaultExtension:".js"},{name:`TypeScript React Apollo ${italic("(typed components and HOCs)")}`,package:"@graphql-codegen/typescript-react-apollo",value:"typescript-react-apollo",pathInRepo:"typescript/react-apollo",available:e=>allOf(e,Tags.react,Tags.typescript),shouldBeSelected:()=>!0,defaultExtension:".tsx"},{name:`TypeScript Stencil Apollo ${italic("(typed components)")}`,package:"@graphql-codegen/typescript-stencil-apollo",value:"typescript-stencil-apollo",pathInRepo:"typescript/stencil-apollo",available:hasTag(Tags.stencil),shouldBeSelected:()=>!0,defaultExtension:".tsx"},{name:`TypeScript MongoDB ${italic("(typed MongoDB objects)")}`,package:"@graphql-codegen/typescript-mongodb",value:"typescript-mongodb",pathInRepo:"typescript/mongodb",available:e=>allOf(e,Tags.node,Tags.typescript),shouldBeSelected:()=>!1,defaultExtension:".ts"},{name:`TypeScript GraphQL files modules ${italic("(declarations for .graphql files)")}`,package:"@graphql-codegen/typescript-graphql-files-modules",value:"typescript-graphql-files-modules",pathInRepo:"typescript/graphql-files-modules",available:e=>allOf(e,Tags.browser,Tags.typescript),shouldBeSelected:()=>!1,defaultExtension:".ts"},{name:`TypeScript GraphQL document nodes ${italic("(embedded GraphQL document)")}`,package:"@graphql-codegen/typescript-document-nodes",value:"typescript-document-nodes",pathInRepo:"typescript/document-nodes",available:e=>allOf(e,Tags.typescript),shouldBeSelected:()=>!1,defaultExtension:".ts"},{name:`Introspection Fragment Matcher ${italic("(for Apollo Client)")}`,package:"@graphql-codegen/fragment-matcher",value:"fragment-matcher",pathInRepo:"other/fragment-matcher",available:hasTag(Tags.browser),shouldBeSelected:()=>!1,defaultExtension:".ts"}];function hasTag(e){return t=>t.includes(e)}function oneOf(e,...t){return e.some((e=>t.includes(e)))}function noneOf(e,...t){return!e.some((e=>t.includes(e)))}function allOf(e,...t){return t.every((t=>e.includes(t)))}function getQuestions(e){return[{type:"checkbox",name:"targets",message:"What type of application are you building?",choices:getApplicationTypeChoices(e),validate:e=>e.length>0},{type:"input",name:"schema",message:"Where is your schema?:",suffix:grey(" (path or url)"),default:"http://localhost:4000",validate:e=>e.length>0},{type:"input",name:"documents",message:"Where are your operations and fragments?:",when:e=>(e.targets=normalizeTargets(e.targets),e.targets.includes(Tags.browser)),default:"src/**/*.graphql",validate:e=>e.length>0},{type:"checkbox",name:"plugins",message:"Pick plugins:",choices:getPluginChoices,validate:e=>e.length>0},{type:"input",name:"output",message:"Where to write the output:",default:getOutputDefaultValue,validate:e=>e.length>0},{type:"confirm",name:"introspection",message:"Do you want to generate an introspection file?"},{type:"input",name:"config",message:"How to name the config file?",default:"codegen.yml",validate:e=>{const t=e.length>0,n=["json","yml","yaml"].some((t=>e.toLocaleLowerCase().endsWith(`.${t}`)));return t&&n}},{type:"input",name:"script",message:"What script in package.json should run the codegen?",validate:e=>e.length>0}]}function getApplicationTypeChoices(e){function t(t){return e.TypeScript?t.push(Tags.typescript):e.Flow?t.push(Tags.flow):t.push(Tags.flow,Tags.typescript),t}return[{name:"Backend - API or server",key:"backend",value:t([Tags.node]),checked:e.Node},{name:"Application built with Angular",key:"angular",value:[Tags.angular,Tags.browser,Tags.typescript],checked:e.Angular},{name:"Application built with React",key:"react",value:t([Tags.react,Tags.browser]),checked:e.React},{name:"Application built with Stencil",key:"stencil",value:[Tags.stencil,Tags.browser,Tags.typescript],checked:e.Stencil},{name:"Application built with other framework or vanilla JS",key:"client",value:[Tags.browser,Tags.typescript,Tags.flow],checked:e.Browser&&!e.Angular&&!e.React&&!e.Stencil}]}function getPluginChoices(e){return plugins.filter((t=>t.available(e.targets))).map((t=>({name:t.name,value:t,checked:t.shouldBeSelected(e.targets)})))}function normalizeTargets(e){return[].concat(...e)}function getOutputDefaultValue(e){return e.plugins.some((e=>".tsx"===e.defaultExtension))?"src/generated/graphql.tsx":e.plugins.some((e=>".ts"===e.defaultExtension))?"src/generated/graphql.ts":"src/generated/graphql.js"}async function guessTargets(){const e=JSON.parse(fs.readFileSync(path.resolve(process.cwd(),"package.json"),{encoding:"utf-8"})),t=Object.keys({...e.dependencies,...e.devDependencies});return{[Tags.angular]:isAngular(t),[Tags.react]:isReact(t),[Tags.stencil]:isStencil(t),[Tags.browser]:!1,[Tags.node]:!1,[Tags.typescript]:isTypescript(t),[Tags.flow]:isFlow(t)}}function isAngular(e){return e.includes("@angular/core")}function isReact(e){return e.includes("react")}function isStencil(e){return e.includes("@stencil/core")}function isTypescript(e){return e.includes("typescript")}function isFlow(e){return e.includes("flow")}function log$1(...e){console.log(...e)}async function init(){log$1(`\n    Welcome to ${bold("GraphQL Code Generator")}!\n    Answer few questions and we will setup everything for you.\n  `);const e=await guessTargets(),t=await inquirer.prompt(getQuestions(e)),n={overwrite:!0,schema:t.schema,documents:t.targets.includes(Tags.browser)?t.documents:null,generates:{[t.output]:{plugins:t.plugins.map((e=>e.value))}}};t.introspection&&addIntrospection(n);const{relativePath:o}=writeConfig(t,n);writePackage(t,o),log$1(`\n    Config file generated at ${bold(o)}\n    \n      ${bold("$ npm install")}\n\n    To install the plugins.\n\n      ${bold(`$ npm run ${t.script}`)}\n\n    To run GraphQL Code Generator.\n  `)}function addIntrospection(e){e.generates["./graphql.schema.json"]={plugins:["introspection"]}}const isBrowser="undefined"!=typeof window&&void 0!==window.document,isNode="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node;function cliError(e,t=!0){let n;if(n=e instanceof Error?e.message||e.toString():"string"==typeof e?e:JSON.stringify(e),console.error(n),t&&isNode)process.exit(1);else if(t&&isBrowser)throw e}function runCli(e){return"init"===e?init():createContext().then((e=>generate(e).catch((async t=>{throw await lifecycleHooks(e.getConfig().hooks).onError(t.toString()),t}))))}exports.CodegenContext=CodegenContext,exports.CodegenExtension=CodegenExtension,exports.cliError=cliError,exports.createContext=createContext,exports.ensureContext=ensureContext,exports.executeCodegen=executeCodegen,exports.findAndLoadGraphQLConfig=findAndLoadGraphQLConfig,exports.generate=generate,exports.init=init,exports.loadContext=loadContext,exports.parseArgv=parseArgv,exports.runCli=runCli,exports.setCommandOptions=setCommandOptions,exports.updateContextWithCliFlags=updateContextWithCliFlags;
//# sourceMappingURL=/sm/557438ec820e4ea72c73217e6091a8deca796f0309f132efed02093c8796f3b9.map