@gql.tada/cli-utils 1.9.1 → 1.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index-chunk.js","sources":["../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/constants.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/errors.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/format.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/utils.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/Command.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/core.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/HelpCommand.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/Cli.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/platform/browser.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Boolean.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/String.mjs","../../src/utils/error.ts","../../src/term/csi.ts","../../src/term/write.ts","../../src/term/symbols.ts","../../src/term/github.ts","../../src/term/tty.ts","../../src/commands/shared/logger.ts","../../src/commands/shared/projects.ts","../../src/commands/shared/utils.ts","../../src/commands/generate-output/logger.ts","../../src/commands/generate-output/runner.ts","../../src/commands/generate-output/index.ts","../../src/commands/generate-persisted/logger.ts","../../src/commands/generate-persisted/runner.ts","../../src/commands/generate-persisted/index.ts","../../../../node_modules/.pnpm/typanion@3.14.0/node_modules/typanion/lib/index.mjs","../../src/commands/generate-schema/runner.ts","../../src/commands/generate-schema/logger.ts","../../src/commands/generate-schema/index.ts","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Array.mjs","../../src/commands/turbo/logger.ts","../../src/commands/turbo/runner.ts","../../src/commands/turbo/index.ts","../../src/commands/scan/module-graph.ts","../../src/commands/scan/fragment-graph.ts","../../src/commands/scan/context.ts","../../src/commands/scan/rules/field-usage.ts","../../src/commands/scan/rules/index.ts","../../src/commands/scan/rules/input-usage.ts","../../src/commands/scan/rules/deprecated-usage.ts","../../src/commands/scan/rules/orphan-fragments.ts","../../src/commands/scan/rules/cross-feature-fragments.ts","../../src/commands/scan/rules/operation-complexity.ts","../../src/commands/scan/rules/fetch-depth.ts","../../src/commands/scan/rules/directive-usage.ts","../../src/commands/scan/output/overview.ts","../../src/commands/scan/schema-util.ts","../../src/commands/scan/output/json.ts","../../src/commands/scan/output/graph.ts","../../src/commands/scan/output/terminal.ts","../../src/commands/scan/logger.ts","../../src/commands/scan/runner.ts","../../src/commands/scan/analyze.ts","../../src/commands/scan/index.ts","../../src/commands/check/logger.ts","../../src/commands/check/runner.ts","../../src/commands/check/index.ts","../../../../node_modules/.pnpm/semiver@1.1.0/node_modules/semiver/dist/semiver.mjs","../../src/utils/semver.ts","../../src/ts/utils.ts","../../src/ts/vendor/typescript-vfs.ts","../../../../node_modules/.pnpm/muggle-string@0.4.1/node_modules/muggle-string/out/binarySearch.js","../../../../node_modules/.pnpm/muggle-string@0.4.1/node_modules/muggle-string/out/track.js","../../../../node_modules/.pnpm/muggle-string@0.4.1/node_modules/muggle-string/out/types.js","../../../../node_modules/.pnpm/muggle-string@0.4.1/node_modules/muggle-string/out/index.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/binarySearch.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/translateOffset.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/sourceMap.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/buildMappings.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/buildStacks.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/index.js","../../src/ts/mapping.ts","../../src/ts/container.ts","../../src/ts/transformers.ts","../../src/ts/factory.ts","../../src/commands/doctor/helpers/fs.ts","../../src/commands/doctor/helpers/graphqlConfig.ts","../../src/commands/doctor/helpers/workspaceRoot.ts","../../src/commands/doctor/helpers/versions.ts","../../src/commands/doctor/helpers/vscode.ts","../../src/commands/doctor/logger.ts","../../src/commands/doctor/runner.ts","../../src/commands/doctor/index.ts","../../src/commands/init/index.ts","../../src/index.ts"],"sourcesContent":["var SpecialToken;\n(function (SpecialToken) {\n SpecialToken[\"StartOfInput\"] = \"\\0\";\n SpecialToken[\"EndOfInput\"] = \"\\u0001\";\n SpecialToken[\"EndOfPartialInput\"] = \"\\u0002\";\n})(SpecialToken || (SpecialToken = {}));\nvar NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"InitialNode\"] = 0] = \"InitialNode\";\n NodeType[NodeType[\"SuccessNode\"] = 1] = \"SuccessNode\";\n NodeType[NodeType[\"ErrorNode\"] = 2] = \"ErrorNode\";\n NodeType[NodeType[\"CustomNode\"] = 3] = \"CustomNode\";\n})(NodeType || (NodeType = {}));\nconst HELP_COMMAND_INDEX = -1;\nconst HELP_REGEX = /^(-h|--help)(?:=([0-9]+))?$/;\nconst OPTION_REGEX = /^(--[a-z]+(?:-[a-z]+)*|-[a-zA-Z]+)$/;\nconst BATCH_REGEX = /^-[a-zA-Z]{2,}$/;\nconst BINDING_REGEX = /^([^=]+)=([\\s\\S]*)$/;\nconst IS_DEBUG = process.env.DEBUG_CLI === `1`;\n\nexport { BATCH_REGEX, BINDING_REGEX, HELP_COMMAND_INDEX, HELP_REGEX, IS_DEBUG, NodeType, OPTION_REGEX, SpecialToken };\n","import { SpecialToken } from './constants.mjs';\n\n/**\n * A generic usage error with the name `UsageError`.\n *\n * It should be used over `Error` only when it's the user's fault.\n */\nclass UsageError extends Error {\n constructor(message) {\n super(message);\n this.clipanion = { type: `usage` };\n this.name = `UsageError`;\n }\n}\nclass UnknownSyntaxError extends Error {\n constructor(input, candidates) {\n super();\n this.input = input;\n this.candidates = candidates;\n this.clipanion = { type: `none` };\n this.name = `UnknownSyntaxError`;\n if (this.candidates.length === 0) {\n this.message = `Command not found, but we're not sure what's the alternative.`;\n }\n else if (this.candidates.every(candidate => candidate.reason !== null && candidate.reason === candidates[0].reason)) {\n const [{ reason }] = this.candidates;\n this.message = `${reason}\\n\\n${this.candidates.map(({ usage }) => `$ ${usage}`).join(`\\n`)}`;\n }\n else if (this.candidates.length === 1) {\n const [{ usage }] = this.candidates;\n this.message = `Command not found; did you mean:\\n\\n$ ${usage}\\n${whileRunning(input)}`;\n }\n else {\n this.message = `Command not found; did you mean one of:\\n\\n${this.candidates.map(({ usage }, index) => {\n return `${`${index}.`.padStart(4)} ${usage}`;\n }).join(`\\n`)}\\n\\n${whileRunning(input)}`;\n }\n }\n}\nclass AmbiguousSyntaxError extends Error {\n constructor(input, usages) {\n super();\n this.input = input;\n this.usages = usages;\n this.clipanion = { type: `none` };\n this.name = `AmbiguousSyntaxError`;\n this.message = `Cannot find which to pick amongst the following alternatives:\\n\\n${this.usages.map((usage, index) => {\n return `${`${index}.`.padStart(4)} ${usage}`;\n }).join(`\\n`)}\\n\\n${whileRunning(input)}`;\n }\n}\nconst whileRunning = (input) => `While running ${input.filter(token => {\n return token !== SpecialToken.EndOfInput && token !== SpecialToken.EndOfPartialInput;\n}).map(token => {\n const json = JSON.stringify(token);\n if (token.match(/\\s/) || token.length === 0 || json !== `\"${token}\"`) {\n return json;\n }\n else {\n return token;\n }\n}).join(` `)}`;\n\nexport { AmbiguousSyntaxError, UnknownSyntaxError, UsageError };\n","const MAX_LINE_LENGTH = 80;\nconst richLine = Array(MAX_LINE_LENGTH).fill(`━`);\nfor (let t = 0; t <= 24; ++t)\n richLine[richLine.length - t] = `\\x1b[38;5;${232 + t}m━`;\nconst richFormat = {\n header: str => `\\x1b[1m━━━ ${str}${str.length < MAX_LINE_LENGTH - 5 ? ` ${richLine.slice(str.length + 5).join(``)}` : `:`}\\x1b[0m`,\n bold: str => `\\x1b[1m${str}\\x1b[22m`,\n error: str => `\\x1b[31m\\x1b[1m${str}\\x1b[22m\\x1b[39m`,\n code: str => `\\x1b[36m${str}\\x1b[39m`,\n};\nconst textFormat = {\n header: str => str,\n bold: str => str,\n error: str => str,\n code: str => str,\n};\nfunction dedent(text) {\n const lines = text.split(`\\n`);\n const nonEmptyLines = lines.filter(line => line.match(/\\S/));\n const indent = nonEmptyLines.length > 0 ? nonEmptyLines.reduce((minLength, line) => Math.min(minLength, line.length - line.trimStart().length), Number.MAX_VALUE) : 0;\n return lines\n .map(line => line.slice(indent).trimRight())\n .join(`\\n`);\n}\n/**\n * Formats markdown text to be displayed to the console. Not all markdown features are supported.\n *\n * @param text The markdown text to format.\n * @param opts.format The format to use.\n * @param opts.paragraphs Whether to cut the text into paragraphs of 80 characters at most.\n */\nfunction formatMarkdownish(text, { format, paragraphs }) {\n // Enforce \\n as newline character\n text = text.replace(/\\r\\n?/g, `\\n`);\n // Remove the indentation, since it got messed up with the JS indentation\n text = dedent(text);\n // Remove surrounding newlines, since they got added for JS formatting\n text = text.replace(/^\\n+|\\n+$/g, ``);\n // List items always end with at least two newlines (in order to not be collapsed)\n text = text.replace(/^(\\s*)-([^\\n]*?)\\n+/gm, `$1-$2\\n\\n`);\n // Single newlines are removed; larger than that are collapsed into one\n text = text.replace(/\\n(\\n)?\\n*/g, ($0, $1) => $1 ? $1 : ` `);\n if (paragraphs) {\n text = text.split(/\\n/).map(paragraph => {\n // Does the paragraph starts with a list?\n const bulletMatch = paragraph.match(/^\\s*[*-][\\t ]+(.*)/);\n if (!bulletMatch)\n // No, cut the paragraphs into segments of 80 characters\n return paragraph.match(/(.{1,80})(?: |$)/g).join(`\\n`);\n const indent = paragraph.length - paragraph.trimStart().length;\n // Yes, cut the paragraphs into segments of (78 - indent) characters (to account for the prefix)\n return bulletMatch[1].match(new RegExp(`(.{1,${78 - indent}})(?: |$)`, `g`)).map((line, index) => {\n return ` `.repeat(indent) + (index === 0 ? `- ` : ` `) + line;\n }).join(`\\n`);\n }).join(`\\n\\n`);\n }\n // Highlight the code segments\n text = text.replace(/(`+)((?:.|[\\n])*?)\\1/g, ($0, $1, $2) => {\n return format.code($1 + $2 + $1);\n });\n // Highlight the bold segments\n text = text.replace(/(\\*\\*)((?:.|[\\n])*?)\\1/g, ($0, $1, $2) => {\n return format.bold($1 + $2 + $1);\n });\n return text ? `${text}\\n` : ``;\n}\n\nexport { formatMarkdownish, richFormat, textFormat };\n","import { UsageError } from '../../errors.mjs';\n\nconst isOptionSymbol = Symbol(`clipanion/isOption`);\nfunction makeCommandOption(spec) {\n // We lie! But it's for the good cause: the cli engine will turn the specs into proper values after instantiation.\n return { ...spec, [isOptionSymbol]: true };\n}\nfunction rerouteArguments(a, b) {\n if (typeof a === `undefined`)\n return [a, b];\n if (typeof a === `object` && a !== null && !Array.isArray(a)) {\n return [undefined, a];\n }\n else {\n return [a, b];\n }\n}\nfunction cleanValidationError(message, { mergeName = false } = {}) {\n const match = message.match(/^([^:]+): (.*)$/m);\n if (!match)\n return `validation failed`;\n let [, path, line] = match;\n if (mergeName)\n line = line[0].toLowerCase() + line.slice(1);\n line = path !== `.` || !mergeName\n ? `${path.replace(/^\\.(\\[|$)/, `$1`)}: ${line}`\n : `: ${line}`;\n return line;\n}\nfunction formatError(message, errors) {\n if (errors.length === 1) {\n return new UsageError(`${message}${cleanValidationError(errors[0], { mergeName: true })}`);\n }\n else {\n return new UsageError(`${message}:\\n${errors.map(error => `\\n- ${cleanValidationError(error)}`).join(``)}`);\n }\n}\nfunction applyValidator(name, value, validator) {\n if (typeof validator === `undefined`)\n return value;\n const errors = [];\n const coercions = [];\n const coercion = (v) => {\n const orig = value;\n value = v;\n return coercion.bind(null, orig);\n };\n const check = validator(value, { errors, coercions, coercion });\n if (!check)\n throw formatError(`Invalid value for ${name}`, errors);\n for (const [, op] of coercions)\n op();\n return value;\n}\n\nexport { applyValidator, cleanValidationError, formatError, isOptionSymbol, makeCommandOption, rerouteArguments };\n","import { formatError, isOptionSymbol } from './options/utils.mjs';\n\n/**\n * Base abstract class for CLI commands. The main thing to remember is to\n * declare an async `execute` member function that will be called when the\n * command is invoked from the CLI, and optionally a `paths` property to\n * declare the set of paths under which the command should be exposed.\n */\nclass Command {\n constructor() {\n /**\n * Predefined that will be set to true if `-h,--help` has been used, in\n * which case `Command#execute` won't be called.\n */\n this.help = false;\n }\n /**\n * Defines the usage information for the given command.\n */\n static Usage(usage) {\n return usage;\n }\n /**\n * Standard error handler which will simply rethrow the error. Can be used\n * to add custom logic to handle errors from the command or simply return\n * the parent class error handling.\n */\n async catch(error) {\n throw error;\n }\n async validateAndExecute() {\n const commandClass = this.constructor;\n const cascade = commandClass.schema;\n if (Array.isArray(cascade)) {\n const { isDict, isUnknown, applyCascade } = await import('typanion');\n const schema = applyCascade(isDict(isUnknown()), cascade);\n const errors = [];\n const coercions = [];\n const check = schema(this, { errors, coercions });\n if (!check)\n throw formatError(`Invalid option schema`, errors);\n for (const [, op] of coercions) {\n op();\n }\n }\n else if (cascade != null) {\n throw new Error(`Invalid command schema`);\n }\n const exitCode = await this.execute();\n if (typeof exitCode !== `undefined`) {\n return exitCode;\n }\n else {\n return 0;\n }\n }\n}\n/**\n * Used to detect option definitions.\n */\nCommand.isOption = isOptionSymbol;\n/**\n * Just an helper to use along with the `paths` fields, to make it\n * clearer that a command is the default one.\n *\n * @example\n * class MyCommand extends Command {\n * static paths = [Command.Default];\n * }\n */\nCommand.Default = [];\n\nexport { Command };\n","import { IS_DEBUG, NodeType, SpecialToken, HELP_COMMAND_INDEX, BATCH_REGEX, BINDING_REGEX, OPTION_REGEX, HELP_REGEX } from './constants.mjs';\nimport { UnknownSyntaxError, AmbiguousSyntaxError } from './errors.mjs';\n\n// ------------------------------------------------------------------------\nfunction debug(str) {\n if (IS_DEBUG) {\n console.log(str);\n }\n}\nconst basicHelpState = {\n candidateUsage: null,\n requiredOptions: [],\n errorMessage: null,\n ignoreOptions: false,\n path: [],\n positionals: [],\n options: [],\n remainder: null,\n selectedIndex: HELP_COMMAND_INDEX,\n tokens: [],\n};\nfunction makeStateMachine() {\n const stateMachine = {\n nodes: [],\n };\n for (let t = 0; t < NodeType.CustomNode; ++t)\n stateMachine.nodes.push(makeNode());\n return stateMachine;\n}\nfunction makeAnyOfMachine(inputs) {\n const output = makeStateMachine();\n const heads = [];\n let offset = output.nodes.length;\n for (const input of inputs) {\n heads.push(offset);\n for (let t = 0; t < input.nodes.length; ++t)\n if (!isTerminalNode(t))\n output.nodes.push(cloneNode(input.nodes[t], offset));\n offset += input.nodes.length - NodeType.CustomNode + 1;\n }\n for (const head of heads)\n registerShortcut(output, NodeType.InitialNode, head);\n return output;\n}\nfunction injectNode(machine, node) {\n machine.nodes.push(node);\n return machine.nodes.length - 1;\n}\nfunction simplifyMachine(input) {\n const visited = new Set();\n const process = (node) => {\n if (visited.has(node))\n return;\n visited.add(node);\n const nodeDef = input.nodes[node];\n for (const transitions of Object.values(nodeDef.statics))\n for (const { to } of transitions)\n process(to);\n for (const [, { to }] of nodeDef.dynamics)\n process(to);\n for (const { to } of nodeDef.shortcuts)\n process(to);\n const shortcuts = new Set(nodeDef.shortcuts.map(({ to }) => to));\n while (nodeDef.shortcuts.length > 0) {\n const { to } = nodeDef.shortcuts.shift();\n const toDef = input.nodes[to];\n for (const [segment, transitions] of Object.entries(toDef.statics)) {\n const store = !Object.prototype.hasOwnProperty.call(nodeDef.statics, segment)\n ? nodeDef.statics[segment] = []\n : nodeDef.statics[segment];\n for (const transition of transitions) {\n if (!store.some(({ to }) => transition.to === to)) {\n store.push(transition);\n }\n }\n }\n for (const [test, transition] of toDef.dynamics)\n if (!nodeDef.dynamics.some(([otherTest, { to }]) => test === otherTest && transition.to === to))\n nodeDef.dynamics.push([test, transition]);\n for (const transition of toDef.shortcuts) {\n if (!shortcuts.has(transition.to)) {\n nodeDef.shortcuts.push(transition);\n shortcuts.add(transition.to);\n }\n }\n }\n };\n process(NodeType.InitialNode);\n}\nfunction debugMachine(machine, { prefix = `` } = {}) {\n // Don't iterate unless it's needed\n if (IS_DEBUG) {\n debug(`${prefix}Nodes are:`);\n for (let t = 0; t < machine.nodes.length; ++t) {\n debug(`${prefix} ${t}: ${JSON.stringify(machine.nodes[t])}`);\n }\n }\n}\nfunction runMachineInternal(machine, input, partial = false) {\n debug(`Running a vm on ${JSON.stringify(input)}`);\n let branches = [{\n node: NodeType.InitialNode,\n state: {\n candidateUsage: null,\n requiredOptions: [],\n errorMessage: null,\n ignoreOptions: false,\n options: [],\n path: [],\n positionals: [],\n remainder: null,\n selectedIndex: null,\n tokens: [],\n },\n }];\n debugMachine(machine, { prefix: ` ` });\n const tokens = [SpecialToken.StartOfInput, ...input];\n for (let t = 0; t < tokens.length; ++t) {\n const segment = tokens[t];\n const isEOI = segment === SpecialToken.EndOfInput || segment === SpecialToken.EndOfPartialInput;\n // The -1 is because we added a START_OF_INPUT token\n const segmentIndex = t - 1;\n debug(` Processing ${JSON.stringify(segment)}`);\n const nextBranches = [];\n for (const { node, state } of branches) {\n debug(` Current node is ${node}`);\n const nodeDef = machine.nodes[node];\n if (node === NodeType.ErrorNode) {\n nextBranches.push({ node, state });\n continue;\n }\n console.assert(nodeDef.shortcuts.length === 0, `Shortcuts should have been eliminated by now`);\n const hasExactMatch = Object.prototype.hasOwnProperty.call(nodeDef.statics, segment);\n if (!partial || t < tokens.length - 1 || hasExactMatch) {\n if (hasExactMatch) {\n const transitions = nodeDef.statics[segment];\n for (const { to, reducer } of transitions) {\n nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });\n debug(` Static transition to ${to} found`);\n }\n }\n else {\n debug(` No static transition found`);\n }\n }\n else {\n let hasMatches = false;\n for (const candidate of Object.keys(nodeDef.statics)) {\n if (!candidate.startsWith(segment))\n continue;\n if (segment === candidate) {\n for (const { to, reducer } of nodeDef.statics[candidate]) {\n nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });\n debug(` Static transition to ${to} found`);\n }\n }\n else {\n for (const { to } of nodeDef.statics[candidate]) {\n nextBranches.push({ node: to, state: { ...state, remainder: candidate.slice(segment.length) } });\n debug(` Static transition to ${to} found (partial match)`);\n }\n }\n hasMatches = true;\n }\n if (!hasMatches) {\n debug(` No partial static transition found`);\n }\n }\n if (!isEOI) {\n for (const [test, { to, reducer }] of nodeDef.dynamics) {\n if (execute(tests, test, state, segment, segmentIndex)) {\n nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });\n debug(` Dynamic transition to ${to} found (via ${test})`);\n }\n }\n }\n }\n if (nextBranches.length === 0 && isEOI && input.length === 1) {\n return [{\n node: NodeType.InitialNode,\n state: basicHelpState,\n }];\n }\n if (nextBranches.length === 0) {\n throw new UnknownSyntaxError(input, branches.filter(({ node }) => {\n return node !== NodeType.ErrorNode;\n }).map(({ state }) => {\n return { usage: state.candidateUsage, reason: null };\n }));\n }\n if (nextBranches.every(({ node }) => node === NodeType.ErrorNode)) {\n throw new UnknownSyntaxError(input, nextBranches.map(({ state }) => {\n return { usage: state.candidateUsage, reason: state.errorMessage };\n }));\n }\n branches = trimSmallerBranches(nextBranches);\n }\n if (branches.length > 0) {\n debug(` Results:`);\n for (const branch of branches) {\n debug(` - ${branch.node} -> ${JSON.stringify(branch.state)}`);\n }\n }\n else {\n debug(` No results`);\n }\n return branches;\n}\nfunction runMachine(machine, input, { endToken = SpecialToken.EndOfInput } = {}) {\n const branches = runMachineInternal(machine, [...input, endToken]);\n return selectBestState(input, branches.map(({ state }) => {\n return state;\n }));\n}\nfunction trimSmallerBranches(branches) {\n let maxPathSize = 0;\n for (const { state } of branches)\n if (state.path.length > maxPathSize)\n maxPathSize = state.path.length;\n return branches.filter(({ state }) => {\n return state.path.length === maxPathSize;\n });\n}\nfunction selectBestState(input, states) {\n const terminalStates = states.filter(state => {\n return state.selectedIndex !== null;\n });\n if (terminalStates.length === 0)\n throw new Error();\n const requiredOptionsSetStates = terminalStates.filter(state => state.selectedIndex === HELP_COMMAND_INDEX || state.requiredOptions.every(names => names.some(name => state.options.find(opt => opt.name === name))));\n if (requiredOptionsSetStates.length === 0) {\n throw new UnknownSyntaxError(input, terminalStates.map(state => ({\n usage: state.candidateUsage,\n reason: null,\n })));\n }\n let maxPathSize = 0;\n for (const state of requiredOptionsSetStates)\n if (state.path.length > maxPathSize)\n maxPathSize = state.path.length;\n const bestPathBranches = requiredOptionsSetStates.filter(state => {\n return state.path.length === maxPathSize;\n });\n const getPositionalCount = (state) => state.positionals.filter(({ extra }) => {\n return !extra;\n }).length + state.options.length;\n const statesWithPositionalCount = bestPathBranches.map(state => {\n return { state, positionalCount: getPositionalCount(state) };\n });\n let maxPositionalCount = 0;\n for (const { positionalCount } of statesWithPositionalCount)\n if (positionalCount > maxPositionalCount)\n maxPositionalCount = positionalCount;\n const bestPositionalStates = statesWithPositionalCount.filter(({ positionalCount }) => {\n return positionalCount === maxPositionalCount;\n }).map(({ state }) => {\n return state;\n });\n const fixedStates = aggregateHelpStates(bestPositionalStates);\n if (fixedStates.length > 1)\n throw new AmbiguousSyntaxError(input, fixedStates.map(state => state.candidateUsage));\n return fixedStates[0];\n}\nfunction aggregateHelpStates(states) {\n const notHelps = [];\n const helps = [];\n for (const state of states) {\n if (state.selectedIndex === HELP_COMMAND_INDEX) {\n helps.push(state);\n }\n else {\n notHelps.push(state);\n }\n }\n if (helps.length > 0) {\n notHelps.push({\n ...basicHelpState,\n path: findCommonPrefix(...helps.map(state => state.path)),\n options: helps.reduce((options, state) => options.concat(state.options), []),\n });\n }\n return notHelps;\n}\nfunction findCommonPrefix(firstPath, secondPath, ...rest) {\n if (secondPath === undefined)\n return Array.from(firstPath);\n return findCommonPrefix(firstPath.filter((segment, i) => segment === secondPath[i]), ...rest);\n}\nfunction makeNode() {\n return {\n dynamics: [],\n shortcuts: [],\n statics: {},\n };\n}\nfunction isTerminalNode(node) {\n return node === NodeType.SuccessNode || node === NodeType.ErrorNode;\n}\nfunction cloneTransition(input, offset = 0) {\n const to = !isTerminalNode(input.to)\n ? input.to >= NodeType.CustomNode\n ? input.to + offset - NodeType.CustomNode + 1\n : input.to + offset\n : input.to;\n return {\n to,\n reducer: input.reducer,\n };\n}\nfunction cloneNode(input, offset = 0) {\n const output = makeNode();\n for (const [test, transition] of input.dynamics)\n output.dynamics.push([test, cloneTransition(transition, offset)]);\n for (const transition of input.shortcuts)\n output.shortcuts.push(cloneTransition(transition, offset));\n for (const [segment, transitions] of Object.entries(input.statics))\n output.statics[segment] = transitions.map(transition => cloneTransition(transition, offset));\n return output;\n}\nfunction registerDynamic(machine, from, test, to, reducer) {\n machine.nodes[from].dynamics.push([\n test,\n { to, reducer: reducer },\n ]);\n}\nfunction registerShortcut(machine, from, to, reducer) {\n machine.nodes[from].shortcuts.push({ to, reducer: reducer });\n}\nfunction registerStatic(machine, from, test, to, reducer) {\n const store = !Object.prototype.hasOwnProperty.call(machine.nodes[from].statics, test)\n ? machine.nodes[from].statics[test] = []\n : machine.nodes[from].statics[test];\n store.push({ to, reducer: reducer });\n}\nfunction execute(store, callback, state, segment, segmentIndex) {\n // TypeScript's control flow can't properly narrow\n // generic conditionals for some mysterious reason\n if (Array.isArray(callback)) {\n const [name, ...args] = callback;\n return store[name](state, segment, segmentIndex, ...args);\n }\n else {\n return store[callback](state, segment, segmentIndex);\n }\n}\nconst tests = {\n always: () => {\n return true;\n },\n isOptionLike: (state, segment) => {\n return !state.ignoreOptions && (segment !== `-` && segment.startsWith(`-`));\n },\n isNotOptionLike: (state, segment) => {\n return state.ignoreOptions || segment === `-` || !segment.startsWith(`-`);\n },\n isOption: (state, segment, segmentIndex, name) => {\n return !state.ignoreOptions && segment === name;\n },\n isBatchOption: (state, segment, segmentIndex, names) => {\n return !state.ignoreOptions && BATCH_REGEX.test(segment) && [...segment.slice(1)].every(name => names.has(`-${name}`));\n },\n isBoundOption: (state, segment, segmentIndex, names, options) => {\n const optionParsing = segment.match(BINDING_REGEX);\n return !state.ignoreOptions && !!optionParsing && OPTION_REGEX.test(optionParsing[1]) && names.has(optionParsing[1])\n // Disallow bound options with no arguments (i.e. booleans)\n && options.filter(opt => opt.nameSet.includes(optionParsing[1])).every(opt => opt.allowBinding);\n },\n isNegatedOption: (state, segment, segmentIndex, name) => {\n return !state.ignoreOptions && segment === `--no-${name.slice(2)}`;\n },\n isHelp: (state, segment) => {\n return !state.ignoreOptions && HELP_REGEX.test(segment);\n },\n isUnsupportedOption: (state, segment, segmentIndex, names) => {\n return !state.ignoreOptions && segment.startsWith(`-`) && OPTION_REGEX.test(segment) && !names.has(segment);\n },\n isInvalidOption: (state, segment) => {\n return !state.ignoreOptions && segment.startsWith(`-`) && !OPTION_REGEX.test(segment);\n },\n};\nconst reducers = {\n setCandidateState: (state, segment, segmentIndex, candidateState) => {\n return { ...state, ...candidateState };\n },\n setSelectedIndex: (state, segment, segmentIndex, index) => {\n return { ...state, selectedIndex: index };\n },\n pushBatch: (state, segment, segmentIndex, names) => {\n const options = state.options.slice();\n const tokens = state.tokens.slice();\n for (let t = 1; t < segment.length; ++t) {\n const name = names.get(`-${segment[t]}`);\n const slice = t === 1 ? [0, 2] : [t, t + 1];\n options.push({ name, value: true });\n tokens.push({ segmentIndex, type: `option`, option: name, slice });\n }\n return { ...state, options, tokens };\n },\n pushBound: (state, segment, segmentIndex) => {\n const [, name, value] = segment.match(BINDING_REGEX);\n const options = state.options.concat({ name, value });\n const tokens = state.tokens.concat([\n { segmentIndex, type: `option`, slice: [0, name.length], option: name },\n { segmentIndex, type: `assign`, slice: [name.length, name.length + 1] },\n { segmentIndex, type: `value`, slice: [name.length + 1, name.length + value.length + 1] },\n ]);\n return { ...state, options, tokens };\n },\n pushPath: (state, segment, segmentIndex) => {\n const path = state.path.concat(segment);\n const tokens = state.tokens.concat({ segmentIndex, type: `path` });\n return { ...state, path, tokens };\n },\n pushPositional: (state, segment, segmentIndex) => {\n const positionals = state.positionals.concat({ value: segment, extra: false });\n const tokens = state.tokens.concat({ segmentIndex, type: `positional` });\n return { ...state, positionals, tokens };\n },\n pushExtra: (state, segment, segmentIndex) => {\n const positionals = state.positionals.concat({ value: segment, extra: true });\n const tokens = state.tokens.concat({ segmentIndex, type: `positional` });\n return { ...state, positionals, tokens };\n },\n pushExtraNoLimits: (state, segment, segmentIndex) => {\n const positionals = state.positionals.concat({ value: segment, extra: NoLimits });\n const tokens = state.tokens.concat({ segmentIndex, type: `positional` });\n return { ...state, positionals, tokens };\n },\n pushTrue: (state, segment, segmentIndex, name) => {\n const options = state.options.concat({ name, value: true });\n const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: name });\n return { ...state, options, tokens };\n },\n pushFalse: (state, segment, segmentIndex, name) => {\n const options = state.options.concat({ name, value: false });\n const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: name });\n return { ...state, options, tokens };\n },\n pushUndefined: (state, segment, segmentIndex, name) => {\n const options = state.options.concat({ name: segment, value: undefined });\n const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: segment });\n return { ...state, options, tokens };\n },\n pushStringValue: (state, segment, segmentIndex) => {\n var _a;\n const lastOption = state.options[state.options.length - 1];\n const options = state.options.slice();\n const tokens = state.tokens.concat({ segmentIndex, type: `value` });\n lastOption.value = ((_a = lastOption.value) !== null && _a !== void 0 ? _a : []).concat([segment]);\n return { ...state, options, tokens };\n },\n setStringValue: (state, segment, segmentIndex) => {\n const lastOption = state.options[state.options.length - 1];\n const options = state.options.slice();\n const tokens = state.tokens.concat({ segmentIndex, type: `value` });\n lastOption.value = segment;\n return { ...state, options, tokens };\n },\n inhibateOptions: (state) => {\n return { ...state, ignoreOptions: true };\n },\n useHelp: (state, segment, segmentIndex, command) => {\n const [, /* name */ , index] = segment.match(HELP_REGEX);\n if (typeof index !== `undefined`) {\n return { ...state, options: [{ name: `-c`, value: String(command) }, { name: `-i`, value: index }] };\n }\n else {\n return { ...state, options: [{ name: `-c`, value: String(command) }] };\n }\n },\n setError: (state, segment, segmentIndex, errorMessage) => {\n if (segment === SpecialToken.EndOfInput || segment === SpecialToken.EndOfPartialInput) {\n return { ...state, errorMessage: `${errorMessage}.` };\n }\n else {\n return { ...state, errorMessage: `${errorMessage} (\"${segment}\").` };\n }\n },\n setOptionArityError: (state, segment) => {\n const lastOption = state.options[state.options.length - 1];\n return { ...state, errorMessage: `Not enough arguments to option ${lastOption.name}.` };\n },\n};\n// ------------------------------------------------------------------------\nconst NoLimits = Symbol();\nclass CommandBuilder {\n constructor(cliIndex, cliOpts) {\n this.allOptionNames = new Map();\n this.arity = { leading: [], trailing: [], extra: [], proxy: false };\n this.options = [];\n this.paths = [];\n this.cliIndex = cliIndex;\n this.cliOpts = cliOpts;\n }\n addPath(path) {\n this.paths.push(path);\n }\n setArity({ leading = this.arity.leading, trailing = this.arity.trailing, extra = this.arity.extra, proxy = this.arity.proxy }) {\n Object.assign(this.arity, { leading, trailing, extra, proxy });\n }\n addPositional({ name = `arg`, required = true } = {}) {\n if (!required && this.arity.extra === NoLimits)\n throw new Error(`Optional parameters cannot be declared when using .rest() or .proxy()`);\n if (!required && this.arity.trailing.length > 0)\n throw new Error(`Optional parameters cannot be declared after the required trailing positional arguments`);\n if (!required && this.arity.extra !== NoLimits) {\n this.arity.extra.push(name);\n }\n else if (this.arity.extra !== NoLimits && this.arity.extra.length === 0) {\n this.arity.leading.push(name);\n }\n else {\n this.arity.trailing.push(name);\n }\n }\n addRest({ name = `arg`, required = 0 } = {}) {\n if (this.arity.extra === NoLimits)\n throw new Error(`Infinite lists cannot be declared multiple times in the same command`);\n if (this.arity.trailing.length > 0)\n throw new Error(`Infinite lists cannot be declared after the required trailing positional arguments`);\n for (let t = 0; t < required; ++t)\n this.addPositional({ name });\n this.arity.extra = NoLimits;\n }\n addProxy({ required = 0 } = {}) {\n this.addRest({ required });\n this.arity.proxy = true;\n }\n addOption({ names: nameSet, description, arity = 0, hidden = false, required = false, allowBinding = true }) {\n if (!allowBinding && arity > 1)\n throw new Error(`The arity cannot be higher than 1 when the option only supports the --arg=value syntax`);\n if (!Number.isInteger(arity))\n throw new Error(`The arity must be an integer, got ${arity}`);\n if (arity < 0)\n throw new Error(`The arity must be positive, got ${arity}`);\n const preferredName = nameSet.reduce((longestName, name) => {\n return name.length > longestName.length ? name : longestName;\n }, ``);\n for (const name of nameSet)\n this.allOptionNames.set(name, preferredName);\n this.options.push({ preferredName, nameSet, description, arity, hidden, required, allowBinding });\n }\n setContext(context) {\n this.context = context;\n }\n usage({ detailed = true, inlineOptions = true } = {}) {\n const segments = [this.cliOpts.binaryName];\n const detailedOptionList = [];\n if (this.paths.length > 0)\n segments.push(...this.paths[0]);\n if (detailed) {\n for (const { preferredName, nameSet, arity, hidden, description, required } of this.options) {\n if (hidden)\n continue;\n const args = [];\n for (let t = 0; t < arity; ++t)\n args.push(` #${t}`);\n const definition = `${nameSet.join(`,`)}${args.join(``)}`;\n if (!inlineOptions && description) {\n detailedOptionList.push({ preferredName, nameSet, definition, description, required });\n }\n else {\n segments.push(required ? `<${definition}>` : `[${definition}]`);\n }\n }\n segments.push(...this.arity.leading.map(name => `<${name}>`));\n if (this.arity.extra === NoLimits)\n segments.push(`...`);\n else\n segments.push(...this.arity.extra.map(name => `[${name}]`));\n segments.push(...this.arity.trailing.map(name => `<${name}>`));\n }\n const usage = segments.join(` `);\n return { usage, options: detailedOptionList };\n }\n compile() {\n if (typeof this.context === `undefined`)\n throw new Error(`Assertion failed: No context attached`);\n const machine = makeStateMachine();\n let firstNode = NodeType.InitialNode;\n const candidateUsage = this.usage().usage;\n const requiredOptions = this.options\n .filter(opt => opt.required)\n .map(opt => opt.nameSet);\n firstNode = injectNode(machine, makeNode());\n registerStatic(machine, NodeType.InitialNode, SpecialToken.StartOfInput, firstNode, [`setCandidateState`, { candidateUsage, requiredOptions }]);\n const positionalArgument = this.arity.proxy\n ? `always`\n : `isNotOptionLike`;\n const paths = this.paths.length > 0\n ? this.paths\n : [[]];\n for (const path of paths) {\n let lastPathNode = firstNode;\n // We allow options to be specified before the path. Note that we\n // only do this when there is a path, otherwise there would be\n // some redundancy with the options attached later.\n if (path.length > 0) {\n const optionPathNode = injectNode(machine, makeNode());\n registerShortcut(machine, lastPathNode, optionPathNode);\n this.registerOptions(machine, optionPathNode);\n lastPathNode = optionPathNode;\n }\n for (let t = 0; t < path.length; ++t) {\n const nextPathNode = injectNode(machine, makeNode());\n registerStatic(machine, lastPathNode, path[t], nextPathNode, `pushPath`);\n lastPathNode = nextPathNode;\n if (t + 1 < path.length) {\n // Allow to pass `-h` (without anything after it) after each part of a path.\n // Note that we do not do this for the last part, otherwise there would be\n // some redundancy with the `useHelp` attached later.\n const helpNode = injectNode(machine, makeNode());\n registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]);\n registerStatic(machine, helpNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, HELP_COMMAND_INDEX]);\n }\n }\n if (this.arity.leading.length > 0 || !this.arity.proxy) {\n const helpNode = injectNode(machine, makeNode());\n registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]);\n registerDynamic(machine, helpNode, `always`, helpNode, `pushExtra`);\n registerStatic(machine, helpNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, HELP_COMMAND_INDEX]);\n this.registerOptions(machine, lastPathNode);\n }\n if (this.arity.leading.length > 0) {\n registerStatic(machine, lastPathNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, lastPathNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n let lastLeadingNode = lastPathNode;\n for (let t = 0; t < this.arity.leading.length; ++t) {\n const nextLeadingNode = injectNode(machine, makeNode());\n if (!this.arity.proxy || t + 1 !== this.arity.leading.length)\n this.registerOptions(machine, nextLeadingNode);\n if (this.arity.trailing.length > 0 || t + 1 !== this.arity.leading.length) {\n registerStatic(machine, nextLeadingNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, nextLeadingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n registerDynamic(machine, lastLeadingNode, `isNotOptionLike`, nextLeadingNode, `pushPositional`);\n lastLeadingNode = nextLeadingNode;\n }\n let lastExtraNode = lastLeadingNode;\n if (this.arity.extra === NoLimits || this.arity.extra.length > 0) {\n const extraShortcutNode = injectNode(machine, makeNode());\n registerShortcut(machine, lastLeadingNode, extraShortcutNode);\n if (this.arity.extra === NoLimits) {\n const extraNode = injectNode(machine, makeNode());\n if (!this.arity.proxy)\n this.registerOptions(machine, extraNode);\n registerDynamic(machine, lastLeadingNode, positionalArgument, extraNode, `pushExtraNoLimits`);\n registerDynamic(machine, extraNode, positionalArgument, extraNode, `pushExtraNoLimits`);\n registerShortcut(machine, extraNode, extraShortcutNode);\n }\n else {\n for (let t = 0; t < this.arity.extra.length; ++t) {\n const nextExtraNode = injectNode(machine, makeNode());\n if (!this.arity.proxy || t > 0)\n this.registerOptions(machine, nextExtraNode);\n registerDynamic(machine, lastExtraNode, positionalArgument, nextExtraNode, `pushExtra`);\n registerShortcut(machine, nextExtraNode, extraShortcutNode);\n lastExtraNode = nextExtraNode;\n }\n }\n lastExtraNode = extraShortcutNode;\n }\n if (this.arity.trailing.length > 0) {\n registerStatic(machine, lastExtraNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, lastExtraNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n let lastTrailingNode = lastExtraNode;\n for (let t = 0; t < this.arity.trailing.length; ++t) {\n const nextTrailingNode = injectNode(machine, makeNode());\n if (!this.arity.proxy)\n this.registerOptions(machine, nextTrailingNode);\n if (t + 1 < this.arity.trailing.length) {\n registerStatic(machine, nextTrailingNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, nextTrailingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n registerDynamic(machine, lastTrailingNode, `isNotOptionLike`, nextTrailingNode, `pushPositional`);\n lastTrailingNode = nextTrailingNode;\n }\n registerDynamic(machine, lastTrailingNode, positionalArgument, NodeType.ErrorNode, [`setError`, `Extraneous positional argument`]);\n registerStatic(machine, lastTrailingNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n registerStatic(machine, lastTrailingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n return {\n machine,\n context: this.context,\n };\n }\n registerOptions(machine, node) {\n registerDynamic(machine, node, [`isOption`, `--`], node, `inhibateOptions`);\n registerDynamic(machine, node, [`isBatchOption`, this.allOptionNames], node, [`pushBatch`, this.allOptionNames]);\n registerDynamic(machine, node, [`isBoundOption`, this.allOptionNames, this.options], node, `pushBound`);\n registerDynamic(machine, node, [`isUnsupportedOption`, this.allOptionNames], NodeType.ErrorNode, [`setError`, `Unsupported option name`]);\n registerDynamic(machine, node, [`isInvalidOption`], NodeType.ErrorNode, [`setError`, `Invalid option name`]);\n for (const option of this.options) {\n if (option.arity === 0) {\n for (const name of option.nameSet) {\n registerDynamic(machine, node, [`isOption`, name], node, [`pushTrue`, option.preferredName]);\n if (name.startsWith(`--`) && !name.startsWith(`--no-`)) {\n registerDynamic(machine, node, [`isNegatedOption`, name], node, [`pushFalse`, option.preferredName]);\n }\n }\n }\n else {\n // We inject a new node at the end of the state machine\n let lastNode = injectNode(machine, makeNode());\n // We register transitions from the starting node to this new node\n for (const name of option.nameSet)\n registerDynamic(machine, node, [`isOption`, name], lastNode, [`pushUndefined`, option.preferredName]);\n // For each argument, we inject a new node at the end and we\n // register a transition from the current node to this new node\n for (let t = 0; t < option.arity; ++t) {\n const nextNode = injectNode(machine, makeNode());\n // We can provide better errors when another option or EndOfInput is encountered\n registerStatic(machine, lastNode, SpecialToken.EndOfInput, NodeType.ErrorNode, `setOptionArityError`);\n registerStatic(machine, lastNode, SpecialToken.EndOfPartialInput, NodeType.ErrorNode, `setOptionArityError`);\n registerDynamic(machine, lastNode, `isOptionLike`, NodeType.ErrorNode, `setOptionArityError`);\n // If the option has a single argument, no need to store it in an array\n const action = option.arity === 1\n ? `setStringValue`\n : `pushStringValue`;\n registerDynamic(machine, lastNode, `isNotOptionLike`, nextNode, action);\n lastNode = nextNode;\n }\n // In the end, we register a shortcut from\n // the last node back to the starting node\n registerShortcut(machine, lastNode, node);\n }\n }\n }\n}\nclass CliBuilder {\n constructor({ binaryName = `...` } = {}) {\n this.builders = [];\n this.opts = { binaryName };\n }\n static build(cbs, opts = {}) {\n return new CliBuilder(opts).commands(cbs).compile();\n }\n getBuilderByIndex(n) {\n if (!(n >= 0 && n < this.builders.length))\n throw new Error(`Assertion failed: Out-of-bound command index (${n})`);\n return this.builders[n];\n }\n commands(cbs) {\n for (const cb of cbs)\n cb(this.command());\n return this;\n }\n command() {\n const builder = new CommandBuilder(this.builders.length, this.opts);\n this.builders.push(builder);\n return builder;\n }\n compile() {\n const machines = [];\n const contexts = [];\n for (const builder of this.builders) {\n const { machine, context } = builder.compile();\n machines.push(machine);\n contexts.push(context);\n }\n const machine = makeAnyOfMachine(machines);\n simplifyMachine(machine);\n return {\n machine,\n contexts,\n process: (input, { partial } = {}) => {\n const endToken = partial\n ? SpecialToken.EndOfPartialInput\n : SpecialToken.EndOfInput;\n return runMachine(machine, input, { endToken });\n },\n };\n }\n}\n\nexport { CliBuilder, CommandBuilder, NoLimits, aggregateHelpStates, cloneNode, cloneTransition, debug, debugMachine, execute, injectNode, isTerminalNode, makeAnyOfMachine, makeNode, makeStateMachine, reducers, registerDynamic, registerShortcut, registerStatic, runMachineInternal, selectBestState, simplifyMachine, tests, trimSmallerBranches };\n","import { Command } from './Command.mjs';\n\nclass HelpCommand extends Command {\n constructor(contexts) {\n super();\n this.contexts = contexts;\n this.commands = [];\n }\n static from(state, contexts) {\n const command = new HelpCommand(contexts);\n command.path = state.path;\n for (const opt of state.options) {\n switch (opt.name) {\n case `-c`:\n {\n command.commands.push(Number(opt.value));\n }\n break;\n case `-i`:\n {\n command.index = Number(opt.value);\n }\n break;\n }\n }\n return command;\n }\n async execute() {\n let commands = this.commands;\n if (typeof this.index !== `undefined` && this.index >= 0 && this.index < commands.length)\n commands = [commands[this.index]];\n if (commands.length === 0) {\n this.context.stdout.write(this.cli.usage());\n }\n else if (commands.length === 1) {\n this.context.stdout.write(this.cli.usage(this.contexts[commands[0]].commandClass, { detailed: true }));\n }\n else if (commands.length > 1) {\n this.context.stdout.write(`Multiple commands match your selection:\\n`);\n this.context.stdout.write(`\\n`);\n let index = 0;\n for (const command of this.commands)\n this.context.stdout.write(this.cli.usage(this.contexts[command].commandClass, { prefix: `${index++}. `.padStart(5) }));\n this.context.stdout.write(`\\n`);\n this.context.stdout.write(`Run again with -h=<index> to see the longer details of any of those commands.\\n`);\n }\n }\n}\n\nexport { HelpCommand };\n","import { HELP_COMMAND_INDEX } from '../constants.mjs';\nimport { CliBuilder } from '../core.mjs';\nimport { formatMarkdownish, richFormat, textFormat } from '../format.mjs';\nimport { getCaptureActivator, getDefaultColorDepth } from '../platform/node.mjs';\nimport { Command } from './Command.mjs';\nimport { HelpCommand } from './HelpCommand.mjs';\n\nconst errorCommandSymbol = Symbol(`clipanion/errorCommand`);\nasync function runExit(...args) {\n const { resolvedOptions, resolvedCommandClasses, resolvedArgv, resolvedContext, } = resolveRunParameters(args);\n const cli = Cli.from(resolvedCommandClasses, resolvedOptions);\n return cli.runExit(resolvedArgv, resolvedContext);\n}\nasync function run(...args) {\n const { resolvedOptions, resolvedCommandClasses, resolvedArgv, resolvedContext, } = resolveRunParameters(args);\n const cli = Cli.from(resolvedCommandClasses, resolvedOptions);\n return cli.run(resolvedArgv, resolvedContext);\n}\nfunction resolveRunParameters(args) {\n let resolvedOptions;\n let resolvedCommandClasses;\n let resolvedArgv;\n let resolvedContext;\n if (typeof process !== `undefined` && typeof process.argv !== `undefined`)\n resolvedArgv = process.argv.slice(2);\n switch (args.length) {\n case 1:\n {\n resolvedCommandClasses = args[0];\n }\n break;\n case 2:\n {\n if (args[0] && (args[0].prototype instanceof Command) || Array.isArray(args[0])) {\n resolvedCommandClasses = args[0];\n if (Array.isArray(args[1])) {\n resolvedArgv = args[1];\n }\n else {\n resolvedContext = args[1];\n }\n }\n else {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n }\n }\n break;\n case 3:\n {\n if (Array.isArray(args[2])) {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n resolvedArgv = args[2];\n }\n else if (args[0] && (args[0].prototype instanceof Command) || Array.isArray(args[0])) {\n resolvedCommandClasses = args[0];\n resolvedArgv = args[1];\n resolvedContext = args[2];\n }\n else {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n resolvedContext = args[2];\n }\n }\n break;\n default:\n {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n resolvedArgv = args[2];\n resolvedContext = args[3];\n }\n break;\n }\n if (typeof resolvedArgv === `undefined`)\n throw new Error(`The argv parameter must be provided when running Clipanion outside of a Node context`);\n return {\n resolvedOptions,\n resolvedCommandClasses,\n resolvedArgv,\n resolvedContext,\n };\n}\n/**\n * @template Context The context shared by all commands. Contexts are a set of values, defined when calling the `run`/`runExit` functions from the CLI instance, that will be made available to the commands via `this.context`.\n */\nclass Cli {\n constructor({ binaryLabel, binaryName: binaryNameOpt = `...`, binaryVersion, enableCapture = false, enableColors } = {}) {\n this.registrations = new Map();\n this.builder = new CliBuilder({ binaryName: binaryNameOpt });\n this.binaryLabel = binaryLabel;\n this.binaryName = binaryNameOpt;\n this.binaryVersion = binaryVersion;\n this.enableCapture = enableCapture;\n this.enableColors = enableColors;\n }\n /**\n * Creates a new Cli and registers all commands passed as parameters.\n *\n * @param commandClasses The Commands to register\n * @returns The created `Cli` instance\n */\n static from(commandClasses, options = {}) {\n const cli = new Cli(options);\n const resolvedCommandClasses = Array.isArray(commandClasses)\n ? commandClasses\n : [commandClasses];\n for (const commandClass of resolvedCommandClasses)\n cli.register(commandClass);\n return cli;\n }\n /**\n * Registers a command inside the CLI.\n */\n register(commandClass) {\n var _a;\n const specs = new Map();\n const command = new commandClass();\n for (const key in command) {\n const value = command[key];\n if (typeof value === `object` && value !== null && value[Command.isOption]) {\n specs.set(key, value);\n }\n }\n const builder = this.builder.command();\n const index = builder.cliIndex;\n const paths = (_a = commandClass.paths) !== null && _a !== void 0 ? _a : command.paths;\n if (typeof paths !== `undefined`)\n for (const path of paths)\n builder.addPath(path);\n this.registrations.set(commandClass, { specs, builder, index });\n for (const [key, { definition }] of specs.entries())\n definition(builder, key);\n builder.setContext({\n commandClass,\n });\n }\n process(opts, contextArg) {\n const { input, context: userContext, partial } = typeof opts === `object` && Array.isArray(opts)\n ? { input: opts, context: contextArg }\n : opts;\n const { contexts, process } = this.builder.compile();\n const state = process(input, { partial });\n const context = {\n ...Cli.defaultContext,\n ...userContext,\n };\n switch (state.selectedIndex) {\n case HELP_COMMAND_INDEX:\n {\n const command = HelpCommand.from(state, contexts);\n command.context = context;\n command.tokens = state.tokens;\n return command;\n }\n default:\n {\n const { commandClass } = contexts[state.selectedIndex];\n const record = this.registrations.get(commandClass);\n if (typeof record === `undefined`)\n throw new Error(`Assertion failed: Expected the command class to have been registered.`);\n const command = new commandClass();\n command.context = context;\n command.tokens = state.tokens;\n command.path = state.path;\n try {\n for (const [key, { transformer }] of record.specs.entries())\n command[key] = transformer(record.builder, key, state, context);\n return command;\n }\n catch (error) {\n error[errorCommandSymbol] = command;\n throw error;\n }\n }\n break;\n }\n }\n async run(input, userContext) {\n var _a, _b;\n let command;\n const context = {\n ...Cli.defaultContext,\n ...userContext,\n };\n const colored = (_a = this.enableColors) !== null && _a !== void 0 ? _a : context.colorDepth > 1;\n if (!Array.isArray(input)) {\n command = input;\n }\n else {\n try {\n command = this.process(input, context);\n }\n catch (error) {\n context.stdout.write(this.error(error, { colored }));\n return 1;\n }\n }\n if (command.help) {\n context.stdout.write(this.usage(command, { colored, detailed: true }));\n return 0;\n }\n command.context = context;\n command.cli = {\n binaryLabel: this.binaryLabel,\n binaryName: this.binaryName,\n binaryVersion: this.binaryVersion,\n enableCapture: this.enableCapture,\n enableColors: this.enableColors,\n definitions: () => this.definitions(),\n definition: command => this.definition(command),\n error: (error, opts) => this.error(error, opts),\n format: colored => this.format(colored),\n process: (input, subContext) => this.process(input, { ...context, ...subContext }),\n run: (input, subContext) => this.run(input, { ...context, ...subContext }),\n usage: (command, opts) => this.usage(command, opts),\n };\n const activate = this.enableCapture\n ? (_b = getCaptureActivator(context)) !== null && _b !== void 0 ? _b : noopCaptureActivator\n : noopCaptureActivator;\n let exitCode;\n try {\n exitCode = await activate(() => command.validateAndExecute().catch(error => command.catch(error).then(() => 0)));\n }\n catch (error) {\n context.stdout.write(this.error(error, { colored, command }));\n return 1;\n }\n return exitCode;\n }\n async runExit(input, context) {\n process.exitCode = await this.run(input, context);\n }\n definition(commandClass, { colored = false } = {}) {\n if (!commandClass.usage)\n return null;\n const { usage: path } = this.getUsageByRegistration(commandClass, { detailed: false });\n const { usage, options } = this.getUsageByRegistration(commandClass, { detailed: true, inlineOptions: false });\n const category = typeof commandClass.usage.category !== `undefined`\n ? formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false })\n : undefined;\n const description = typeof commandClass.usage.description !== `undefined`\n ? formatMarkdownish(commandClass.usage.description, { format: this.format(colored), paragraphs: false })\n : undefined;\n const details = typeof commandClass.usage.details !== `undefined`\n ? formatMarkdownish(commandClass.usage.details, { format: this.format(colored), paragraphs: true })\n : undefined;\n const examples = typeof commandClass.usage.examples !== `undefined`\n ? commandClass.usage.examples.map(([label, cli]) => [formatMarkdownish(label, { format: this.format(colored), paragraphs: false }), cli.replace(/\\$0/g, this.binaryName)])\n : undefined;\n return { path, usage, category, description, details, examples, options };\n }\n definitions({ colored = false } = {}) {\n const data = [];\n for (const commandClass of this.registrations.keys()) {\n const usage = this.definition(commandClass, { colored });\n if (!usage)\n continue;\n data.push(usage);\n }\n return data;\n }\n usage(command = null, { colored, detailed = false, prefix = `$ ` } = {}) {\n var _a;\n // In case the default command is the only one, we can just show the command help rather than the general one\n if (command === null) {\n for (const commandClass of this.registrations.keys()) {\n const paths = commandClass.paths;\n const isDocumented = typeof commandClass.usage !== `undefined`;\n const isExclusivelyDefault = !paths || paths.length === 0 || (paths.length === 1 && paths[0].length === 0);\n const isDefault = isExclusivelyDefault || ((_a = paths === null || paths === void 0 ? void 0 : paths.some(path => path.length === 0)) !== null && _a !== void 0 ? _a : false);\n if (isDefault) {\n if (command) {\n command = null;\n break;\n }\n else {\n command = commandClass;\n }\n }\n else {\n if (isDocumented) {\n command = null;\n continue;\n }\n }\n }\n if (command) {\n detailed = true;\n }\n }\n // @ts-ignore\n const commandClass = command !== null && command instanceof Command\n ? command.constructor\n : command;\n let result = ``;\n if (!commandClass) {\n const commandsByCategories = new Map();\n for (const [commandClass, { index }] of this.registrations.entries()) {\n if (typeof commandClass.usage === `undefined`)\n continue;\n const category = typeof commandClass.usage.category !== `undefined`\n ? formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false })\n : null;\n let categoryCommands = commandsByCategories.get(category);\n if (typeof categoryCommands === `undefined`)\n commandsByCategories.set(category, categoryCommands = []);\n const { usage } = this.getUsageByIndex(index);\n categoryCommands.push({ commandClass, usage });\n }\n const categoryNames = Array.from(commandsByCategories.keys()).sort((a, b) => {\n if (a === null)\n return -1;\n if (b === null)\n return +1;\n return a.localeCompare(b, `en`, { usage: `sort`, caseFirst: `upper` });\n });\n const hasLabel = typeof this.binaryLabel !== `undefined`;\n const hasVersion = typeof this.binaryVersion !== `undefined`;\n if (hasLabel || hasVersion) {\n if (hasLabel && hasVersion)\n result += `${this.format(colored).header(`${this.binaryLabel} - ${this.binaryVersion}`)}\\n\\n`;\n else if (hasLabel)\n result += `${this.format(colored).header(`${this.binaryLabel}`)}\\n`;\n else\n result += `${this.format(colored).header(`${this.binaryVersion}`)}\\n`;\n result += ` ${this.format(colored).bold(prefix)}${this.binaryName} <command>\\n`;\n }\n else {\n result += `${this.format(colored).bold(prefix)}${this.binaryName} <command>\\n`;\n }\n for (const categoryName of categoryNames) {\n const commands = commandsByCategories.get(categoryName).slice().sort((a, b) => {\n return a.usage.localeCompare(b.usage, `en`, { usage: `sort`, caseFirst: `upper` });\n });\n const header = categoryName !== null\n ? categoryName.trim()\n : `General commands`;\n result += `\\n`;\n result += `${this.format(colored).header(`${header}`)}\\n`;\n for (const { commandClass, usage } of commands) {\n const doc = commandClass.usage.description || `undocumented`;\n result += `\\n`;\n result += ` ${this.format(colored).bold(usage)}\\n`;\n result += ` ${formatMarkdownish(doc, { format: this.format(colored), paragraphs: false })}`;\n }\n }\n result += `\\n`;\n result += formatMarkdownish(`You can also print more details about any of these commands by calling them with the \\`-h,--help\\` flag right after the command name.`, { format: this.format(colored), paragraphs: true });\n }\n else {\n if (!detailed) {\n const { usage } = this.getUsageByRegistration(commandClass);\n result += `${this.format(colored).bold(prefix)}${usage}\\n`;\n }\n else {\n const { description = ``, details = ``, examples = [], } = commandClass.usage || {};\n if (description !== ``) {\n result += formatMarkdownish(description, { format: this.format(colored), paragraphs: false }).replace(/^./, $0 => $0.toUpperCase());\n result += `\\n`;\n }\n if (details !== `` || examples.length > 0) {\n result += `${this.format(colored).header(`Usage`)}\\n`;\n result += `\\n`;\n }\n const { usage, options } = this.getUsageByRegistration(commandClass, { inlineOptions: false });\n result += `${this.format(colored).bold(prefix)}${usage}\\n`;\n if (options.length > 0) {\n result += `\\n`;\n result += `${this.format(colored).header(`Options`)}\\n`;\n const maxDefinitionLength = options.reduce((length, option) => {\n return Math.max(length, option.definition.length);\n }, 0);\n result += `\\n`;\n for (const { definition, description } of options) {\n result += ` ${this.format(colored).bold(definition.padEnd(maxDefinitionLength))} ${formatMarkdownish(description, { format: this.format(colored), paragraphs: false })}`;\n }\n }\n if (details !== ``) {\n result += `\\n`;\n result += `${this.format(colored).header(`Details`)}\\n`;\n result += `\\n`;\n result += formatMarkdownish(details, { format: this.format(colored), paragraphs: true });\n }\n if (examples.length > 0) {\n result += `\\n`;\n result += `${this.format(colored).header(`Examples`)}\\n`;\n for (const [description, example] of examples) {\n result += `\\n`;\n result += formatMarkdownish(description, { format: this.format(colored), paragraphs: false });\n result += `${example\n .replace(/^/m, ` ${this.format(colored).bold(prefix)}`)\n .replace(/\\$0/g, this.binaryName)}\\n`;\n }\n }\n }\n }\n return result;\n }\n error(error, _a) {\n var _b;\n var { colored, command = (_b = error[errorCommandSymbol]) !== null && _b !== void 0 ? _b : null } = _a === void 0 ? {} : _a;\n if (!error || typeof error !== `object` || !(`stack` in error))\n error = new Error(`Execution failed with a non-error rejection (rejected value: ${JSON.stringify(error)})`);\n let result = ``;\n let name = error.name.replace(/([a-z])([A-Z])/g, `$1 $2`);\n if (name === `Error`)\n name = `Internal Error`;\n result += `${this.format(colored).error(name)}: ${error.message}\\n`;\n const meta = error.clipanion;\n if (typeof meta !== `undefined`) {\n if (meta.type === `usage`) {\n result += `\\n`;\n result += this.usage(command);\n }\n }\n else {\n if (error.stack) {\n result += `${error.stack.replace(/^.*\\n/, ``)}\\n`;\n }\n }\n return result;\n }\n format(colored) {\n var _a;\n return ((_a = colored !== null && colored !== void 0 ? colored : this.enableColors) !== null && _a !== void 0 ? _a : Cli.defaultContext.colorDepth > 1) ? richFormat : textFormat;\n }\n getUsageByRegistration(klass, opts) {\n const record = this.registrations.get(klass);\n if (typeof record === `undefined`)\n throw new Error(`Assertion failed: Unregistered command`);\n return this.getUsageByIndex(record.index, opts);\n }\n getUsageByIndex(n, opts) {\n return this.builder.getBuilderByIndex(n).usage(opts);\n }\n}\n/**\n * The default context of the CLI.\n *\n * Contains the stdio of the current `process`.\n */\nCli.defaultContext = {\n env: process.env,\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n colorDepth: getDefaultColorDepth(),\n};\nfunction noopCaptureActivator(fn) {\n return fn();\n}\n\nexport { Cli, run, runExit };\n","function getDefaultColorDepth() {\n return 1;\n}\nfunction getCaptureActivator() {\n throw new Error(`The enableCapture option cannot be used from within a browser environment`);\n}\n\nexport { getCaptureActivator, getDefaultColorDepth };\n","import { makeCommandOption, rerouteArguments } from './utils.mjs';\n\nfunction Boolean(descriptor, initialValueBase, optsBase) {\n const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});\n const optNames = descriptor.split(`,`);\n const nameSet = new Set(optNames);\n return makeCommandOption({\n definition(builder) {\n builder.addOption({\n names: optNames,\n allowBinding: false,\n arity: 0,\n hidden: opts.hidden,\n description: opts.description,\n required: opts.required,\n });\n },\n transformer(builer, key, state) {\n let currentValue = initialValue;\n for (const { name, value } of state.options) {\n if (!nameSet.has(name))\n continue;\n currentValue = value;\n }\n return currentValue;\n },\n });\n}\n\nexport { Boolean };\n","import { NoLimits } from '../../core.mjs';\nimport { makeCommandOption, applyValidator, rerouteArguments } from './utils.mjs';\n\nfunction StringOption(descriptor, initialValueBase, optsBase) {\n const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});\n const { arity = 1 } = opts;\n const optNames = descriptor.split(`,`);\n const nameSet = new Set(optNames);\n return makeCommandOption({\n definition(builder) {\n builder.addOption({\n names: optNames,\n arity: opts.tolerateBoolean ? 0 : arity,\n hidden: opts.hidden,\n description: opts.description,\n required: opts.required,\n });\n },\n transformer(builder, key, state, context) {\n let usedName;\n let currentValue = initialValue;\n if (typeof opts.env !== `undefined` && context.env[opts.env]) {\n usedName = opts.env;\n currentValue = context.env[opts.env];\n }\n for (const { name, value } of state.options) {\n if (!nameSet.has(name))\n continue;\n usedName = name;\n currentValue = value;\n }\n if (typeof currentValue === `string`) {\n return applyValidator(usedName !== null && usedName !== void 0 ? usedName : key, currentValue, opts.validator);\n }\n else {\n return currentValue;\n }\n },\n });\n}\nfunction StringPositional(opts = {}) {\n const { required = true } = opts;\n return makeCommandOption({\n definition(builder, key) {\n var _a;\n builder.addPositional({\n name: (_a = opts.name) !== null && _a !== void 0 ? _a : key,\n required: opts.required,\n });\n },\n transformer(builder, key, state) {\n var _a;\n for (let i = 0; i < state.positionals.length; ++i) {\n // We skip NoLimits extras. We only care about\n // required and optional finite positionals.\n if (state.positionals[i].extra === NoLimits)\n continue;\n // We skip optional positionals when we only\n // care about required positionals.\n if (required && state.positionals[i].extra === true)\n continue;\n // We skip required positionals when we only\n // care about optional positionals.\n if (!required && state.positionals[i].extra === false)\n continue;\n // We remove the positional from the list\n const [positional] = state.positionals.splice(i, 1);\n return applyValidator((_a = opts.name) !== null && _a !== void 0 ? _a : key, positional.value, opts.validator);\n }\n return undefined;\n },\n });\n}\n// This function is badly typed, but it doesn't matter because the overloads provide the true public typings\nfunction String(descriptor, ...args) {\n if (typeof descriptor === `string`) {\n return StringOption(descriptor, ...args);\n }\n else {\n return StringPositional(descriptor);\n }\n}\n\nexport { String };\n","export const enum TadaErrorCode {\n VUE_SUPPORT,\n SVELTE_SUPPORT,\n UNKNOWN_EXTERNAL_FILE,\n}\n\nexport class TadaError extends Error {\n static isTadaError(error: unknown): error is TadaError {\n return !!(typeof error === 'object' && error && 'name' in error && error.name === 'TadaError');\n }\n\n readonly code: TadaErrorCode;\n constructor(code: TadaErrorCode, message: string) {\n super(message);\n this.code = code;\n this.name = 'TadaError';\n }\n}\n\nexport const exitCode = () => {\n const { exitCode } = process;\n return typeof exitCode === 'string' ? parseInt(exitCode, 10) || 0 : exitCode;\n};\n","let hasColor = false;\n\nexport function _setColor(color: boolean) {\n hasColor = color;\n}\n\n// See: http://xtermjs.org/docs/api/vtfeatures/#csi\nconst enum CSI {\n InsertChars = '@',\n ScrollLeft = 'SP@',\n Up = 'A',\n ScrollRight = 'SPA',\n Down = 'B',\n Forward = 'C',\n Backward = 'D',\n NextLine = 'E',\n PrevLine = 'F',\n ToColumn = 'G',\n ToPosition = 'H',\n Tab = 'I',\n Erase = 'J',\n EraseLine = 'K',\n InsertLines = 'L',\n DeleteLines = 'M',\n DeleteChars = 'P',\n ScrollUp = 'S',\n ScrollDown = 'T',\n EraseChars = 'X',\n TabBackwards = 'Z',\n RepeatChar = 'b',\n ToRow = 'd',\n DownLine = 'e',\n TabClear = 'g',\n SetMode = 'h',\n UnsetMode = 'l',\n SetPrivateMode = '?h',\n UnsetPrivateMode = '?l',\n ResetPrivateMode = '?r',\n Style = 'm',\n Reset = '!p',\n Protect = '\"q',\n Cursor = 'SPq',\n SetMargin = 'r',\n SaveCursor = 's',\n RestoreCursor = 'u',\n InsertColumns = \"'}\",\n DeleteColumns = \"'~\",\n}\n\nconst enum TabClear {\n Current = 0,\n All = 3,\n}\n\nconst enum Erase {\n Forward = 0,\n Backward = 1,\n All = 2,\n Scrollback = 3,\n}\n\nconst enum EraseLine {\n Forward = 0,\n Backward = 1,\n All = 2,\n}\n\nconst enum Protect {\n Insert = 4,\n AutomaticNewline = 20,\n}\n\nconst enum Mode {\n Insert = 4,\n AutomaticNewline = 20,\n}\n\nconst enum PrivateMode {\n AppCursorKeys = 1,\n USASCII = 2,\n Column132 = 3,\n OriginMode = 6,\n AutoWrap = 7,\n AutoRepeat = 8,\n X10Mouse = 9,\n BlinkCursor = 12,\n ShowCursor = 25,\n ReverseWrapAround = 45,\n AlternativeScreenBuffer = 47,\n AppKeypad = 66,\n X11Mouse = 1000,\n CellMotionMouseTracking = 1002,\n AllMotionMouseTracking = 1003,\n FocusEvents = 1004,\n Utf8Mouse = 1005,\n SGRMouse = 1006,\n UrxvtMouse = 1015,\n SGRPixelsMouse = 1016,\n SaveCursor = 1048,\n BracketedPaste = 2004,\n}\n\nconst enum Cursor {\n Empty = 0,\n Block = 1,\n BlinkBlock = 2,\n Underline = 3,\n BlinkUnderline = 4,\n Bar = 5,\n BlinkBar = 6,\n}\n\nconst enum Style {\n Reset = 0,\n Bold = 1,\n Faint = 2,\n Italic = 3,\n Underline = 4,\n Blink = 5,\n RapidBlink = 6,\n Invert = 7,\n Invisible = 8,\n Strikethrough = 9,\n DoubleUnderlined = 21,\n Normal = 22, // No Bold, No Faint\n NoItalic = 23,\n NoUnderline = 24,\n NoBlink = 25,\n NoInvert = 27,\n Visible = 28,\n NoStrikethrough = 29,\n\n Black = 30,\n Red = 31,\n Green = 32,\n Yellow = 33,\n Blue = 34,\n Magenta = 35,\n Cyan = 36,\n White = 37,\n Foreground = 39,\n\n OnBlack = 40,\n OnRed = 41,\n OnGreen = 42,\n OnYellow = 43,\n OnBlue = 44,\n OnMagenta = 45,\n OnCyan = 46,\n OnWhite = 47,\n OnBackground = 49,\n\n BrightBlack = 90,\n BrightRed = 91,\n BrightGreen = 92,\n BrightYellow = 93,\n BrightBlue = 94,\n BrightMagenta = 95,\n BrightCyan = 96,\n BrightWhite = 97,\n\n OnBrightBlack = 100,\n OnBrightRed = 101,\n OnBrightGreen = 102,\n OnBrightYellow = 103,\n OnBrightBlue = 104,\n OnBrightMagenta = 105,\n OnBrightCyan = 106,\n OnBrightWhite = 107,\n\n DoubleUnderline = '4:2',\n CurlyUnderline = '4:3',\n DottedUnderline = '4:4',\n DashedUnderline = '4:5',\n}\n\ntype escapeCSI = '\\x1B[';\nconst escapeCSI = '\\x1B[';\n\ntype CommandNoParam = CSI.Reset | CSI.SaveCursor | CSI.RestoreCursor | CSI.ResetPrivateMode;\n\ntype CommandSingleParam =\n | CSI.ScrollLeft\n | CSI.ScrollRight\n | CSI.ScrollUp\n | CSI.ScrollDown\n | CSI.Up\n | CSI.Down\n | CSI.Backward\n | CSI.Forward\n | CSI.PrevLine\n | CSI.NextLine\n | CSI.DownLine\n | CSI.ToColumn\n | CSI.ToRow\n | CSI.Tab\n | CSI.TabBackwards\n | CSI.InsertChars\n | CSI.InsertLines\n | CSI.InsertColumns\n | CSI.DeleteChars\n | CSI.DeleteLines\n | CSI.DeleteColumns\n | CSI.RepeatChar;\n\ntype CommandParam =\n | number\n | TabClear\n | Erase\n | EraseLine\n | Protect\n | Cursor\n | Mode\n | PrivateMode\n | Style\n | readonly Mode[]\n | readonly PrivateMode[]\n | readonly Style[];\n\nfunction cmd(code: CommandNoParam): `${escapeCSI}${CommandNoParam}`;\nfunction cmd(\n code: CommandSingleParam,\n count?: number\n): `${escapeCSI}${number}${CommandSingleParam}`;\nfunction cmd(code: CSI.TabClear, mode?: TabClear): `${escapeCSI}${TabClear}${CSI.TabClear}`;\nfunction cmd(code: CSI.Erase, mode?: Erase): `${escapeCSI}${Erase}${CSI.Erase}`;\nfunction cmd(code: CSI.EraseLine, mode?: EraseLine): `${escapeCSI}${EraseLine}${CSI.EraseLine}`;\nfunction cmd(code: CSI.Protect, mode?: Protect): `${escapeCSI}${Protect}${CSI.Protect}`;\nfunction cmd(code: CSI.Cursor, style: Cursor): `${escapeCSI}${Cursor}${CSI.Cursor}`;\n\nfunction cmd(\n code: CSI.ToPosition,\n row: number,\n column: number\n): `${escapeCSI}${number};${number}${CSI.ToPosition}`;\n\nfunction cmd(\n code: CSI.SetMargin,\n top: number,\n bottom: number\n): `${escapeCSI}${number};${number}${CSI.SetMargin}`;\n\nfunction cmd(code: CSI.SetMode, modes: Mode | readonly Mode[]): `${escapeCSI}${Mode}${CSI.SetMode}`;\n\nfunction cmd(\n code: CSI.SetPrivateMode,\n modes: PrivateMode | readonly PrivateMode[]\n): `${escapeCSI}?${PrivateMode}${CSI.SetMode}`;\n\nfunction cmd(\n code: CSI.UnsetMode,\n modes: Mode | readonly Mode[]\n): `${escapeCSI}${Mode}${CSI.UnsetMode}`;\n\nfunction cmd(\n code: CSI.UnsetPrivateMode,\n modes: PrivateMode | readonly PrivateMode[]\n): `${escapeCSI}?${PrivateMode}${CSI.UnsetMode}`;\n\nfunction cmd(code: CSI.Style, styles: Style | readonly Style[]): `${escapeCSI}${Style}${CSI.Style}`;\n\nfunction cmd(code: CSI, a?: CommandParam, b?: number): cmdCode {\n if (!hasColor && code === CSI.Style) return '';\n let out = escapeCSI;\n if (code === CSI.SetPrivateMode) {\n out += '?';\n code = CSI.SetMode;\n } else if (code === CSI.UnsetPrivateMode) {\n out += '?';\n code = CSI.UnsetMode;\n }\n if (Array.isArray(a)) {\n out += a.join(';');\n } else if (a != null) {\n out += `${a}`;\n if (b != null) out += `;${b}`;\n }\n out += code;\n return out as cmdCode;\n}\n\nexport type cmdCode = `${escapeCSI}${string}${CSI}` | '';\n\nexport { cmd, CSI, TabClear, Erase, EraseLine, Protect, Mode, PrivateMode, Cursor, Style };\n","import type { Source } from 'wonka';\n\nimport {\n pipe,\n fromAsyncIterable,\n fromValue,\n concatMap,\n never,\n merge,\n takeUntil,\n takeLast,\n filter,\n share,\n scan,\n make,\n onPush,\n onEnd,\n subscribe,\n} from 'wonka';\n\nimport { cmd, CSI, EraseLine, Style } from './csi';\n\nconst ansiRegex = /([\\x1B\\x9B][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><])/g;\n\nexport const stripAnsi = (input: string) => input.replace(ansiRegex, '');\n\nexport class CLIError extends Error {\n output: string;\n exit: number;\n constructor(message: string, exitCode?: number) {\n super(stripAnsi(message));\n this.output = message;\n this.exit = exitCode != null ? exitCode : 1;\n }\n\n toString() {\n return this.output;\n }\n}\n\nfunction text(input: readonly string[], ...args: readonly string[]): string;\nfunction text(...input: readonly string[]): string;\n\nfunction text(input: string | readonly string[], ...args: readonly string[]): string {\n let out = '';\n if (Array.isArray(input)) {\n let argIndex = 0;\n for (let index = 0; index < input.length; index++) {\n out += input[index];\n if (argIndex < args.length) out += args[argIndex++];\n }\n } else if (typeof input === 'string') {\n out += input;\n for (const arg of args) out += arg;\n }\n return out;\n}\n\nfunction error(input: readonly string[], ...args: readonly string[]): CLIError;\nfunction error(arg: string | number, ...input: readonly string[]): CLIError;\nfunction error(...input: readonly string[]): CLIError;\n\nfunction error(arg: readonly string[] | string | number, ...input: readonly string[]): CLIError {\n return typeof arg === 'number'\n ? new CLIError(text(...input), arg)\n : new CLIError(text(arg as string, ...input));\n}\n\nfunction clear(text: string) {\n let lines = 0;\n for (let index = 0; index < text.length; index++)\n if (text.charCodeAt(index) === 10 /*'\\n'*/) lines++;\n if (lines) {\n return cmd(CSI.PrevLine, lines) + cmd(CSI.DeleteLines, lines + 1);\n } else if (stripAnsi(text)) {\n return cmd(CSI.EraseLine, EraseLine.Backward) + cmd(CSI.ToColumn, 1);\n } else {\n return '';\n }\n}\n\ntype ComposeInput = undefined | string | CLIError | Source<string> | AsyncIterable<ComposeInput>;\n\nfunction commit(source: Source<string | CLIError>): Source<string | CLIError> {\n return make((observer) => {\n let last: string | CLIError | undefined;\n const subscription = pipe(\n source,\n onPush((value) => {\n last = value;\n observer.next(value);\n }),\n onEnd(() => {\n if (typeof last === 'string' && !last.endsWith('\\n')) observer.next('');\n observer.complete();\n }),\n subscribe(() => {})\n );\n return subscription.unsubscribe;\n });\n}\n\nasync function* convertError(outputs: AsyncIterable<ComposeInput>): AsyncIterable<ComposeInput> {\n try {\n yield* outputs;\n } catch (error) {\n if (error instanceof CLIError) {\n process.exitCode = error.exit;\n yield error;\n } else {\n yield ('' + error).trim();\n }\n }\n\n yield '\\n';\n}\n\nfunction compose(outputs: AsyncIterable<ComposeInput>): Source<string | CLIError> {\n const reset = cmd(CSI.Style, [Style.Reset, Style.NoInvert]);\n const outputs$ = pipe(\n fromAsyncIterable(convertError(outputs)),\n concatMap((output) => {\n return typeof output === 'object' && !(output instanceof CLIError)\n ? compose(output)\n : fromValue(output);\n }),\n filter(<T>(x: T): x is Exclude<T, undefined> => x != null),\n share\n );\n\n return pipe(\n outputs$,\n concatMap((output) => {\n const output$ = pipe(\n typeof output === 'string' || output instanceof CLIError\n ? fromValue(output)\n : merge([output, never]),\n takeUntil(outputs$),\n share\n );\n return pipe(\n commit(output$),\n scan((prev: CLIError | string, output) => {\n return typeof output === 'string'\n ? clear(typeof prev === 'string' ? prev : '') + output + reset\n : output;\n }, '')\n );\n }),\n takeUntil(pipe(outputs$, takeLast(1)))\n );\n}\n\nexport type { ComposeInput };\nexport { text, error, compose, clear };\n","export const enum Chars {\n Bell = '\\x07',\n Newline = '\\x0a',\n Tab = '\\x09',\n Space = ' ',\n Ellipsis = '…',\n}\n\nexport const enum Box {\n TopLeft = '┌',\n TopRight = '┐',\n BottomLeft = '└',\n BottomRight = '┘',\n Vertical = '│',\n VerticalRight = '├',\n VerticalLeft = '┤',\n Horizontal = '─',\n HorizontalDown = '┬',\n HorizontalUp = '┴',\n Cross = '┼',\n}\n\nexport const enum HeavyBox {\n TopLeft = '┏',\n TopRight = '┓',\n BottomLeft = '┗',\n BottomRight = '┛',\n Vertical = '┃',\n VerticalRight = '┣',\n VerticalLeft = '┫',\n Horizontal = '━',\n HorizontalDown = '┳',\n HorizontalUp = '┻',\n Cross = '╋',\n}\n\nexport const enum DoubleBox {\n TopLeft = '╔',\n TopRight = '╗',\n BottomLeft = '╚',\n BottomRight = '╝',\n Vertical = '║',\n VerticalRight = '╠',\n VerticalLeft = '╣',\n Horizontal = '═',\n HorizontalDown = '╦',\n HorizontalUp = '╩',\n Cross = '╬',\n}\n\nexport enum RoundedBox {\n TopLeft = '╭',\n TopRight = '╮',\n BottomLeft = '╰',\n BottomRight = '╯',\n Vertical = '│',\n VerticalRight = '├',\n VerticalLeft = '┤',\n Horizontal = '─',\n HorizontalDown = '┬',\n HorizontalUp = '┴',\n Cross = '┼',\n}\n\nexport const enum Arrow {\n Right = '→',\n Left = '←',\n Up = '↑',\n Down = '↓',\n LeftRight = '↔',\n UpDown = '↕',\n}\n\nexport const enum Triangle {\n Right = '▶',\n Left = '◀',\n Up = '▲',\n Down = '▼',\n}\n\nexport const enum SmallTriangle {\n Right = '▸',\n Left = '◂',\n Up = '▴',\n Down = '▾',\n}\n\nexport const enum Line {\n DiagonalCross = '╳',\n Diagonalbackwards = '╲',\n Diagonal = '╱',\n VerticalDashed = '┆',\n VerticalDashedHeavy = '┇',\n Vertical = '│',\n VerticalHeavy = '┃',\n HorizontalDashed = '┄',\n HorizontalDashedHeavy = '┅',\n Horizontal = '─',\n HorizontalHeavy = '━',\n}\n\nexport const enum Circle {\n Filled = '●',\n Outline = '◯',\n OutlineFilled = '◉',\n Dotted = '◌',\n Doubled = '◎',\n Small = '•',\n HalfLeft = '◐',\n HalfTop = '◓',\n HalfRight = '◑',\n HalfBottom = '◒',\n}\n\nexport const enum Chevron {\n Default = '',\n Small = '›',\n Heavy = '❯',\n}\n\nexport const enum Diamond {\n Default = '◆',\n Outline = '◇',\n}\n\nexport const enum Square {\n Default = '■',\n Outline = '☐',\n Crossed = '☒',\n}\n\nexport const enum Heart {\n Default = '❤︎',\n Outline = '♥',\n}\n\nexport const enum Icons {\n Tick = '✓',\n TickSwoosh = '✔',\n Cross = '✖',\n CrossSwoosh = '✘',\n Home = '⌂',\n Note = '♪',\n Warning = '⚠',\n Info = 'ℹ',\n Star = '★',\n}\n\nexport const enum Shade {\n Light = '░',\n Medium = '▒',\n Heavy = '▓',\n}\n\nexport const dotSpinner = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\nexport const circleSpinner = ['◐', '◓', '◑', '◒'];\n","export const isGithubCI = !!process.env.GITHUB_ACTIONS;\n\nexport interface AnnotationProperties {\n title?: string;\n file?: string;\n line?: number;\n endLine?: number;\n col?: number;\n endColumn?: number;\n}\n\nconst toCommandValue = (input: unknown): string =>\n typeof input == 'string' || input == null\n ? '' + (input ? '' + input : '')\n : JSON.stringify(input);\n\nconst escapeData = (input: unknown) =>\n toCommandValue(input).replace(/%/g, '%25').replace(/\\r/g, '%0D').replace(/\\n/g, '%0A');\n\nconst escapeProperty = (input: unknown): string =>\n toCommandValue(input)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A')\n .replace(/:/g, '%3A')\n .replace(/,/g, '%2C');\n\nexport function githubAnnotation(\n kind: 'error' | 'warning' | 'notice',\n message: string,\n properties?: AnnotationProperties\n) {\n if (isGithubCI) {\n let out = `::${kind}`;\n let propsOut = '';\n if (properties) {\n for (const key in properties) {\n if (properties) propsOut += ',';\n if (properties[key]) propsOut += `${key}=${escapeProperty(properties[key])}`;\n }\n }\n if (propsOut) out += ` ${propsOut}`;\n out += `::${escapeData(message)}\\n`;\n process.stdout.write(out);\n }\n}\n","import {\n fromValue,\n make,\n concat,\n pipe,\n filter,\n share,\n takeUntil,\n toPromise,\n onPush,\n onStart,\n onEnd,\n} from 'wonka';\n\nimport type { Source } from 'wonka';\nimport type { WriteStream, ReadStream } from 'node:tty';\nimport { emitKeypressEvents } from 'node:readline';\n\nimport type { ComposeInput, CLIError } from './write';\nimport { text, compose } from './write';\nimport { cmd, _setColor, CSI, Mode, PrivateMode } from './csi';\nimport { isGithubCI } from './github';\n\nexport interface TTYParams {\n disableTTY?: boolean;\n silent?: boolean;\n}\n\nexport interface KeypressEvent {\n data?: string;\n sequence: string;\n name: string;\n ctrl: boolean;\n meta: boolean;\n shift: boolean;\n}\n\nexport interface TTY {\n isInteractive: boolean;\n\n output: WriteStream;\n pipeTo: WriteStream | null;\n inputSource: Source<KeypressEvent>;\n cancelSource: Source<unknown>;\n\n write(input: readonly string[], ...args: readonly string[]): void;\n write(...input: readonly string[]): void;\n\n start(outputs: AsyncIterable<ComposeInput>, disableInput?: boolean): Promise<string | CLIError>;\n\n mode(...modes: readonly (Mode | PrivateMode)[]): void;\n modeOff(...modes: readonly (Mode | PrivateMode)[]): void;\n}\n\nfunction fromReadStream(stream: ReadStream, onTerminate: () => void): Source<KeypressEvent> {\n return make((observer) => {\n function onKeypress(data: string | undefined, event: KeypressEvent) {\n switch (event.name) {\n case 'c':\n case 'd':\n case 'x':\n if (event.ctrl) return onTerminate();\n break;\n case 'escape':\n return cleanup();\n }\n observer.next({ ...event, data });\n }\n\n function cleanup() {\n if (stream.isTTY) stream.setRawMode(false);\n observer.complete();\n stream.removeListener('keypress', onKeypress);\n stream.unref();\n }\n\n if (stream.isTTY) stream.setRawMode(true);\n emitKeypressEvents(stream);\n stream.setEncoding('utf8');\n stream.resume();\n stream.addListener('keypress', onKeypress);\n return cleanup;\n });\n}\n\nexport function initTTY(params: TTYParams = {}): TTY {\n let isTTY = process.env.TERM !== 'dumb' && !process.env.CI && !params.disableTTY;\n let pipeTo: WriteStream | null = null;\n let output: WriteStream = process.stdout;\n if (isGithubCI) {\n output = process.stderr;\n } else if (!output.isTTY && process.stderr.isTTY) {\n output = process.stderr;\n pipeTo = process.stdout;\n } else {\n isTTY = output.isTTY;\n }\n\n const hasColorArg = process.argv.includes('--color');\n const hasColorEnv = 'FORCE_COLOR' in process.env || (!process.env.NO_COLOR && !process.env.CI);\n _setColor((isTTY && hasColorEnv) || hasColorArg || isGithubCI);\n\n function _restore() {\n if (process.stdin.isTTY) process.stdin.setRawMode(false);\n output.write(\n cmd(CSI.Reset) + cmd(CSI.ResetPrivateMode) + cmd(CSI.SetPrivateMode, PrivateMode.ShowCursor)\n );\n }\n\n function _terminate(code: number) {\n _restore();\n process.exit(code);\n }\n\n function _signal(signal: NodeJS.Signals) {\n _terminate(signal === 'SIGINT' ? 130 : 143);\n }\n\n function _start() {\n _setColor((isTTY && hasColorEnv) || hasColorArg);\n if (isTTY) {\n output.write(cmd(CSI.UnsetPrivateMode, PrivateMode.ShowCursor));\n process.on('SIGINT', _signal);\n process.on('SIGTERM', _signal);\n }\n }\n\n function _end() {\n if (isTTY) {\n process.removeListener('SIGINT', _signal);\n process.removeListener('SIGTERM', _signal);\n output.write(\n cmd(CSI.Reset) + cmd(CSI.ResetPrivateMode) + cmd(CSI.SetPrivateMode, PrivateMode.ShowCursor)\n );\n }\n }\n\n const inputSource = pipe(\n fromReadStream(process.stdin, () => _terminate(130)),\n onStart(_start),\n onEnd(_end),\n share\n );\n\n const cancelSource = pipe(\n concat([\n pipe(\n inputSource,\n filter(() => false)\n ),\n fromValue(null),\n ]),\n share\n );\n\n function write(...input: any[]) {\n if (!params.silent) output.write(text(...input));\n }\n\n function start(outputs: AsyncIterable<ComposeInput>): Promise<string | CLIError> {\n const write = (input: string | CLIError) => {\n if (!params.silent) output.write('' + input);\n };\n if (params.disableTTY) {\n return pipe(compose(outputs), onPush(write), toPromise);\n } else {\n return pipe(compose(outputs), onPush(write), takeUntil(cancelSource), toPromise);\n }\n }\n\n function mode(...modes: readonly (Mode | PrivateMode)[]): void {\n if (isTTY) {\n const normalModes: Mode[] = [];\n const privateModes: PrivateMode[] = [];\n for (const mode of modes) {\n if (mode === Mode.Insert || mode === Mode.AutomaticNewline) {\n normalModes.push(mode);\n } else {\n privateModes.push(mode);\n }\n }\n if (normalModes.length) output.write(cmd(CSI.SetMode, normalModes));\n if (privateModes.length) output.write(cmd(CSI.SetPrivateMode, privateModes));\n }\n }\n\n function modeOff(...modes: readonly (Mode | PrivateMode)[]): void {\n if (isTTY) {\n const normalModes: Mode[] = [];\n const privateModes: PrivateMode[] = [];\n for (const mode of modes) {\n if (mode === Mode.Insert || mode === Mode.AutomaticNewline) {\n normalModes.push(mode);\n } else {\n privateModes.push(mode);\n }\n }\n if (normalModes.length) output.write(cmd(CSI.UnsetMode, normalModes));\n if (privateModes.length) output.write(cmd(CSI.UnsetPrivateMode, privateModes));\n }\n }\n\n return {\n isInteractive: isTTY,\n output,\n pipeTo,\n inputSource,\n cancelSource,\n write,\n start,\n mode,\n modeOff,\n };\n}\n","import * as t from '../../term';\n\nexport function indent(text: string, indent: string) {\n if (text.includes('\\n')) {\n const out = text\n .trim()\n .split('\\n')\n .join(t.text([t.Chars.Newline, indent]));\n return text.endsWith('\\n') ? out + '\\n' : out;\n } else {\n return text;\n }\n}\n\nexport function code(text: string) {\n return t.text`${t.cmd(t.CSI.Style, t.Style.Underline)}${text}${t.cmd(\n t.CSI.Style,\n t.Style.NoUnderline\n )}`;\n}\n\nexport function bold(text: string) {\n return t.text`${t.cmd(t.CSI.Style, t.Style.Bold)}${text}${t.cmd(t.CSI.Style, t.Style.Normal)}`;\n}\n\nexport function hint(text: string) {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${t.Icons.Info} `,\n t.cmd(t.CSI.Style, t.Style.Blue),\n indent(text, ' '),\n ]);\n}\n\nexport function projectHeader(label: string) {\n return t.text([\n '\\n',\n t.cmd(t.CSI.Style, t.Style.Magenta),\n `${t.SmallTriangle.Right} `,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n bold(label),\n '\\n',\n ]);\n}\n\nexport function errorMessage(message: string) {\n return t.error([\n '\\n',\n t.cmd(t.CSI.Style, [t.Style.Red, t.Style.Invert]),\n ` ${t.Icons.Warning} Error `,\n t.cmd(t.CSI.Style, t.Style.NoInvert),\n `\\n${message.trim()}\\n`,\n ]);\n}\n\nexport function externalError(message: string, error: unknown) {\n let title: string;\n let text: string;\n if (error && typeof error === 'object') {\n if (\n 'name' in error &&\n (error.name === 'TSError' || error.name === 'TadaError' || 'code' in error)\n ) {\n title = 'code' in error ? 'System Error' : 'Error';\n text =\n error.name === 'TadaError'\n ? t.text([t.cmd(t.CSI.Style, t.Style.Blue), (error as Error).message])\n : (error as Error).message.trim();\n } else if ('stack' in error && typeof error.stack === 'string') {\n title = 'Unexpected Error';\n text = `${error.stack}`;\n } else if ('message' in error && typeof error.message === 'string') {\n title = 'Unexpected Error';\n text = `${error.message}`;\n } else {\n title = 'Unexpected Error';\n text = `${error}`;\n }\n } else {\n title = 'Unexpected Error';\n text = `${error}`;\n }\n\n return t.error([\n '\\n',\n t.cmd(t.CSI.Style, [t.Style.Red, t.Style.Invert]),\n ` ${t.Icons.Warning} ${title} `,\n t.cmd(t.CSI.Style, t.Style.NoInvert),\n `\\n${message.trim()}\\n`,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n indent(!text.endsWith('\\n') ? text + '\\n' : text, ' '),\n ]);\n}\n\nexport function experimentMessage(message: string) {\n return t.error([\n t.cmd(t.CSI.Style, [t.Style.Yellow, t.Style.Bold]),\n `${t.Icons.Warning} Note: `,\n t.cmd(t.CSI.Style, t.Style.Reset),\n `${message.trim()}\\n\\n`,\n ]);\n}\n","import * as path from 'node:path';\nimport type { GraphQLSPConfig, LoadConfigResult } from '@gql.tada/internal';\nimport { loadConfigs, parseConfig, validateUniqueOutputLocations } from '@gql.tada/internal';\n\nexport interface ProjectContext {\n configResult: LoadConfigResult;\n pluginConfig: GraphQLSPConfig;\n /** Directory of the project's own tsconfig.json file. */\n projectPath: string;\n /** Display name for per-project output. */\n label: string;\n}\n\n/** Loads all projects with a plugin config, including referenced projects. */\nexport const loadProjects = async (tsconfig: string | undefined): Promise<ProjectContext[]> => {\n const configResults = await loadConfigs(tsconfig);\n const projects = configResults.map((configResult): ProjectContext => {\n const projectPath = path.dirname(configResult.tsconfigPath);\n return {\n configResult,\n pluginConfig: parseConfig(configResult.pluginConfig, configResult.rootPath),\n projectPath,\n label: path.relative(process.cwd(), configResult.tsconfigPath) || configResult.tsconfigPath,\n };\n });\n validateUniqueOutputLocations(\n projects.map((project) => ({\n projectPath: project.projectPath,\n config: project.pluginConfig,\n label: project.label,\n }))\n );\n return projects;\n};\n","import type { WriteStream } from 'node:tty';\nimport type { PathLike } from 'node:fs';\nimport { dirname } from 'node:path';\nimport * as fs from 'node:fs/promises';\n\n/** Checks whether a directory exists on disk */\nconst directoryExists = async (file: PathLike): Promise<boolean> => {\n try {\n const stat = await fs.stat(file);\n if (stat.isDirectory()) {\n return true;\n } else if (stat.isSymbolicLink()) {\n return directoryExists(await fs.realpath(file));\n } else {\n return false;\n }\n } catch {\n return false;\n }\n};\n\n/** Checks whether a file exists on disk */\nconst fileExists = (file: PathLike): Promise<boolean> =>\n fs\n .stat(file)\n .then((stat) => stat.isFile())\n .catch(() => false);\n\nconst touchFile = async (file: PathLike): Promise<void> => {\n try {\n const now = new Date();\n await fs.utimes(file, now, now);\n } catch (_error) {}\n};\n\nexport type WriteTarget = PathLike | WriteStream;\n\n/** Reads the current contents of a file target, or `undefined` for streams or missing files. */\nexport const readOutput = async (target: WriteTarget): Promise<string | undefined> => {\n if (target && typeof target === 'object' && 'writable' in target) return undefined;\n try {\n return await fs.readFile(target, 'utf8');\n } catch {\n return undefined;\n }\n};\n\n/** Writes a file to a swapfile then moves it into place to prevent excess change events. */\nexport const writeOutput = async (target: WriteTarget, contents: string): Promise<void> => {\n if (target && typeof target === 'object' && 'writable' in target) {\n // If we get a WritableStream (e.g. stdout), we write to that\n // but we listen for errors and wait for it to flush fully\n return await new Promise((resolve, reject) => {\n target.write(contents, (error) => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n }\n\n const targetDirectory = dirname(typeof target !== 'string' ? await fs.realpath(target) : target);\n if (!(await directoryExists(targetDirectory))) {\n await fs.mkdir(targetDirectory, { recursive: true });\n }\n\n if (!(await fileExists(target))) {\n // If the file doesn't exist, we can write directly, and not\n // try-catch so the error falls through\n await fs.writeFile(target, contents);\n } else {\n // If the file exists, we write to a swap-file, then rename (i.e. move)\n // the file into place. No try-catch around `writeFile` for proper\n // directory/permission errors\n const tempTarget = target + '.tmp';\n await fs.writeFile(tempTarget, contents);\n try {\n await fs.rename(tempTarget, target);\n } catch (error) {\n await fs.unlink(tempTarget);\n throw error;\n } finally {\n // When we move the file into place, we also update its access and\n // modification time manually, in case the rename doesn't trigger\n // a change event\n await touchFile(target);\n }\n }\n};\n","import * as t from '../../term';\n\nimport { hint, code } from '../shared/logger';\nexport * from '../shared/logger';\n\nexport function summary(showHint?: boolean) {\n let out = t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Introspection output was generated successfully\\n`,\n ]);\n if (showHint) {\n out += hint(\n `The pipe output was generated in the ${code('.d.ts')} format.\\n` +\n `For the ${code('.ts')} format, pass the ${code('--force-ts-format')} argument.\\n`\n );\n }\n return out;\n}\n","import * as path from 'node:path';\n\nimport {\n loadRef,\n minifyIntrospection,\n outputIntrospectionFile,\n extractIntrospectionHeader,\n} from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, writeOutput, readOutput } from '../shared';\nimport * as logger from './logger';\n\nexport interface OutputOptions {\n /** Whether to output the `.ts` format when the CLI's standard output is piped to an output file.\n * @defaultValue `false` */\n forceTSFormat?: boolean;\n /** Whether to disable the optimized output format for `.d.ts` files.\n * @defaultValue `false` */\n disablePreprocessing?: boolean;\n /** The filename to write the cache file to.\n * @defaultValue The `tadaTurboLocation` configuration option */\n output: string | undefined;\n /** The `tsconfig.json` to use for configurations and the TypeScript program.\n * @defaultValue A `tsconfig.json` in the current or any parent directory. */\n tsconfig: string | undefined;\n /** Whether to disable terminal output when using the programmatic API.\n * @defaultValue `false` */\n silent?: boolean;\n}\n\nexport async function* run(tty: TTY, opts: OutputOptions): AsyncIterable<ComposeInput> {\n let projects: ProjectContext[];\n try {\n projects = await loadProjects(opts.tsconfig);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n if (projects.length > 1 && (opts.output || tty.pipeTo)) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple projects are configured.\\n' +\n logger.hint(\n `You can only output all projects to their ${logger.code(\n '\"tadaOutputLocation\"'\n )} options\\n` +\n `when multiple projects are set up through ${logger.code('\"references\"')}.`\n )\n );\n }\n\n for (const project of projects) {\n if (projects.length > 1) yield logger.projectHeader(project.label);\n yield* runProject(tty, opts, project);\n }\n}\n\n/** Generates the introspection output for a single project. */\nasync function* runProject(\n tty: TTY,\n opts: OutputOptions,\n project: ProjectContext\n): AsyncIterable<ComposeInput> {\n const { pluginConfig, projectPath } = project;\n\n let schemaRef = loadRef(pluginConfig);\n try {\n schemaRef = await schemaRef.load({ rootPath: projectPath });\n } catch (error) {\n throw logger.externalError('Failed to load schema(s).', error);\n }\n\n if ('schema' in pluginConfig) {\n const schema = schemaRef.current!;\n\n let destination: WriteTarget;\n if (!opts.output && tty.pipeTo) {\n destination = tty.pipeTo;\n } else if (opts.output) {\n destination = path.resolve(process.cwd(), opts.output);\n } else if (pluginConfig.tadaOutputLocation) {\n destination = path.resolve(projectPath, pluginConfig.tadaOutputLocation);\n } else {\n throw logger.errorMessage(\n 'No output path was specified to write the output file to.\\n' +\n logger.hint(\n `You have to either set ${logger.code(\n '\"tadaOutputLocation\"'\n )} in your configuration,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n }\n\n const existing = await readOutput(destination);\n let contents: string;\n try {\n contents = outputIntrospectionFile(minifyIntrospection(schema.introspection), {\n fileType:\n destination && typeof destination === 'string'\n ? destination\n : opts.forceTSFormat\n ? '.ts'\n : '.d.ts',\n shouldPreprocess: !opts.disablePreprocessing,\n preamble: existing ? extractIntrospectionHeader(existing) || undefined : undefined,\n });\n } catch (error) {\n throw logger.externalError('Could not generate introspection output', error);\n }\n\n try {\n await writeOutput(destination, contents);\n } catch (error) {\n throw logger.externalError(\n 'Something went wrong while writing the introspection file',\n error\n );\n }\n\n yield logger.summary(!opts.forceTSFormat && typeof destination !== 'string');\n } else {\n if (opts.output) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple schemas are configured.\\n' +\n logger.hint(\n `You can only output all schemas to their ${logger.code(\n '\"tadaOutputLocation\"'\n )} options\\n` + `when multiple ${logger.code('schemas')} are set up.`\n )\n );\n }\n\n for (const schemaName in schemaRef.multi) {\n const schema = schemaRef.multi[schemaName];\n if (!schema) {\n continue;\n } else if (!schema.tadaOutputLocation) {\n throw logger.errorMessage(\n `No output path was specified to write the '${schemaName}' schema to.\\n` +\n logger.hint(\n `You have to set ${logger.code('\"tadaOutputLocation\"')} in each schema configuration.`\n )\n );\n }\n\n const destination = path.resolve(projectPath, schema.tadaOutputLocation);\n const existing = await readOutput(destination);\n let contents: string;\n try {\n contents = outputIntrospectionFile(minifyIntrospection(schema.introspection), {\n fileType: schema.tadaOutputLocation,\n shouldPreprocess: !opts.disablePreprocessing,\n preamble: existing ? extractIntrospectionHeader(existing) || undefined : undefined,\n });\n } catch (error) {\n throw logger.externalError(\n `Could not generate any output for the '${schemaName}' schema`,\n error\n );\n }\n\n try {\n await writeOutput(destination, contents);\n } catch (error) {\n throw logger.externalError(\n `Something went wrong while writing the '${schemaName}' schema's output`,\n error\n );\n }\n }\n\n yield logger.summary();\n }\n}\n","import { Command, Option } from 'clipanion';\n\nimport type { OutputOptions } from './runner';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class GenerateOutputCommand extends Command {\n static paths = [['generate-output'], ['generate', 'output']];\n\n forceTSFormat = Option.Boolean('--force-ts-format', false, {\n description: 'Forces the `.ts` output format when the output is piped',\n hidden: true,\n });\n\n disablePreprocessing = Option.Boolean('--disable-preprocessing', false, {\n description:\n 'Disables pre-processing, which is an internal introspection format generated ahead of time',\n });\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` used to read, unless `--output` is passed.',\n });\n\n output = Option.String('--output,-o', {\n description:\n 'Specifies where to output the file to.\\tDefault: The `tadaOutputLocation` configuration option',\n });\n\n async execute() {\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n forceTSFormat: this.forceTSFormat,\n disablePreprocessing: this.disablePreprocessing,\n output: this.output,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Outputs the `gql.tada` output file manually.\n *\n * @remarks\n * Loads the schema from the specified `schema` configuration option and writes the output file\n * to the specified output location.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#generateoutput}\n */\nexport async function generateOutput(opts: OutputOptions): Promise<void> {\n const tty = initTTY({ disableTTY: true, silent: opts.silent });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","import { pipe, interval, map, concat, fromValue } from 'wonka';\n\nimport * as path from 'node:path';\nimport * as t from '../../term';\n\nimport type { PersistedWarning } from './types';\nimport { indent } from '../shared/logger';\n\nexport * from '../shared/logger';\n\nconst CWD = process.cwd();\nconst INDENT = ' ';\n\nexport function warningFile(filePath: string) {\n const relativePath = path.relative(CWD, filePath);\n if (!relativePath.startsWith('..')) filePath = relativePath;\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Underline),\n filePath,\n t.cmd(t.CSI.Style, t.Style.NoUnderline),\n '\\n',\n ]);\n}\n\nexport function warningMessage(message: PersistedWarning) {\n return t.text([\n INDENT,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${message.line}:${message.col}`,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n indent(message.message.trim(), t.text([INDENT, t.Chars.Tab])),\n t.Chars.Newline,\n ]);\n}\n\nconst documentSummary = (documentCount: number | Record<string, number>) => {\n let out = '';\n if (\n typeof documentCount !== 'number'\n ? Object.values(documentCount).every((value) => !value)\n : !documentCount\n ) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.Blue),\n `${t.Icons.Info} No persisted documents were found `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `(Persisted manifests were not generated)\\n`,\n ]);\n } else if (typeof documentCount === 'number') {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Persisted manifest was generated successfully `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `(${documentCount} documents extracted)\\n`,\n ]);\n } else {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Persisted manifests were generated successfully.\\n`,\n ]);\n for (const schemaName in documentCount) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${documentCount[schemaName]} documents extracted for the '${schemaName}' schema\\n`,\n ]);\n }\n }\n return out;\n};\n\nexport function warningSummary(warningCount: number) {\n return t.error([t.cmd(t.CSI.Style, t.Style.Red), `${t.Icons.Cross} ${warningCount} warnings\\n`]);\n}\n\nexport function infoSummary(warningCount: number, documentCount: number | Record<string, number>) {\n let out = '';\n if (warningCount) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ` ${warningCount} warnings\\n`,\n ]);\n }\n out += documentSummary(documentCount);\n return out;\n}\n\nexport function warningGithub(message: PersistedWarning): void {\n t.githubAnnotation('warning', message.message, {\n file: message.file,\n line: message.line,\n col: message.col,\n });\n}\n\nexport function runningPersisted(file?: number, ofFiles?: number) {\n const progress = file ? (ofFiles ? `(${file}/${ofFiles})` : `(${file})`) : '';\n const frame = (state: number) =>\n t.text([\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.dotSpinner[state % t.dotSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n `Scanning files${t.Chars.Ellipsis} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n progress,\n ]);\n return concat([\n fromValue(frame(0)),\n pipe(\n interval(150),\n map((state) => frame(state + 1))\n ),\n ]);\n}\n","import * as path from 'node:path';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, writeOutput } from '../shared';\nimport type { PersistedDocument } from './types';\nimport * as logger from './logger';\n\nexport interface PersistedOptions {\n /** Whether to disable normalization of GraphQL documents in the output.\n * @defaultValue `false`\n * @remarks\n * Normalizing a GraphQL document means to parse then print them, which\n * removes comments and normalizes formatting.\n */\n disableNormalization?: boolean;\n /** The `tsconfig.json` to use for configurations and the TypeScript program.\n * @defaultValue A `tsconfig.json` in the current or any parent directory. */\n tsconfig: string | undefined;\n /** The filename to write the persisted JSON manifest to.\n * @defaultValue The `schema` configuration option */\n output: string | undefined;\n /** Whether to fail instead of just logging a warning. */\n failOnWarn: boolean;\n}\n\nexport async function* run(tty: TTY, opts: PersistedOptions): AsyncIterable<ComposeInput> {\n let projects: ProjectContext[];\n try {\n projects = await loadProjects(opts.tsconfig);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n if (projects.length > 1 && (opts.output || tty.pipeTo)) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple projects are configured.\\n' +\n logger.hint(\n `You can only output all projects to their ${logger.code(\n '\"tadaPersistedLocation\"'\n )} options\\n` +\n `when multiple projects are set up through ${logger.code('\"references\"')}.`\n )\n );\n }\n\n let totalWarnings = 0;\n let failedProjects = false;\n for (const project of projects) {\n if (projects.length > 1) yield logger.projectHeader(project.label);\n const result = yield* runProject(tty, opts, project, projects.length > 1);\n totalWarnings += result.warnings;\n failedProjects = failedProjects || result.failed;\n }\n\n if (failedProjects) {\n throw logger.warningSummary(totalWarnings);\n }\n}\n\ninterface ProjectResult {\n warnings: number;\n failed: boolean;\n}\n\n/** Generates the persisted manifest for a single project. */\nasync function* runProject(\n tty: TTY,\n opts: PersistedOptions,\n project: ProjectContext,\n deferWarnings: boolean\n): AsyncGenerator<ComposeInput, ProjectResult> {\n const { runPersisted } = await import('./thread');\n\n const { pluginConfig, projectPath } = project;\n\n if (tty.isInteractive) yield logger.runningPersisted();\n\n const generator = runPersisted({\n disableNormalization: !!opts.disableNormalization,\n rootPath: project.configResult.rootPath,\n tsconfigPath: project.configResult.tsconfigPath,\n configPath: project.configResult.configPath,\n pluginConfig,\n });\n\n const documents: PersistedDocument[] = [];\n let warnings = 0;\n let totalFileCount = 0;\n let fileCount = 0;\n\n try {\n if (tty.isInteractive) yield logger.runningPersisted();\n\n for await (const signal of generator) {\n if (signal.kind === 'EXTERNAL_WARNING') {\n yield logger.experimentMessage(\n `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n );\n } else if (signal.kind === 'FILE_COUNT') {\n totalFileCount = signal.fileCount;\n } else {\n fileCount++;\n documents.push(...signal.documents);\n warnings += signal.warnings.length;\n if (signal.warnings.length) {\n let buffer = logger.warningFile(signal.filePath);\n for (const warning of signal.warnings) {\n buffer += logger.warningMessage(warning);\n logger.warningGithub(warning);\n }\n yield buffer + '\\n';\n }\n }\n\n if (tty.isInteractive) yield logger.runningPersisted(fileCount, totalFileCount);\n }\n } catch (error) {\n throw logger.externalError('Could not generate persisted manifest file', error);\n }\n\n if ('schema' in pluginConfig) {\n let destination: WriteTarget;\n if (!opts.output && tty.pipeTo) {\n destination = tty.pipeTo;\n } else if (opts.output) {\n destination = path.resolve(process.cwd(), opts.output);\n } else if (pluginConfig.tadaPersistedLocation) {\n destination = path.resolve(projectPath, pluginConfig.tadaPersistedLocation);\n } else {\n throw logger.errorMessage(\n 'No output path was specified to write the persisted manifest file to.\\n' +\n logger.hint(\n `You have to either set ${logger.code(\n '\"tadaPersistedLocation\"'\n )} in your configuration,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n }\n\n if (warnings && opts.failOnWarn) {\n if (!deferWarnings) throw logger.warningSummary(warnings);\n return { warnings, failed: true };\n } else if (documents.length) {\n try {\n const json: Record<string, string> = {};\n for (const item of documents) json[item.hashKey] = item.document;\n const contents = JSON.stringify(json, null, 2);\n await writeOutput(destination, contents);\n } catch (error) {\n throw logger.externalError(\n 'Something went wrong while writing the persisted manifest file.',\n error\n );\n }\n }\n\n yield logger.infoSummary(warnings, documents.length);\n } else {\n if (opts.output) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple schemas are configured.\\n' +\n logger.hint(\n `You can only output all schemas to their ${logger.code(\n '\"tadaPersistedLocation\"'\n )} options\\n` + `when multiple ${logger.code('schemas')} are set up.`\n )\n );\n }\n\n const documentCount: Record<string, number> = {};\n for (const schemaConfig of pluginConfig.schemas) {\n const { name, tadaPersistedLocation } = schemaConfig;\n if (!tadaPersistedLocation) {\n throw logger.errorMessage(\n `No output path was specified to write the '${name}' schema to.\\n` +\n logger.hint(\n `You have to set ${logger.code(\n '\"tadaPersistedLocation\"'\n )} in each schema configuration.`\n )\n );\n }\n\n try {\n documentCount[name] = 0;\n const json: Record<string, string> = {};\n for (const item of documents) {\n if (item.schemaName === name) {\n json[item.hashKey] = item.document;\n documentCount[name]++;\n }\n }\n if (documentCount[name]) {\n const contents = JSON.stringify(json, null, 2);\n await writeOutput(path.resolve(projectPath, tadaPersistedLocation), contents);\n }\n } catch (error) {\n throw logger.externalError(\n `Something went wrong while writing the '${name}' schema's persisted manifest file.`,\n error\n );\n }\n }\n\n if (warnings && opts.failOnWarn) {\n if (!deferWarnings) throw logger.warningSummary(warnings);\n return { warnings, failed: true };\n } else {\n yield logger.infoSummary(warnings, documentCount);\n }\n }\n\n return { warnings, failed: false };\n}\n","import { Command, Option } from 'clipanion';\n\nimport type { PersistedOptions } from './runner';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class GeneratePersisted extends Command {\n static paths = [['generate-persisted'], ['generate', 'persisted']];\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` used to read, unless `--output` is passed.',\n });\n\n disableNormalization = Option.Boolean('--disable-normalization', false, {\n description: 'Disables normalizing of GraphQL documents (parsing then printing documents)',\n });\n\n failOnWarn = Option.Boolean('--fail-on-warn', false, {\n description: 'Triggers an error and a non-zero exit code if any warnings have been reported',\n });\n\n output = Option.String('--output,-o', {\n description:\n 'Specifies where to output the file to.\\tDefault: The `tadaPersistedLocation` configuration option',\n });\n\n async execute() {\n // TODO: Add verbose/log/list/debug/trace option that outputs discovered documents (by name) per file\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n disableNormalization: this.disableNormalization,\n failOnWarn: this.failOnWarn,\n output: this.output,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Generates a JSON manifest file of all `graphql.persisted()` documents.\n *\n * @remarks\n * Scans your code for `graphql.persisted()` calls and generates a JSON\n * manifest file containing a mapping of document IDs to the GraphQL document strings.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#generatepersisted}\n */\nexport async function generatePersisted(opts: PersistedOptions) {\n const tty = initTTY({ disableTTY: true });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","const simpleKeyRegExp = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\nfunction getPrintable(value) {\n if (value === null)\n return `null`;\n if (value === undefined)\n return `undefined`;\n if (value === ``)\n return `an empty string`;\n if (typeof value === 'symbol')\n return `<${value.toString()}>`;\n if (Array.isArray(value))\n return `an array`;\n return JSON.stringify(value);\n}\nfunction getPrintableArray(value, conjunction) {\n if (value.length === 0)\n return `nothing`;\n if (value.length === 1)\n return getPrintable(value[0]);\n const rest = value.slice(0, -1);\n const trailing = value[value.length - 1];\n const separator = value.length > 2\n ? `, ${conjunction} `\n : ` ${conjunction} `;\n return `${rest.map(value => getPrintable(value)).join(`, `)}${separator}${getPrintable(trailing)}`;\n}\nfunction computeKey(state, key) {\n var _a, _b, _c;\n if (typeof key === `number`) {\n return `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}[${key}]`;\n }\n else if (simpleKeyRegExp.test(key)) {\n return `${(_b = state === null || state === void 0 ? void 0 : state.p) !== null && _b !== void 0 ? _b : ``}.${key}`;\n }\n else {\n return `${(_c = state === null || state === void 0 ? void 0 : state.p) !== null && _c !== void 0 ? _c : `.`}[${JSON.stringify(key)}]`;\n }\n}\nfunction plural(n, singular, plural) {\n return n === 1 ? singular : plural;\n}\n\nconst colorStringRegExp = /^#[0-9a-f]{6}$/i;\nconst colorStringAlphaRegExp = /^#[0-9a-f]{6}([0-9a-f]{2})?$/i;\n// https://stackoverflow.com/a/475217/880703\nconst base64RegExp = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n// https://stackoverflow.com/a/14166194/880703\nconst uuid4RegExp = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$/i;\n// https://stackoverflow.com/a/28022901/880703 + https://www.debuggex.com/r/bl8J35wMKk48a7u_\nconst iso8601RegExp = /^(?:[1-9]\\d{3}(-?)(?:(?:0[1-9]|1[0-2])\\1(?:0[1-9]|1\\d|2[0-8])|(?:0[13-9]|1[0-2])\\1(?:29|30)|(?:0[13578]|1[02])(?:\\1)31|00[1-9]|0[1-9]\\d|[12]\\d{2}|3(?:[0-5]\\d|6[0-5]))|(?:[1-9]\\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)(?:(-?)02(?:\\2)29|-?366))T(?:[01]\\d|2[0-3])(:?)[0-5]\\d(?:\\3[0-5]\\d)?(?:Z|[+-][01]\\d(?:\\3[0-5]\\d)?)$/;\n\nfunction pushError({ errors, p } = {}, message) {\n errors === null || errors === void 0 ? void 0 : errors.push(`${p !== null && p !== void 0 ? p : `.`}: ${message}`);\n return false;\n}\nfunction makeSetter(target, key) {\n return (v) => {\n target[key] = v;\n };\n}\nfunction makeCoercionFn(target, key) {\n return (v) => {\n const previous = target[key];\n target[key] = v;\n return makeCoercionFn(target, key).bind(null, previous);\n };\n}\nfunction makeLazyCoercionFn(fn, orig, generator) {\n const commit = () => {\n fn(generator());\n return revert;\n };\n const revert = () => {\n fn(orig);\n return commit;\n };\n return commit;\n}\n\n/**\n * Create a validator that always returns true and never refines the type.\n */\nfunction isUnknown() {\n return makeValidator({\n test: (value, state) => {\n return true;\n },\n });\n}\nfunction isLiteral(expected) {\n return makeValidator({\n test: (value, state) => {\n if (value !== expected)\n return pushError(state, `Expected ${getPrintable(expected)} (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a string.\n * Refines the type to `string`.\n */\nfunction isString() {\n return makeValidator({\n test: (value, state) => {\n if (typeof value !== `string`)\n return pushError(state, `Expected a string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\nfunction isEnum(enumSpec) {\n const valuesArray = Array.isArray(enumSpec) ? enumSpec : Object.values(enumSpec);\n const isAlphaNum = valuesArray.every(item => typeof item === 'string' || typeof item === 'number');\n const values = new Set(valuesArray);\n if (values.size === 1)\n return isLiteral([...values][0]);\n return makeValidator({\n test: (value, state) => {\n if (!values.has(value)) {\n if (isAlphaNum) {\n return pushError(state, `Expected one of ${getPrintableArray(valuesArray, `or`)} (got ${getPrintable(value)})`);\n }\n else {\n return pushError(state, `Expected a valid enumeration value (got ${getPrintable(value)})`);\n }\n }\n return true;\n },\n });\n}\nconst BOOLEAN_COERCIONS = new Map([\n [`true`, true],\n [`True`, true],\n [`1`, true],\n [1, true],\n [`false`, false],\n [`False`, false],\n [`0`, false],\n [0, false],\n]);\n/**\n * Create a validator that only returns true when the tested value is a\n * boolean. Refines the type to `boolean`.\n *\n * Supports coercion:\n * - 'true' / 'True' / '1' / 1 will turn to `true`\n * - 'false' / 'False' / '0' / 0 will turn to `false`\n */\nfunction isBoolean() {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof value !== `boolean`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const coercion = BOOLEAN_COERCIONS.get(value);\n if (typeof coercion !== `undefined`) {\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);\n return true;\n }\n }\n return pushError(state, `Expected a boolean (got ${getPrintable(value)})`);\n }\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a\n * number (including floating numbers; use `cascade` and `isInteger` to\n * restrict the range further). Refines the type to `number`.\n *\n * Supports coercion.\n */\nfunction isNumber() {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof value !== `number`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n let coercion;\n if (typeof value === `string`) {\n let val;\n try {\n val = JSON.parse(value);\n }\n catch (_b) { }\n // We check against JSON.stringify that the output is the same to ensure that the number can be safely represented in JS\n if (typeof val === `number`) {\n if (JSON.stringify(val) === value) {\n coercion = val;\n }\n else {\n return pushError(state, `Received a number that can't be safely represented by the runtime (${value})`);\n }\n }\n }\n if (typeof coercion !== `undefined`) {\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);\n return true;\n }\n }\n return pushError(state, `Expected a number (got ${getPrintable(value)})`);\n }\n return true;\n },\n });\n}\n/**\n * Important: This validator only makes sense when used in conjunction with\n * coercion! It will always error when used without.\n *\n * Create a validator that only returns true when the tested value is a\n * JSON representation of the expected type. Refines the type to the\n * expected type, and casts the value into its inner value.\n */\nfunction isPayload(spec) {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) === `undefined`)\n return pushError(state, `The isPayload predicate can only be used with coercion enabled`);\n if (typeof state.coercion === `undefined`)\n return pushError(state, `Unbound coercion result`);\n if (typeof value !== `string`)\n return pushError(state, `Expected a string (got ${getPrintable(value)})`);\n let inner;\n try {\n inner = JSON.parse(value);\n }\n catch (_b) {\n return pushError(state, `Expected a JSON string (got ${getPrintable(value)})`);\n }\n const wrapper = { value: inner };\n if (!spec(inner, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(wrapper, `value`) })))\n return false;\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, wrapper.value)]);\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a\n * valid date. Refines the type to `Date`.\n *\n * Supports coercion via one of the following formats:\n * - ISO86001 strings\n * - Unix timestamps\n */\nfunction isDate() {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (!(value instanceof Date)) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n let coercion;\n if (typeof value === `string` && iso8601RegExp.test(value)) {\n coercion = new Date(value);\n }\n else {\n let timestamp;\n if (typeof value === `string`) {\n let val;\n try {\n val = JSON.parse(value);\n }\n catch (_b) { }\n if (typeof val === `number`) {\n timestamp = val;\n }\n }\n else if (typeof value === `number`) {\n timestamp = value;\n }\n if (typeof timestamp !== `undefined`) {\n if (Number.isSafeInteger(timestamp) || !Number.isSafeInteger(timestamp * 1000)) {\n coercion = new Date(timestamp * 1000);\n }\n else {\n return pushError(state, `Received a timestamp that can't be safely represented by the runtime (${value})`);\n }\n }\n }\n if (typeof coercion !== `undefined`) {\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);\n return true;\n }\n }\n return pushError(state, `Expected a date (got ${getPrintable(value)})`);\n }\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * array whose all values match the provided subspec. Refines the type to\n * `Array<T>`, with `T` being the subspec inferred type.\n *\n * Supports coercion if the `delimiter` option is set, in which case strings\n * will be split accordingly.\n */\nfunction isArray(spec, { delimiter } = {}) {\n return makeValidator({\n test: (value, state) => {\n var _a;\n const originalValue = value;\n if (typeof value === `string` && typeof delimiter !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n value = value.split(delimiter);\n }\n }\n if (!Array.isArray(value))\n return pushError(state, `Expected an array (got ${getPrintable(value)})`);\n let valid = true;\n for (let t = 0, T = value.length; t < T; ++t) {\n valid = spec(value[t], Object.assign(Object.assign({}, state), { p: computeKey(state, t), coercion: makeCoercionFn(value, t) })) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n if (value !== originalValue)\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);\n return valid;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * set whose all values match the provided subspec. Refines the type to\n * `Set<T>`, with `T` being the subspec inferred type.\n *\n * Supports coercion from arrays (or anything that can be coerced into an\n * array).\n */\nfunction isSet(spec, { delimiter } = {}) {\n const isArrayValidator = isArray(spec, { delimiter });\n return makeValidator({\n test: (value, state) => {\n var _a, _b;\n if (Object.getPrototypeOf(value).toString() === `[object Set]`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const originalValues = [...value];\n const coercedValues = [...value];\n if (!isArrayValidator(coercedValues, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n const updateValue = () => coercedValues.some((val, t) => val !== originalValues[t])\n ? new Set(coercedValues)\n : value;\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, makeLazyCoercionFn(state.coercion, value, updateValue)]);\n return true;\n }\n else {\n let valid = true;\n for (const subValue of value) {\n valid = spec(subValue, Object.assign({}, state)) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n return valid;\n }\n }\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const store = { value };\n if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(store, `value`) })))\n return false;\n state.coercions.push([(_b = state.p) !== null && _b !== void 0 ? _b : `.`, makeLazyCoercionFn(state.coercion, value, () => new Set(store.value))]);\n return true;\n }\n return pushError(state, `Expected a set (got ${getPrintable(value)})`);\n }\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * map whose all values match the provided subspecs. Refines the type to\n * `Map<U, V>`, with `U` being the key subspec inferred type and `V` being\n * the value subspec inferred type.\n *\n * Supports coercion from array of tuples (or anything that can be coerced into\n * an array of tuples).\n */\nfunction isMap(keySpec, valueSpec) {\n const isArrayValidator = isArray(isTuple([keySpec, valueSpec]));\n const isRecordValidator = isRecord(valueSpec, { keys: keySpec });\n return makeValidator({\n test: (value, state) => {\n var _a, _b, _c;\n if (Object.getPrototypeOf(value).toString() === `[object Map]`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const originalValues = [...value];\n const coercedValues = [...value];\n if (!isArrayValidator(coercedValues, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n const updateValue = () => coercedValues.some((val, t) => val[0] !== originalValues[t][0] || val[1] !== originalValues[t][1])\n ? new Map(coercedValues)\n : value;\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, makeLazyCoercionFn(state.coercion, value, updateValue)]);\n return true;\n }\n else {\n let valid = true;\n for (const [key, subValue] of value) {\n valid = keySpec(key, Object.assign({}, state)) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n valid = valueSpec(subValue, Object.assign(Object.assign({}, state), { p: computeKey(state, key) })) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n return valid;\n }\n }\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const store = { value };\n if (Array.isArray(value)) {\n if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n state.coercions.push([(_b = state.p) !== null && _b !== void 0 ? _b : `.`, makeLazyCoercionFn(state.coercion, value, () => new Map(store.value))]);\n return true;\n }\n else {\n if (!isRecordValidator(value, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(store, `value`) })))\n return false;\n state.coercions.push([(_c = state.p) !== null && _c !== void 0 ? _c : `.`, makeLazyCoercionFn(state.coercion, value, () => new Map(Object.entries(store.value)))]);\n return true;\n }\n }\n return pushError(state, `Expected a map (got ${getPrintable(value)})`);\n }\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a\n * tuple whose each value matches the corresponding subspec. Refines the type\n * into a tuple whose each item has the type inferred by the corresponding\n * tuple.\n *\n * Supports coercion if the `delimiter` option is set, in which case strings\n * will be split accordingly.\n */\nfunction isTuple(spec, { delimiter } = {}) {\n const lengthValidator = hasExactLength(spec.length);\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof value === `string` && typeof delimiter !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n value = value.split(delimiter);\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);\n }\n }\n if (!Array.isArray(value))\n return pushError(state, `Expected a tuple (got ${getPrintable(value)})`);\n let valid = lengthValidator(value, Object.assign({}, state));\n for (let t = 0, T = value.length; t < T && t < spec.length; ++t) {\n valid = spec[t](value[t], Object.assign(Object.assign({}, state), { p: computeKey(state, t), coercion: makeCoercionFn(value, t) })) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n return valid;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object with any amount of properties that must all match the provided\n * subspec. Refines the type to `Record<string, T>`, with `T` being the\n * subspec inferred type.\n *\n * Keys can be optionally validated as well by using the `keys` optional\n * subspec parameter.\n */\nfunction isRecord(spec, { keys: keySpec = null, } = {}) {\n const isArrayValidator = isArray(isTuple([keySpec !== null && keySpec !== void 0 ? keySpec : isString(), spec]));\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (Array.isArray(value)) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n value = Object.fromEntries(value);\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);\n return true;\n }\n }\n if (typeof value !== `object` || value === null)\n return pushError(state, `Expected an object (got ${getPrintable(value)})`);\n const keys = Object.keys(value);\n let valid = true;\n for (let t = 0, T = keys.length; t < T && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null); ++t) {\n const key = keys[t];\n const sub = value[key];\n if (key === `__proto__` || key === `constructor`) {\n valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`);\n continue;\n }\n if (keySpec !== null && !keySpec(key, state)) {\n valid = false;\n continue;\n }\n if (!spec(sub, Object.assign(Object.assign({}, state), { p: computeKey(state, key), coercion: makeCoercionFn(value, key) }))) {\n valid = false;\n continue;\n }\n }\n return valid;\n },\n });\n}\n/**\n * @deprecated Replace `isDict` by `isRecord`\n */\nfunction isDict(spec, opts = {}) {\n return isRecord(spec, opts);\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object whose all properties match their corresponding subspec. Refines\n * the type into an object whose each property has the type inferred by the\n * corresponding subspec.\n *\n * Unlike `t.isPartial`, `t.isObject` doesn't allow extraneous properties by\n * default. This behaviour can be altered by using the `extra` optional\n * subspec parameter, which will be called to validate an object only\n * containing the extraneous properties.\n *\n * Calling `t.isObject(..., {extra: t.isRecord(t.isUnknown())})` is\n * essentially the same as calling `t.isPartial(...)`.\n */\nfunction isObject(props, { extra: extraSpec = null, } = {}) {\n const specKeys = Object.keys(props);\n const validator = makeValidator({\n test: (value, state) => {\n if (typeof value !== `object` || value === null)\n return pushError(state, `Expected an object (got ${getPrintable(value)})`);\n const keys = new Set([...specKeys, ...Object.keys(value)]);\n const extra = {};\n let valid = true;\n for (const key of keys) {\n if (key === `constructor` || key === `__proto__`) {\n valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`);\n }\n else {\n const spec = Object.prototype.hasOwnProperty.call(props, key)\n ? props[key]\n : undefined;\n const sub = Object.prototype.hasOwnProperty.call(value, key)\n ? value[key]\n : undefined;\n if (typeof spec !== `undefined`) {\n valid = spec(sub, Object.assign(Object.assign({}, state), { p: computeKey(state, key), coercion: makeCoercionFn(value, key) })) && valid;\n }\n else if (extraSpec === null) {\n valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Extraneous property (got ${getPrintable(sub)})`);\n }\n else {\n Object.defineProperty(extra, key, {\n enumerable: true,\n get: () => sub,\n set: makeSetter(value, key)\n });\n }\n }\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n if (extraSpec !== null && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null))\n valid = extraSpec(extra, state) && valid;\n return valid;\n },\n });\n return Object.assign(validator, {\n properties: props,\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object whose all properties match their corresponding subspec. Refines\n * the type into an object whose each property has the type inferred by the\n * corresponding subspec.\n *\n * Unlike `t.isObject`, `t.isPartial` allows extraneous properties. The\n * resulting type will reflect this behaviour by including an index\n * signature (each extraneous property being typed `unknown`).\n *\n * Calling `t.isPartial(...)` is essentially the same as calling\n * `t.isObject(..., {extra: t.isRecord(t.isUnknown())})`.\n */\nfunction isPartial(props) {\n return isObject(props, { extra: isRecord(isUnknown()) });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object whose prototype is derived from the given class. Refines the type\n * into a class instance.\n */\nconst isInstanceOf = (constructor) => makeValidator({\n test: (value, state) => {\n if (!(value instanceof constructor))\n return pushError(state, `Expected an instance of ${constructor.name} (got ${getPrintable(value)})`);\n return true;\n },\n});\n/**\n * Create a validator that only returns true when the tested value is an\n * object matching any of the provided subspecs. If the optional `exclusive`\n * parameter is set to `true`, the behaviour changes so that the validator\n * only returns true when exactly one subspec matches.\n */\nconst isOneOf = (specs, { exclusive = false, } = {}) => makeValidator({\n test: (value, state) => {\n var _a, _b, _c;\n const matches = [];\n const errorBuffer = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined`\n ? [] : undefined;\n for (let t = 0, T = specs.length; t < T; ++t) {\n const subErrors = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined`\n ? [] : undefined;\n const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`\n ? [] : undefined;\n if (specs[t](value, Object.assign(Object.assign({}, state), { errors: subErrors, coercions: subCoercions, p: `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}#${t + 1}` }))) {\n matches.push([`#${t + 1}`, subCoercions]);\n if (!exclusive) {\n break;\n }\n }\n else {\n errorBuffer === null || errorBuffer === void 0 ? void 0 : errorBuffer.push(subErrors[0]);\n }\n }\n if (matches.length === 1) {\n const [, subCoercions] = matches[0];\n if (typeof subCoercions !== `undefined`)\n (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 ? void 0 : _b.push(...subCoercions);\n return true;\n }\n if (matches.length > 1)\n pushError(state, `Expected to match exactly a single predicate (matched ${matches.join(`, `)})`);\n else\n (_c = state === null || state === void 0 ? void 0 : state.errors) === null || _c === void 0 ? void 0 : _c.push(...errorBuffer);\n return false;\n },\n});\n\nfunction makeTrait(value) {\n return () => {\n return value;\n };\n}\nfunction makeValidator({ test }) {\n return makeTrait(test)();\n}\nclass TypeAssertionError extends Error {\n constructor({ errors } = {}) {\n let errorMessage = `Type mismatch`;\n if (errors && errors.length > 0) {\n errorMessage += `\\n`;\n for (const error of errors) {\n errorMessage += `\\n- ${error}`;\n }\n }\n super(errorMessage);\n }\n}\n/**\n * Check that the specified value matches the given validator, and throws an\n * exception if it doesn't. Refine the type if it passes.\n */\nfunction assert(val, validator) {\n if (!validator(val)) {\n throw new TypeAssertionError();\n }\n}\n/**\n * Check that the specified value matches the given validator, and throws an\n * exception if it doesn't. Refine the type if it passes.\n *\n * Thrown exceptions include details about what exactly looks invalid in the\n * tested value.\n */\nfunction assertWithErrors(val, validator) {\n const errors = [];\n if (!validator(val, { errors })) {\n throw new TypeAssertionError({ errors });\n }\n}\n/**\n * Compile-time only. Refine the type as if the validator was matching the\n * tested value, but doesn't actually run it. Similar to the classic `as`\n * operator in TypeScript.\n */\nfunction softAssert(val, validator) {\n // It's a soft assert; we tell TypeScript about the type, but we don't need to check it\n}\nfunction as(value, validator, { coerce = false, errors: storeErrors, throw: throws } = {}) {\n const errors = storeErrors ? [] : undefined;\n if (!coerce) {\n if (validator(value, { errors })) {\n return throws ? value : { value, errors: undefined };\n }\n else if (!throws) {\n return { value: undefined, errors: errors !== null && errors !== void 0 ? errors : true };\n }\n else {\n throw new TypeAssertionError({ errors });\n }\n }\n const state = { value };\n const coercion = makeCoercionFn(state, `value`);\n const coercions = [];\n if (!validator(value, { errors, coercion, coercions })) {\n if (!throws) {\n return { value: undefined, errors: errors !== null && errors !== void 0 ? errors : true };\n }\n else {\n throw new TypeAssertionError({ errors });\n }\n }\n for (const [, apply] of coercions)\n apply();\n if (throws) {\n return state.value;\n }\n else {\n return { value: state.value, errors: undefined };\n }\n}\n/**\n * Create and return a new function that apply the given validators to each\n * corresponding argument passed to the function and throws an exception in\n * case of a mismatch.\n */\nfunction fn(validators, fn) {\n const isValidArgList = isTuple(validators);\n return ((...args) => {\n const check = isValidArgList(args);\n if (!check)\n throw new TypeAssertionError();\n return fn(...args);\n });\n}\n\n/**\n * Create a validator that checks that the tested array or string has at least\n * the specified length.\n */\nfunction hasMinLength(length) {\n return makeValidator({\n test: (value, state) => {\n if (!(value.length >= length))\n return pushError(state, `Expected to have a length of at least ${length} elements (got ${value.length})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested array or string has at most\n * the specified length.\n */\nfunction hasMaxLength(length) {\n return makeValidator({\n test: (value, state) => {\n if (!(value.length <= length))\n return pushError(state, `Expected to have a length of at most ${length} elements (got ${value.length})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested array or string has exactly\n * the specified length.\n */\nfunction hasExactLength(length) {\n return makeValidator({\n test: (value, state) => {\n if (!(value.length === length))\n return pushError(state, `Expected to have a length of exactly ${length} elements (got ${value.length})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested array only contains unique\n * elements. The optional `map` parameter lets you define a transform to\n * apply before making the check (the result of this transform will be\n * discarded afterwards).\n */\nfunction hasUniqueItems({ map, } = {}) {\n return makeValidator({\n test: (value, state) => {\n const set = new Set();\n const dup = new Set();\n for (let t = 0, T = value.length; t < T; ++t) {\n const sub = value[t];\n const key = typeof map !== `undefined`\n ? map(sub)\n : sub;\n if (set.has(key)) {\n if (dup.has(key))\n continue;\n pushError(state, `Expected to contain unique elements; got a duplicate with ${getPrintable(value)}`);\n dup.add(key);\n }\n else {\n set.add(key);\n }\n }\n return dup.size === 0;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is strictly less than 0.\n */\nfunction isNegative() {\n return makeValidator({\n test: (value, state) => {\n if (!(value <= 0))\n return pushError(state, `Expected to be negative (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is equal or greater\n * than 0.\n */\nfunction isPositive() {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= 0))\n return pushError(state, `Expected to be positive (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is equal or greater\n * than the specified reference.\n */\nfunction isAtLeast(n) {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= n))\n return pushError(state, `Expected to be at least ${n} (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is equal or smaller\n * than the specified reference.\n */\nfunction isAtMost(n) {\n return makeValidator({\n test: (value, state) => {\n if (!(value <= n))\n return pushError(state, `Expected to be at most ${n} (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is between the\n * specified references (including the upper boundary).\n */\nfunction isInInclusiveRange(a, b) {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= a && value <= b))\n return pushError(state, `Expected to be in the [${a}; ${b}] range (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is between the\n * specified references (excluding the upper boundary).\n */\nfunction isInExclusiveRange(a, b) {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= a && value < b))\n return pushError(state, `Expected to be in the [${a}; ${b}[ range (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is an integer.\n *\n * By default Typanion will also check that it's a *safe* integer. For example,\n * 2^53 wouldn't be a safe integer because 2^53+1 would be rounded to 2^53,\n * which could put your applications at risk when used in loops.\n */\nfunction isInteger({ unsafe = false, } = {}) {\n return makeValidator({\n test: (value, state) => {\n if (value !== Math.round(value))\n return pushError(state, `Expected to be an integer (got ${value})`);\n if (!unsafe && !Number.isSafeInteger(value))\n return pushError(state, `Expected to be a safe integer (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string matches the given\n * regular expression.\n */\nfunction matchesRegExp(regExp) {\n return makeValidator({\n test: (value, state) => {\n if (!regExp.test(value))\n return pushError(state, `Expected to match the pattern ${regExp.toString()} (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string only contain lowercase\n * characters.\n */\nfunction isLowerCase() {\n return makeValidator({\n test: (value, state) => {\n if (value !== value.toLowerCase())\n return pushError(state, `Expected to be all-lowercase (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string only contain uppercase\n * characters.\n */\nfunction isUpperCase() {\n return makeValidator({\n test: (value, state) => {\n if (value !== value.toUpperCase())\n return pushError(state, `Expected to be all-uppercase (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is a valid UUID v4.\n */\nfunction isUUID4() {\n return makeValidator({\n test: (value, state) => {\n if (!uuid4RegExp.test(value))\n return pushError(state, `Expected to be a valid UUID v4 (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is a valid ISO8601\n * date.\n */\nfunction isISO8601() {\n return makeValidator({\n test: (value, state) => {\n if (!iso8601RegExp.test(value))\n return pushError(state, `Expected to be a valid ISO 8601 date string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is a valid hexadecimal\n * color. Setting the optional `alpha` parameter to `true` allows an additional\n * transparency channel to be included.\n */\nfunction isHexColor({ alpha = false, }) {\n return makeValidator({\n test: (value, state) => {\n const res = alpha\n ? colorStringRegExp.test(value)\n : colorStringAlphaRegExp.test(value);\n if (!res)\n return pushError(state, `Expected to be a valid hexadecimal color string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is valid base64.\n */\nfunction isBase64() {\n return makeValidator({\n test: (value, state) => {\n if (!base64RegExp.test(value))\n return pushError(state, `Expected to be a valid base 64 string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is valid JSON. A\n * optional spec can be passed as parameter, in which case the data will be\n * deserialized and validated against the spec (coercion will be disabled\n * for this check, and even if successful the returned value will still be\n * the original string).\n */\nfunction isJSON(spec = isUnknown()) {\n return makeValidator({\n test: (value, state) => {\n let data;\n try {\n data = JSON.parse(value);\n }\n catch (_a) {\n return pushError(state, `Expected to be a valid JSON string (got ${getPrintable(value)})`);\n }\n return spec(data, state);\n },\n });\n}\n\nfunction cascade(spec, ...followups) {\n const resolvedFollowups = Array.isArray(followups[0])\n ? followups[0]\n : followups;\n return makeValidator({\n test: (value, state) => {\n var _a, _b;\n const context = { value: value };\n const subCoercion = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`\n ? makeCoercionFn(context, `value`) : undefined;\n const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`\n ? [] : undefined;\n if (!spec(value, Object.assign(Object.assign({}, state), { coercion: subCoercion, coercions: subCoercions })))\n return false;\n const reverts = [];\n if (typeof subCoercions !== `undefined`)\n for (const [, coercion] of subCoercions)\n reverts.push(coercion());\n try {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (context.value !== value) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, context.value)]);\n }\n (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 ? void 0 : _b.push(...subCoercions);\n }\n return resolvedFollowups.every(spec => {\n return spec(context.value, state);\n });\n }\n finally {\n for (const revert of reverts) {\n revert();\n }\n }\n },\n });\n}\nfunction applyCascade(spec, ...followups) {\n const resolvedFollowups = Array.isArray(followups[0])\n ? followups[0]\n : followups;\n return cascade(spec, resolvedFollowups);\n}\n/**\n * Wraps the given spec to also allow `undefined`.\n */\nfunction isOptional(spec) {\n return makeValidator({\n test: (value, state) => {\n if (typeof value === `undefined`)\n return true;\n return spec(value, state);\n },\n });\n}\n/**\n * Wraps the given spec to also allow `null`.\n */\nfunction isNullable(spec) {\n return makeValidator({\n test: (value, state) => {\n if (value === null)\n return true;\n return spec(value, state);\n },\n });\n}\nconst checks = {\n missing: (keys, key) => keys.has(key),\n undefined: (keys, key, value) => keys.has(key) && typeof value[key] !== `undefined`,\n nil: (keys, key, value) => keys.has(key) && value[key] != null,\n falsy: (keys, key, value) => keys.has(key) && !!value[key],\n};\n/**\n * Create a validator that checks that the tested object contains the specified\n * keys.\n*/\nfunction hasRequiredKeys(requiredKeys, options) {\n var _a;\n const requiredSet = new Set(requiredKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n const problems = [];\n for (const key of requiredSet)\n if (!check(keys, key, value))\n problems.push(key);\n if (problems.length > 0)\n return pushError(state, `Missing required ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, `and`)}`);\n return true;\n },\n });\n}\n/**\n* Create a validator that checks that the tested object contains at least one\n* of the specified keys.\n*/\nfunction hasAtLeastOneKey(requiredKeys, options) {\n var _a;\n const requiredSet = new Set(requiredKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = Object.keys(value);\n const valid = keys.some(key => check(requiredSet, key, value));\n if (!valid)\n return pushError(state, `Missing at least one property from ${getPrintableArray(Array.from(requiredSet), `or`)}`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested object contains none of the\n * specified keys.\n*/\nfunction hasForbiddenKeys(forbiddenKeys, options) {\n var _a;\n const forbiddenSet = new Set(forbiddenKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n const problems = [];\n for (const key of forbiddenSet)\n if (check(keys, key, value))\n problems.push(key);\n if (problems.length > 0)\n return pushError(state, `Forbidden ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, `and`)}`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested object contains at most one\n * of the specified keys.\n */\nfunction hasMutuallyExclusiveKeys(exclusiveKeys, options) {\n var _a;\n const exclusiveSet = new Set(exclusiveKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n const used = [];\n for (const key of exclusiveSet)\n if (check(keys, key, value))\n used.push(key);\n if (used.length > 1)\n return pushError(state, `Mutually exclusive properties ${getPrintableArray(used, `and`)}`);\n return true;\n },\n });\n}\nvar KeyRelationship;\n(function (KeyRelationship) {\n KeyRelationship[\"Forbids\"] = \"Forbids\";\n KeyRelationship[\"Requires\"] = \"Requires\";\n})(KeyRelationship || (KeyRelationship = {}));\nconst keyRelationships = {\n [KeyRelationship.Forbids]: {\n expect: false,\n message: `forbids using`,\n },\n [KeyRelationship.Requires]: {\n expect: true,\n message: `requires using`,\n },\n};\n/**\n * Create a validator that checks that, when the specified subject property is\n * set, the relationship is satisfied.\n */\nfunction hasKeyRelationship(subject, relationship, others, options) {\n var _a, _b;\n const skipped = new Set((_a = options === null || options === void 0 ? void 0 : options.ignore) !== null && _a !== void 0 ? _a : []);\n const check = checks[(_b = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _b !== void 0 ? _b : 'missing'];\n const otherSet = new Set(others);\n const spec = keyRelationships[relationship];\n const conjunction = relationship === KeyRelationship.Forbids\n ? `or`\n : `and`;\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n if (!check(keys, subject, value) || skipped.has(value[subject]))\n return true;\n const problems = [];\n for (const key of otherSet)\n if ((check(keys, key, value) && !skipped.has(value[key])) !== spec.expect)\n problems.push(key);\n if (problems.length >= 1)\n return pushError(state, `Property \"${subject}\" ${spec.message} ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, conjunction)}`);\n return true;\n },\n });\n}\n\nexport { KeyRelationship, TypeAssertionError, applyCascade, as, assert, assertWithErrors, cascade, fn, hasAtLeastOneKey, hasExactLength, hasForbiddenKeys, hasKeyRelationship, hasMaxLength, hasMinLength, hasMutuallyExclusiveKeys, hasRequiredKeys, hasUniqueItems, isArray, isAtLeast, isAtMost, isBase64, isBoolean, isDate, isDict, isEnum, isHexColor, isISO8601, isInExclusiveRange, isInInclusiveRange, isInstanceOf, isInteger, isJSON, isLiteral, isLowerCase, isMap, isNegative, isNullable, isNumber, isObject, isOneOf, isOptional, isPartial, isPayload, isPositive, isRecord, isSet, isString, isTuple, isUUID4, isUnknown, isUpperCase, makeTrait, makeValidator, matchesRegExp, softAssert };\n","import path from 'node:path';\nimport { printSchema } from 'graphql';\nimport type { GraphQLSchema } from 'graphql';\nimport { load } from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, writeOutput } from '../shared';\nimport * as logger from './logger';\n\nexport interface SchemaOptions {\n /** The filename to a `.graphql` SDL file, introspection JSON, or URL to a GraphQL API to introspect. */\n input: string;\n /** Object of headers to send when introspection a GraphQL API. */\n headers: Record<string, string> | undefined;\n /** The filename to write the GraphQL SDL file to.\n * @defaultValue The `schema` configuration option */\n output: string | undefined;\n /** The `tsconfig.json` to use for configurations and the TypeScript program.\n * @defaultValue A `tsconfig.json` in the current or any parent directory. */\n tsconfig: string | undefined;\n /** Whether to disable terminal output when using the programmatic API.\n * @defaultValue `false` */\n silent?: boolean;\n}\n\nexport async function* run(tty: TTY, opts: SchemaOptions): AsyncIterable<ComposeInput> {\n const origin = opts.headers ? { url: opts.input, headers: opts.headers } : opts.input;\n const loader = load({ rootPath: process.cwd(), origin });\n\n let schema: GraphQLSchema;\n try {\n const loadResult = await loader.load();\n schema = loadResult.schema;\n } catch (error) {\n throw logger.externalError('Failed to load schema.', error);\n }\n\n let destination: WriteTarget;\n if (!opts.output && tty.pipeTo) {\n destination = tty.pipeTo;\n } else if (opts.output) {\n destination = path.resolve(process.cwd(), opts.output);\n } else {\n let projects: ProjectContext[];\n try {\n projects = await loadProjects(opts.tsconfig);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n if (projects.length > 1) {\n throw logger.errorMessage(\n `Output path cannot be automatically determined when multiple projects are configured,\\n` +\n `because multiple projects are set up through ${logger.code('\"references\"')}.` +\n logger.hint(\n `You have to explicitly pass an ${logger.code(\n '--output'\n )} argument to this command,\\n` + 'or pipe this command to an output file.'\n )\n );\n }\n\n const { pluginConfig, projectPath } = projects[0];\n if (\n 'schema' in pluginConfig &&\n typeof pluginConfig.schema === 'string' &&\n path.extname(pluginConfig.schema) === '.graphql'\n ) {\n destination = path.resolve(projectPath, pluginConfig.schema);\n } else if (!('schema' in pluginConfig)) {\n throw logger.errorMessage(\n `Output path cannot be automatically determined when multiple schemas are configured,\\n` +\n `because multiple ${logger.code('schemas')} are set up.` +\n logger.hint(\n `You have to explicitly pass an ${logger.code(\n '--output'\n )} argument to this command,\\n` + 'or pipe this command to an output file.'\n )\n );\n } else {\n throw logger.errorMessage(\n `Output path cannot be automatically determined,\\n` +\n `because ${logger.code('schema')} is not a file path.\\n` +\n logger.hint(\n `You have to either set ${logger.code(\n '\"schema\"'\n )} in your configuration to a ${logger.code('.graphql')} file,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n }\n }\n\n try {\n await writeOutput(destination, printSchema(schema));\n } catch (error) {\n throw logger.externalError('Something went wrong while writing the introspection file', error);\n }\n\n yield logger.summary();\n}\n","import * as t from '../../term';\n\nexport * from '../shared/logger';\n\nexport function summary() {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Schema was generated successfully\\n`,\n ]);\n}\n","import * as t from 'typanion';\nimport { Command, Option } from 'clipanion';\n\nimport { exitCode } from '../../utils/error';\nimport type { SchemaOptions } from './runner';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nconst isHeaderEntries = t.isArray(t.cascade(t.isString(), t.matchesRegExp(/^[\\w-]+[ ]*:[ ]*.+/i)));\n\nconst parseHeaders = (\n headers: readonly string[] | undefined\n): Record<string, string> | undefined => {\n if (headers && headers.length) {\n return (headers || []).reduce((headers, entry) => {\n const index = entry.indexOf(':');\n const key = entry.slice(0, index);\n const value = entry.slice(index + 1);\n headers[key.trimEnd()] = value.trimStart();\n return headers;\n }, {});\n }\n};\n\nexport class GenerateSchema extends Command {\n static paths = [['generate-schema'], ['generate', 'schema']];\n\n input = Option.String({\n name: 'schema',\n required: true,\n });\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` used to read, unless `--output` is passed.',\n });\n\n output = Option.String('--output,-o', {\n description:\n \"Specify where to output the file to.\\tDefault: The `schema` configuration option, if it's a file path\",\n });\n\n headers = Option.Array('--header', {\n description: 'Headers to be used when introspection a schema from a remote URL',\n validator: isHeaderEntries,\n });\n\n async execute() {\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n input: this.input,\n headers: parseHeaders(this.headers),\n output: this.output,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Generates a GraphQL SDL file from a given GraphQL API URL or schema file.\n *\n * @remarks\n * Introspects a targeted GraphQL API by URL, a `.graphql` SDL or introspection\n * JSON file, and outputs a `.graphql` SDL file.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#generateschema}\n */\nexport async function generateSchema(opts: SchemaOptions) {\n const tty = initTTY({ disableTTY: true, silent: opts.silent });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","import { makeCommandOption, applyValidator, rerouteArguments } from './utils.mjs';\n\nfunction Array(descriptor, initialValueBase, optsBase) {\n const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});\n const { arity = 1 } = opts;\n const optNames = descriptor.split(`,`);\n const nameSet = new Set(optNames);\n return makeCommandOption({\n definition(builder) {\n builder.addOption({\n names: optNames,\n arity,\n hidden: opts === null || opts === void 0 ? void 0 : opts.hidden,\n description: opts === null || opts === void 0 ? void 0 : opts.description,\n required: opts.required,\n });\n },\n transformer(builder, key, state) {\n let usedName;\n let currentValue = typeof initialValue !== `undefined`\n ? [...initialValue]\n : undefined;\n for (const { name, value } of state.options) {\n if (!nameSet.has(name))\n continue;\n usedName = name;\n currentValue = currentValue !== null && currentValue !== void 0 ? currentValue : [];\n currentValue.push(value);\n }\n if (typeof currentValue !== `undefined`) {\n return applyValidator(usedName !== null && usedName !== void 0 ? usedName : key, currentValue, opts.validator);\n }\n else {\n return currentValue;\n }\n },\n });\n}\n\nexport { Array };\n","import { pipe, interval, map, concat, fromValue } from 'wonka';\n\nimport * as path from 'node:path';\nimport * as t from '../../term';\n\nimport type { TurboWarning } from './types';\nimport { indent } from '../shared/logger';\n\nexport * from '../shared/logger';\n\nconst CWD = process.cwd();\nconst INDENT = ' ';\n\nexport function warningFile(filePath: string) {\n const relativePath = path.relative(CWD, filePath);\n if (!relativePath.startsWith('..')) filePath = relativePath;\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Underline),\n filePath,\n t.cmd(t.CSI.Style, t.Style.NoUnderline),\n '\\n',\n ]);\n}\n\nexport function warningMessage(message: TurboWarning) {\n return t.text([\n INDENT,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${message.line}:${message.col}`,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n indent(message.message.trim(), t.text([INDENT, t.Chars.Tab])),\n t.Chars.Newline,\n ]);\n}\n\nconst reusedLabel = (count: number | undefined) => (count ? `, ${count} reused` : '');\n\nconst documentSummary = (\n documentCount: number | Record<string, number>,\n cachedCount?: number | Record<string, number>\n) => {\n let out = '';\n if (typeof documentCount === 'number') {\n const cachedLabel = reusedLabel(typeof cachedCount === 'number' ? cachedCount : undefined);\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Type cache was generated successfully `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `(${documentCount} document types cached${cachedLabel})\\n`,\n ]);\n } else {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Type caches were generated successfully.\\n`,\n ]);\n for (const schemaName in documentCount) {\n const cachedLabel = reusedLabel(\n cachedCount && typeof cachedCount !== 'number' ? cachedCount[schemaName] : undefined\n );\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${documentCount[schemaName]} document types cached for the '${schemaName}' schema${cachedLabel}\\n`,\n ]);\n }\n }\n return out;\n};\n\nexport function warningSummary(warningCount: number) {\n return t.error([t.cmd(t.CSI.Style, t.Style.Red), `${t.Icons.Cross} ${warningCount} warnings\\n`]);\n}\n\nexport function infoSummary(\n warningCount: number,\n documentCount: number | Record<string, number>,\n cachedCount?: number | Record<string, number>\n) {\n let out = '';\n if (warningCount) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ` ${warningCount} warnings\\n`,\n ]);\n }\n out += documentSummary(documentCount, cachedCount);\n return out;\n}\n\nexport function warningGithub(message: TurboWarning): void {\n t.githubAnnotation('warning', message.message, {\n file: message.file,\n line: message.line,\n col: message.col,\n });\n}\n\nexport function runningTurbo(file?: number, ofFiles?: number) {\n const progress = file ? (ofFiles ? `(${file}/${ofFiles})` : `(${file})`) : '';\n const frame = (state: number) =>\n t.text([\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.dotSpinner[state % t.dotSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n `Scanning files${t.Chars.Ellipsis} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n progress,\n ]);\n return concat([\n fromValue(frame(0)),\n pipe(\n interval(150),\n map((state) => frame(state + 1))\n ),\n ]);\n}\n\nexport function hintMessage(message: string) {\n return t.error([\n t.cmd(t.CSI.Style, [t.Style.Yellow, t.Style.Bold]),\n `${t.Icons.Warning} Note: `,\n t.cmd(t.CSI.Style, t.Style.Reset),\n `${message.trim()}\\n\\n`,\n ]);\n}\n","import * as path from 'node:path';\n\nimport { extractIntrospectionHeader } from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, writeOutput, readOutput } from '../shared';\nimport type { TurboDocument, GraphQLSourceFile, TurboPath } from './types';\nimport * as logger from './logger';\n\nconst PREAMBLE_IGNORE = ['/* eslint-disable */', '/* prettier-ignore */'].join('\\n') + '\\n';\n\nexport interface TurboOptions {\n /** Whether to fail instead of just logging a warning. */\n failOnWarn: boolean;\n /** The `tsconfig.json` to use for configurations and the TypeScript program.\n * @defaultValue A `tsconfig.json` in the current or any parent directory. */\n tsconfig: string | undefined;\n /** The filename to write the cache file to.\n * @defaultValue The `tadaTurboLocation` configuration option */\n output: string | undefined;\n}\n\nexport async function* run(tty: TTY, opts: TurboOptions): AsyncIterable<ComposeInput> {\n let projects: ProjectContext[];\n try {\n projects = await loadProjects(opts.tsconfig);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n if (projects.length > 1 && (opts.output || tty.pipeTo)) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple projects are configured.\\n' +\n logger.hint(\n `You can only output all projects to their ${logger.code(\n '\"tadaTurboLocation\"'\n )} options\\n` +\n `when multiple projects are set up through ${logger.code('\"references\"')}.`\n )\n );\n }\n\n let totalWarnings = 0;\n let failedProjects = false;\n for (const project of projects) {\n if (projects.length > 1) yield logger.projectHeader(project.label);\n const result = yield* runProject(tty, opts, project, projects.length > 1);\n totalWarnings += result.warnings;\n failedProjects = failedProjects || result.failed;\n }\n\n if (failedProjects) {\n throw logger.warningSummary(totalWarnings);\n }\n}\n\ninterface ProjectResult {\n warnings: number;\n failed: boolean;\n}\n\n/** Runs the turbo cache generation for a single project. */\nasync function* runProject(\n tty: TTY,\n opts: TurboOptions,\n project: ProjectContext,\n deferWarnings: boolean\n): AsyncGenerator<ComposeInput, ProjectResult> {\n const { runTurbo } = await import('./thread');\n\n const { pluginConfig, projectPath } = project;\n\n let destination: WriteTarget;\n const destinations: TurboPath[] = [];\n if ('schema' in pluginConfig) {\n if (!opts.output && tty.pipeTo) {\n destination = tty.pipeTo;\n } else if (opts.output) {\n destination = path.resolve(process.cwd(), opts.output);\n } else if (pluginConfig.tadaTurboLocation) {\n destination = path.resolve(projectPath, pluginConfig.tadaTurboLocation);\n } else if (pluginConfig.tadaOutputLocation) {\n destination = path.resolve(\n projectPath,\n pluginConfig.tadaOutputLocation,\n '..',\n 'graphql-cache.d.ts'\n );\n yield logger.hintMessage(\n 'No output location was specified.\\n' +\n `The turbo cache will by default be saved as ${logger.code('\"graphql-cache.d.ts\"')}.\\n` +\n logger.hint(\n `To change this, add a ${logger.code('\"tadaTurboLocation\"')} in your configuration,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n } else {\n throw logger.errorMessage(\n 'No output path was specified to write the output file to.\\n' +\n logger.hint(\n `You have to either set ${logger.code('\"tadaTurboLocation\"')} in your configuration,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n }\n } else if ('schemas' in pluginConfig) {\n for (const schemaConfig of pluginConfig.schemas) {\n if (schemaConfig.tadaTurboLocation)\n destinations.push({\n path: path.resolve(projectPath, schemaConfig.tadaTurboLocation),\n schemaName: schemaConfig.name,\n });\n }\n }\n\n const generator = runTurbo({\n rootPath: project.configResult.rootPath,\n tsconfigPath: project.configResult.tsconfigPath,\n configPath: project.configResult.configPath,\n pluginConfig,\n turboOutputPath: typeof destination! === 'string' ? destination : destinations,\n });\n\n const documents: TurboDocument[] = [];\n let graphqlSources: GraphQLSourceFile[] = [];\n let warnings = 0;\n let totalFileCount = 0;\n let fileCount = 0;\n let cachedDocumentCount = 0;\n\n try {\n if (tty.isInteractive) yield logger.runningTurbo();\n\n for await (const signal of generator) {\n if (signal.kind === 'EXTERNAL_WARNING') {\n yield logger.experimentMessage(\n `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n );\n } else if (signal.kind === 'FILE_COUNT') {\n totalFileCount = signal.fileCount;\n } else if (signal.kind === 'GRAPHQL_SOURCES') {\n graphqlSources = signal.sources;\n } else {\n fileCount++;\n documents.push(...signal.documents);\n cachedDocumentCount += signal.documents.filter((document) => document.isCached).length;\n warnings += signal.warnings.length;\n if (signal.warnings.length) {\n let buffer = logger.warningFile(signal.filePath);\n for (const warning of signal.warnings) {\n buffer += logger.warningMessage(warning);\n logger.warningGithub(warning);\n }\n yield buffer + '\\n';\n }\n }\n\n if (tty.isInteractive) yield logger.runningTurbo(fileCount, totalFileCount);\n }\n } catch (error) {\n throw logger.externalError('Could not build cache', error);\n }\n\n if ('schema' in pluginConfig) {\n if (warnings && opts.failOnWarn) {\n if (!deferWarnings) throw logger.warningSummary(warnings);\n return { warnings, failed: true };\n }\n\n try {\n const existing = await readOutput(destination!);\n const contents = createCacheContents(documents, graphqlSources, destination!, existing);\n await writeOutput(destination!, contents);\n } catch (error) {\n throw logger.externalError('Something went wrong while writing the type cache file', error);\n }\n\n yield logger.infoSummary(warnings, documents.length, cachedDocumentCount);\n } else {\n if (opts.output) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple schemas are configured.\\n' +\n logger.hint(\n `You can only output all schemas to their ${logger.code(\n '\"tadaTurboLocation\"'\n )} options\\n` + `when multiple ${logger.code('schemas')} are set up.`\n )\n );\n }\n\n const documentCount: Record<string, number> = {};\n const cachedCount: Record<string, number> = {};\n for (const schemaConfig of pluginConfig.schemas) {\n const { name, tadaTurboLocation } = schemaConfig;\n if (!tadaTurboLocation) {\n throw logger.errorMessage(\n `No output path was specified to write the '${name}' type cache to.\\n` +\n logger.hint(\n `You have to set ${logger.code('\"tadaTurboLocation\"')} in each schema configuration.`\n )\n );\n }\n\n try {\n documentCount[name] = 0;\n cachedCount[name] = 0;\n const cache: TurboDocument[] = [];\n for (const item of documents) {\n if (item.schemaName === name) {\n cache.push(item);\n documentCount[name]++;\n if (item.isCached) cachedCount[name]++;\n }\n }\n const destination = path.resolve(projectPath, tadaTurboLocation);\n const existing = await readOutput(destination);\n const contents = createCacheContents(cache, graphqlSources, destination, existing);\n await writeOutput(destination, contents);\n } catch (error) {\n throw logger.externalError(\n `Something went wrong while writing the '${name}' schema's type cache file.`,\n error\n );\n }\n }\n\n if (warnings && opts.failOnWarn) {\n if (!deferWarnings) throw logger.warningSummary(warnings);\n return { warnings, failed: true };\n } else {\n yield logger.infoSummary(warnings, documentCount, cachedCount);\n }\n }\n\n return { warnings, failed: false };\n}\n\nfunction createCacheContents(\n cache: TurboDocument[],\n graphqlSources: GraphQLSourceFile[],\n turboDestination: WriteTarget,\n existing?: string\n): string {\n const preamble = (existing && extractIntrospectionHeader(existing)) || PREAMBLE_IGNORE;\n const documentsByKey = new Map<string, TurboDocument>();\n for (const document of cache) documentsByKey.set(document.argumentKey, document);\n\n let output = '';\n for (const document of documentsByKey.values()) {\n if (output) output += '\\n';\n if (document.documentHash) output += ` /** @gql.tada/hash ${document.documentHash} */\\n`;\n output += ` ${document.argumentKey}:\\n ${document.documentType};`;\n }\n\n let imports = \"import type { TadaDocumentNode, $tada } from 'gql.tada';\\n\";\n\n const isFilePath =\n typeof turboDestination === 'string' ||\n (turboDestination &&\n typeof turboDestination === 'object' &&\n 'toString' in turboDestination &&\n !('writable' in turboDestination));\n\n const addedImports = new Set<string>();\n for (const source of graphqlSources) {\n for (const importInfo of source.imports) {\n if (isFilePath) {\n const turboPath = turboDestination.toString();\n const sourceDir = path.dirname(source.absolutePath);\n const absoluteImportPath = path.resolve(sourceDir, importInfo.specifier);\n const absoluteTurboPath = path.resolve(turboPath);\n\n if (absoluteImportPath === absoluteTurboPath || addedImports.has(importInfo.specifier))\n continue;\n\n addedImports.add(importInfo.specifier);\n }\n\n imports += importInfo.importClause + '\\n';\n }\n }\n\n return (\n preamble +\n imports +\n '\\n' +\n \"declare module 'gql.tada' {\\n\" +\n ' interface setupCache {\\n' +\n output +\n '\\n }' +\n '\\n}\\n'\n );\n}\n","import { Command, Option } from 'clipanion';\n\nimport type { TurboOptions } from './runner';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class TurboCommand extends Command {\n static paths = [['generate', 'turbo'], ['turbo']];\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` read for configuration.',\n });\n\n failOnWarn = Option.Boolean('--fail-on-warn,-w', false, {\n description: 'Triggers an error and a non-zero exit code if any warnings have been reported',\n });\n\n output = Option.String('--output,-o', {\n description:\n 'Specifies where to output the file to.\\tDefault: The `tadaTurboLocation` configuration option',\n });\n\n async execute() {\n // TODO: Add verbose/log/list/debug/trace option that outputs discovered documents (by name) per file\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n failOnWarn: this.failOnWarn,\n output: this.output,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Generates a cache typings file for all GraphQL document types ahead of time.\n *\n * @remarks\n * The `generateTurbo()` function generates a cache for all GraphQL document types ahead of time.\n * This cache speeds up type evaluation and is especially useful when it's checked into the\n * repository after making changes to GraphQL documents, which speeds up all further type\n * checks and evaluation.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#generateturbo}\n */\nexport async function generateTurbo(opts: TurboOptions) {\n const tty = initTTY({ disableTTY: true });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","import * as path from 'node:path';\n\nexport interface ModuleReach {\n /** The module itself plus every module that transitively depends on it. */\n modules: string[];\n /** Distinct areas covered by {@link modules}. */\n areas: string[];\n /** Entry points among {@link modules}. */\n entryPoints: string[];\n}\n\n/**\n * The project's static module dependency graph (file → its project imports).\n *\n * A self-contained, reusable structure: all reachability/area analytics live\n * here and are memoised internally, so the {@link ScanContext} exposes it as a\n * single primitive and rules can do graph analysis without the context growing.\n */\nexport class ModuleGraph {\n private readonly _edges: Map<string, readonly string[]>;\n private readonly _cwd: string;\n private _reverse: Map<string, Set<string>> | undefined;\n private _entryPoints: Set<string> | undefined;\n private _distance: Map<string, number> | undefined;\n private readonly _dependents = new Map<string, Set<string>>();\n\n constructor(edges: Map<string, string[]>, cwd: string = process.cwd()) {\n this._edges = edges;\n this._cwd = cwd;\n }\n\n /** All import edges (module → the project modules it imports). */\n importMap(): ReadonlyMap<string, readonly string[]> {\n return this._edges;\n }\n\n /** The \"area\" a module belongs to: its directory, relative to the cwd. */\n areaOf(modulePath: string): string {\n const rel = path.relative(this._cwd, modulePath);\n const dir = path.dirname(!rel.startsWith('..') ? rel : modulePath);\n return dir === '.' ? '(root)' : dir;\n }\n\n /** Modules that nothing else imports — the roots of the graph. */\n entryPoints(): Set<string> {\n if (this._entryPoints) return this._entryPoints;\n const nodes = new Set<string>();\n const targets = new Set<string>();\n for (const [from, tos] of this._edges) {\n nodes.add(from);\n for (const to of tos) {\n nodes.add(to);\n targets.add(to);\n }\n }\n return (this._entryPoints = new Set([...nodes].filter((node) => !targets.has(node))));\n }\n\n /** Modules that transitively import the given module (its reverse closure). */\n dependents(modulePath: string): Set<string> {\n const cached = this._dependents.get(modulePath);\n if (cached) return cached;\n\n const reverse = this._reverseGraph();\n const result = new Set<string>();\n const stack = [...(reverse.get(modulePath) || [])];\n let node: string | undefined;\n while ((node = stack.pop())) {\n if (result.has(node)) continue;\n result.add(node);\n stack.push(...(reverse.get(node) || []));\n }\n\n this._dependents.set(modulePath, result);\n return result;\n }\n\n /** Shortest distance from any entry point to the module (entry points are 0). */\n distanceFromEntry(modulePath: string): number | undefined {\n if (!this._distance) {\n const distance = new Map<string, number>();\n let frontier = [...this.entryPoints()];\n let depth = 0;\n while (frontier.length) {\n const next: string[] = [];\n for (const node of frontier) {\n if (distance.has(node)) continue;\n distance.set(node, depth);\n for (const to of this._edges.get(node) || []) {\n if (!distance.has(to)) next.push(to);\n }\n }\n frontier = next;\n depth++;\n }\n this._distance = distance;\n }\n return this._distance.get(modulePath);\n }\n\n /** The blast radius of a module: itself plus everything that depends on it. */\n reach(modulePath: string): ModuleReach {\n const entryPoints = this.entryPoints();\n const modules = new Set<string>([modulePath, ...this.dependents(modulePath)]);\n const areas = new Set<string>();\n const reachedEntries = new Set<string>();\n for (const module of modules) {\n areas.add(this.areaOf(module));\n if (entryPoints.has(module)) reachedEntries.add(module);\n }\n return { modules: [...modules], areas: [...areas].sort(), entryPoints: [...reachedEntries] };\n }\n\n private _reverseGraph(): Map<string, Set<string>> {\n if (this._reverse) return this._reverse;\n const reverse = new Map<string, Set<string>>();\n for (const [from, tos] of this._edges) {\n for (const to of tos) {\n let importers = reverse.get(to);\n if (!importers) reverse.set(to, (importers = new Set()));\n importers.add(from);\n }\n }\n return (this._reverse = reverse);\n }\n}\n","import type { SchemaName } from './types';\n\nexport interface FragmentGraphDefinition {\n id: string;\n kind: 'operation' | 'fragment';\n schemaName: SchemaName;\n /** The fragment's name (present for fragment definitions). */\n name?: string;\n /** Names of fragments spread directly by this definition. */\n fragmentSpreads: readonly string[];\n}\n\nconst key = (schemaName: SchemaName, name: string): string => `${schemaName ?? ''}\\0${name}`;\n\n/**\n * The fragment spread graph: resolution by name and reachability between\n * definitions.\n *\n * A self-contained, reusable structure (the GraphQL-side analogue of\n * {@link ModuleGraph}). Reachability is memoised internally, so the\n * {@link ScanContext} exposes it as a single primitive and rules can do\n * fragment-graph analysis without the context growing per rule.\n */\nexport class FragmentGraph {\n private readonly _byId = new Map<string, FragmentGraphDefinition>();\n private readonly _idByName = new Map<string, string>();\n private readonly _operationIds: string[] = [];\n private readonly _reachable = new Map<string, Set<string>>();\n private _operationsReaching: Map<string, Set<string>> | undefined;\n\n constructor(definitions: readonly FragmentGraphDefinition[]) {\n for (const definition of definitions) {\n this._byId.set(definition.id, definition);\n if (definition.kind === 'operation') {\n this._operationIds.push(definition.id);\n } else if (definition.name != null) {\n this._idByName.set(key(definition.schemaName, definition.name), definition.id);\n }\n }\n }\n\n /** Resolves a fragment name to its id within a schema. */\n resolve(schemaName: SchemaName, name: string): string | undefined {\n return this._idByName.get(key(schemaName, name));\n }\n\n /** Ids of fragments reachable from a definition via (nested) spreads. */\n reachableFragments(definitionId: string): Set<string> {\n const cached = this._reachable.get(definitionId);\n if (cached) return cached;\n\n const result = new Set<string>();\n const start = this._byId.get(definitionId);\n if (start) {\n const stack = [...start.fragmentSpreads];\n let name: string | undefined;\n while ((name = stack.pop())) {\n const id = this.resolve(start.schemaName, name);\n if (!id || result.has(id)) continue;\n result.add(id);\n const fragment = this._byId.get(id);\n if (fragment) stack.push(...fragment.fragmentSpreads);\n }\n }\n\n this._reachable.set(definitionId, result);\n return result;\n }\n\n /** Operation ids that reach a fragment directly or transitively. */\n operationsReaching(fragmentId: string): Set<string> {\n if (!this._operationsReaching) {\n const map = new Map<string, Set<string>>();\n for (const operationId of this._operationIds) {\n for (const reachableId of this.reachableFragments(operationId)) {\n let set = map.get(reachableId);\n if (!set) map.set(reachableId, (set = new Set()));\n set.add(operationId);\n }\n }\n this._operationsReaching = map;\n }\n return this._operationsReaching.get(fragmentId) || new Set();\n }\n}\n","import * as crypto from 'node:crypto';\nimport * as path from 'node:path';\nimport { parse, print, visit, Kind } from 'graphql';\nimport type {\n GraphQLSchema,\n GraphQLCompositeType,\n GraphQLField,\n GraphQLOutputType,\n GraphQLInputType,\n GraphQLEnumValue,\n TypeInfo,\n ASTNode,\n ASTVisitor,\n DefinitionNode,\n OperationDefinitionNode,\n FragmentDefinitionNode,\n} from 'graphql';\n\nimport type {\n SchemaName,\n RawScanDocument,\n ScanWarning,\n ModuleInfo,\n OperationInfo,\n FragmentInfo,\n DefinitionRecord,\n} from './types';\nimport { ModuleGraph } from './module-graph';\nimport { FragmentGraph } from './fragment-graph';\nimport type { FragmentGraphDefinition } from './fragment-graph';\n\nconst CWD = process.cwd();\n\nexport interface ScanContextParams {\n documents: RawScanDocument[];\n schemas: Map<SchemaName, GraphQLSchema>;\n imports: Map<string, string[]>;\n warnings: ScanWarning[];\n}\n\nconst hashOf = (input: string): string =>\n crypto.createHash('sha256').update(input).digest('hex').slice(0, 16);\n\n/** Collects the names of fragments spread anywhere within a definition. */\nfunction collectFragmentSpreads(node: DefinitionNode): string[] {\n const names = new Set<string>();\n visit(node, {\n FragmentSpread(spread) {\n names.add(spread.name.value);\n },\n });\n return [...names];\n}\n\n/**\n * Shared state passed to every scan rule, modelled on graphql-js's\n * `ValidationContext`.\n *\n * It exposes only *primitives*: the loaded schemas, the corpus of discovered\n * definitions (identities + AST nodes), fragment resolution, structural\n * reachability helpers, and TypeInfo-backed accessors for the current\n * traversal position. It never holds derived insight data — rules build that\n * themselves.\n */\nexport class ScanContext {\n private readonly _schemas: Map<SchemaName, GraphQLSchema>;\n private readonly _warnings: ScanWarning[];\n private readonly _operations: OperationInfo[] = [];\n private readonly _fragments: FragmentInfo[] = [];\n private readonly _definitions: DefinitionRecord[] = [];\n private readonly _recordByNode = new Map<ASTNode, DefinitionRecord>();\n private readonly _recordById = new Map<string, DefinitionRecord>();\n private readonly _modules: ModuleInfo[];\n\n private _typeInfo: TypeInfo | null = null;\n private _currentDefinition: DefinitionRecord | null = null;\n\n // Static module dependency graph (every scanned file → its project imports).\n private readonly _importGraph: Map<string, string[]>;\n private _moduleGraph: ModuleGraph | undefined;\n private _fragmentGraph: FragmentGraph | undefined;\n\n constructor(params: ScanContextParams) {\n this._schemas = params.schemas;\n this._warnings = [...params.warnings];\n this._importGraph = params.imports;\n this._buildCorpus(params.documents);\n this._modules = this._buildModules(params.imports);\n }\n\n /* -- Corpus accessors (base facts) -- */\n\n get operations(): readonly OperationInfo[] {\n return this._operations;\n }\n\n get fragments(): readonly FragmentInfo[] {\n return this._fragments;\n }\n\n get modules(): readonly ModuleInfo[] {\n return this._modules;\n }\n\n get warnings(): readonly ScanWarning[] {\n return this._warnings;\n }\n\n getSchemas(): Map<SchemaName, GraphQLSchema> {\n return this._schemas;\n }\n\n /** Definition AST nodes for a single schema, for per-schema traversal. */\n definitionNodesForSchema(schemaName: SchemaName): DefinitionNode[] {\n const nodes: DefinitionNode[] = [];\n for (const record of this._definitions) {\n if (record.schemaName === schemaName) nodes.push(record.node);\n }\n return nodes;\n }\n\n /* -- Traversal primitives (set by the driver) -- */\n\n /** @internal Used by the driver to bind the active schema's TypeInfo. */\n setTypeInfo(typeInfo: TypeInfo): void {\n this._typeInfo = typeInfo;\n }\n\n /** A visitor the driver runs first so rules can read the current definition. */\n trackingVisitor(): ASTVisitor {\n return {\n OperationDefinition: {\n enter: (node) => void (this._currentDefinition = this._recordByNode.get(node) || null),\n leave: () => void (this._currentDefinition = null),\n },\n FragmentDefinition: {\n enter: (node) => void (this._currentDefinition = this._recordByNode.get(node) || null),\n leave: () => void (this._currentDefinition = null),\n },\n };\n }\n\n getCurrentDefinition(): DefinitionRecord | null {\n return this._currentDefinition;\n }\n\n getParentType(): GraphQLCompositeType | null | undefined {\n return this._typeInfo?.getParentType();\n }\n\n /** The current output type at this traversal position — the third TypeInfo\n * accessor alongside {@link getParentType} and {@link getFieldDef}. Unused\n * today, but kept as a generic primitive for rules that inspect return types\n * (e.g. list/non-null wrapping) without the context having to grow. */\n getType(): GraphQLOutputType | null | undefined {\n return this._typeInfo?.getType();\n }\n\n getFieldDef(): GraphQLField<unknown, unknown> | null | undefined {\n return this._typeInfo?.getFieldDef();\n }\n\n /** The input type expected at this position (argument / input-field / list value). */\n getInputType(): GraphQLInputType | null | undefined {\n return this._typeInfo?.getInputType();\n }\n\n /** The enclosing input-object type when inside an input object literal. */\n getParentInputType(): GraphQLInputType | null | undefined {\n return this._typeInfo?.getParentInputType();\n }\n\n /** The enum value definition at the current position, if any. */\n getEnumValue(): GraphQLEnumValue | null | undefined {\n return this._typeInfo?.getEnumValue();\n }\n\n /* -- Generic primitives for graph-level rules -- */\n\n /** The project's static module dependency graph, as a reusable structure.\n * All reachability/area analysis lives on it, so graph rules need no bespoke\n * context methods. */\n getModuleGraph(): ModuleGraph {\n return (this._moduleGraph ??= new ModuleGraph(this._importGraph, CWD));\n }\n\n /** The fragment spread graph (resolution + reachability), as a reusable\n * structure. Built from the corpus, so fragment-graph rules need no bespoke\n * context methods. */\n getFragmentGraph(): FragmentGraph {\n if (!this._fragmentGraph) {\n const definitions: FragmentGraphDefinition[] = [];\n for (const op of this._operations) {\n definitions.push({\n id: op.id,\n kind: 'operation',\n schemaName: op.schemaName,\n fragmentSpreads: op.fragmentSpreads,\n });\n }\n for (const fragment of this._fragments) {\n definitions.push({\n id: fragment.id,\n kind: 'fragment',\n schemaName: fragment.schemaName,\n name: fragment.name,\n fragmentSpreads: fragment.fragmentSpreads,\n });\n }\n this._fragmentGraph = new FragmentGraph(definitions);\n }\n return this._fragmentGraph;\n }\n\n /* -- Construction -- */\n\n private _addWarning(message: string, doc: RawScanDocument): void {\n this._warnings.push({ message, file: doc.filePath, line: doc.line, col: doc.col });\n }\n\n private _uniqueId(base: string): string {\n if (!this._recordById.has(base)) return base;\n let n = 2;\n while (this._recordById.has(`${base}#${n}`)) n++;\n return `${base}#${n}`;\n }\n\n private _register(record: DefinitionRecord): void {\n this._definitions.push(record);\n this._recordByNode.set(record.node, record);\n this._recordById.set(record.id, record);\n // Keep the AST node and discriminant internal; expose only clean identities.\n if (record.defKind === 'operation') {\n const { node: _node, defKind: _defKind, ...info } = record;\n this._operations.push(info);\n } else {\n const { node: _node, defKind: _defKind, ...info } = record;\n this._fragments.push(info);\n }\n }\n\n private _buildCorpus(documents: RawScanDocument[]): void {\n let anonCount = 0;\n for (const doc of documents) {\n if (!this._schemas.has(doc.schemaName)) {\n this._addWarning(\n `No schema was loaded for ${doc.schemaName ? `'${doc.schemaName}'` : 'the default schema'}.`,\n doc\n );\n continue;\n }\n\n let definitions: readonly DefinitionNode[];\n try {\n definitions = parse(doc.document, { noLocation: true }).definitions;\n } catch (error) {\n this._addWarning(\n `The document could not be parsed. Run \\`check\\` to see validation errors.\\n` +\n `${error instanceof Error ? error.message : error}`,\n doc\n );\n continue;\n }\n\n const loc = { file: doc.filePath, line: doc.line, col: doc.col };\n for (const definition of definitions) {\n if (definition.kind === Kind.OPERATION_DEFINITION) {\n const op = definition as OperationDefinitionNode;\n const name = op.name ? op.name.value : null;\n const id = this._uniqueId(\n `${doc.schemaName ?? ''}:operation:${name ?? `anonymous-${++anonCount}`}`\n );\n this._register({\n defKind: 'operation',\n node: op,\n id,\n name,\n kind: op.operation,\n schemaName: doc.schemaName,\n module: doc.filePath,\n loc,\n variables: (op.variableDefinitions || []).map((v) => ({\n name: v.variable.name.value,\n type: print(v.type),\n defaultValue: v.defaultValue ? print(v.defaultValue) : undefined,\n })),\n fragmentSpreads: collectFragmentSpreads(op),\n hash: hashOf(print(op)),\n });\n } else if (definition.kind === Kind.FRAGMENT_DEFINITION) {\n const fragment = definition as FragmentDefinitionNode;\n const id = this._uniqueId(`${doc.schemaName ?? ''}:fragment:${fragment.name.value}`);\n this._register({\n defKind: 'fragment',\n node: fragment,\n id,\n name: fragment.name.value,\n typeCondition: fragment.typeCondition.name.value,\n schemaName: doc.schemaName,\n module: doc.filePath,\n loc,\n fragmentSpreads: collectFragmentSpreads(fragment),\n hash: hashOf(print(fragment)),\n });\n }\n }\n }\n }\n\n private _buildModules(imports: Map<string, string[]>): ModuleInfo[] {\n const byPath = new Map<string, ModuleInfo>();\n const ensure = (modulePath: string): ModuleInfo => {\n let info = byPath.get(modulePath);\n if (!info) {\n info = {\n path: modulePath,\n relativePath: path.relative(CWD, modulePath) || modulePath,\n operations: [],\n fragments: [],\n imports: [],\n };\n byPath.set(modulePath, info);\n }\n return info;\n };\n\n for (const op of this._operations) ensure(op.module).operations.push(op.id);\n for (const fragment of this._fragments) ensure(fragment.module).fragments.push(fragment.id);\n\n for (const info of byPath.values()) {\n const resolved = imports.get(info.path);\n if (resolved) {\n for (const target of resolved) {\n if (target !== info.path && byPath.has(target)) info.imports.push(target);\n }\n }\n }\n\n return [...byPath.values()].sort((a, b) => a.relativePath.localeCompare(b.relativePath));\n }\n}\n","import type { ScanRule, RuleDatapoint } from '../types';\n\nexport interface FieldUsageData {\n typeName: string;\n fieldName: string;\n fieldType: string;\n deprecated: boolean;\n deprecationReason?: string | undefined;\n count: number;\n directUsages: { defId: string; module: string }[];\n /** Operation ids that reach this field directly or transitively. */\n operations: string[];\n /** Blast radius: how much of the codebase transitively depends on this field. */\n reach: { modules: number; areas: string[]; entryPoints: number };\n}\n\ninterface Accumulated {\n typeName: string;\n fieldName: string;\n fieldType: string;\n deprecationReason?: string;\n directUsages: { defId: string; module: string }[];\n}\n\n/** Indexes every field that is actually selected: which operations/fragments\n * select each schema coordinate, the operations that reach it, and its blast\n * radius. Fields the schema declares but no document selects are absent (derive\n * them from the schema if needed; the overview carries aggregate coverage). */\nexport const fieldUsage: ScanRule<FieldUsageData> = {\n name: 'field-usage',\n description: 'Used fields, keyed by schema coordinate, with their reach.',\n create(context) {\n const byCoordinate = new Map<string, Accumulated>();\n let seen = new Set<string>();\n const resetSeen = () => void (seen = new Set());\n\n return {\n visitor: {\n OperationDefinition: { enter: resetSeen },\n FragmentDefinition: { enter: resetSeen },\n Field: {\n enter() {\n const parentType = context.getParentType();\n const fieldDef = context.getFieldDef();\n const definition = context.getCurrentDefinition();\n if (!parentType || !fieldDef || !definition) return;\n // Skip reserved introspection meta-fields (__typename, __schema, __type).\n if (fieldDef.name.startsWith('__')) return;\n\n const coordinate = `${parentType.name}.${fieldDef.name}`;\n if (seen.has(coordinate)) return;\n seen.add(coordinate);\n\n let entry = byCoordinate.get(coordinate);\n if (!entry) {\n entry = {\n typeName: parentType.name,\n fieldName: fieldDef.name,\n fieldType: String(fieldDef.type),\n deprecationReason: fieldDef.deprecationReason ?? undefined,\n directUsages: [],\n };\n byCoordinate.set(coordinate, entry);\n }\n entry.directUsages.push({ defId: definition.id, module: definition.module });\n },\n },\n },\n\n collect() {\n const operationIds = new Set(context.operations.map((op) => op.id));\n const moduleById = new Map(context.operations.map((op) => [op.id, op.module] as const));\n const graph = context.getModuleGraph();\n const fragments = context.getFragmentGraph();\n const hasEntryPoints = graph.entryPoints().size > 0;\n\n const datapoints: RuleDatapoint<FieldUsageData>[] = [];\n for (const [coordinate, entry] of byCoordinate) {\n const operations = new Set<string>();\n for (const usage of entry.directUsages) {\n if (operationIds.has(usage.defId)) operations.add(usage.defId);\n else for (const id of fragments.operationsReaching(usage.defId)) operations.add(id);\n }\n\n // Blast radius: every module that selects the field, plus the modules\n // of the operations that reach it, expanded by who depends on them.\n const sourceModules = new Set<string>(entry.directUsages.map((u) => u.module));\n for (const id of operations) {\n const module = moduleById.get(id);\n if (module) sourceModules.add(module);\n }\n const reachModules = new Set<string>();\n const reachAreas = new Set<string>();\n const reachEntries = new Set<string>();\n for (const module of sourceModules) {\n const reach = graph.reach(module);\n for (const m of reach.modules) reachModules.add(m);\n for (const a of reach.areas) reachAreas.add(a);\n for (const e of reach.entryPoints) reachEntries.add(e);\n }\n\n datapoints.push({\n ref: { kind: 'field', coordinate },\n message: `${coordinate} selected ${entry.directUsages.length} time(s)`,\n weight: hasEntryPoints ? reachEntries.size : reachModules.size,\n data: {\n typeName: entry.typeName,\n fieldName: entry.fieldName,\n fieldType: entry.fieldType,\n deprecated: entry.deprecationReason != null,\n deprecationReason: entry.deprecationReason,\n count: entry.directUsages.length,\n directUsages: entry.directUsages,\n operations: [...operations],\n reach: {\n modules: reachModules.size,\n areas: [...reachAreas].sort(),\n entryPoints: reachEntries.size,\n },\n },\n });\n }\n\n // Rank by selection count, then reach, then coordinate for stable ties —\n // so the terminal's top-N shows the most-used fields first.\n const coordinateOf = (d: FieldUsageData) => `${d.typeName}.${d.fieldName}`;\n return datapoints.sort(\n (a, b) =>\n b.data.count - a.data.count ||\n (b.weight ?? 0) - (a.weight ?? 0) ||\n coordinateOf(a.data).localeCompare(coordinateOf(b.data))\n );\n },\n };\n },\n};\n","import type { ScanRule } from '../types';\n\nimport { fieldUsage } from './field-usage';\nimport { inputUsage } from './input-usage';\nimport { deprecatedUsage } from './deprecated-usage';\nimport { orphanFragments } from './orphan-fragments';\nimport { crossFeatureFragments } from './cross-feature-fragments';\nimport { operationComplexity } from './operation-complexity';\nimport { fetchDepth } from './fetch-depth';\nimport { directiveUsage } from './directive-usage';\n\nexport type { FieldUsageData } from './field-usage';\n\n/** The rules run out of the box. Each is a `(context) => { visitor, collect }`\n * factory that owns its state — adding an insight means writing one rule file\n * and registering it here. */\nexport const DEFAULT_RULES: ScanRule[] = [\n // The per-field usage index (reverse lookup + blast radius).\n fieldUsage,\n // Input-side usage: enum values and input-object fields.\n inputUsage,\n // Schema evolution & safety\n deprecatedUsage,\n // Code navigation & refactoring\n orphanFragments,\n crossFeatureFragments,\n // Performance & DX\n operationComplexity,\n // Code-structure (dependency graph)\n fetchDepth,\n // Conventions\n directiveUsage,\n];\n","import { getNamedType } from 'graphql';\n\nimport type { ScanRule, RuleDatapoint } from '../types';\n\nexport interface InputUsageData {\n kind: 'enum-value' | 'input-field';\n count: number;\n}\n\n/** Usage counts for the input side of the schema: which enum values are passed\n * and which input-object fields are set, keyed by coordinate (`Enum.VALUE` /\n * `Input.field`). Answers \"which enum values / input fields do we actually\n * use\", which neither field usage nor coverage captures. */\nexport const inputUsage: ScanRule<InputUsageData> = {\n name: 'input-usage',\n description: 'Usage counts for enum values and input-object fields.',\n create(context) {\n const counts = new Map<string, { kind: InputUsageData['kind']; count: number }>();\n const bump = (coordinate: string, kind: InputUsageData['kind']) => {\n const entry = counts.get(coordinate);\n if (entry) entry.count++;\n else counts.set(coordinate, { kind, count: 1 });\n };\n\n return {\n visitor: {\n EnumValue: {\n enter(node) {\n const inputType = context.getInputType();\n if (inputType) bump(`${getNamedType(inputType).name}.${node.value}`, 'enum-value');\n },\n },\n ObjectField: {\n enter(node) {\n const parentInput = context.getParentInputType();\n if (parentInput)\n bump(`${getNamedType(parentInput).name}.${node.name.value}`, 'input-field');\n },\n },\n },\n\n collect() {\n const datapoints: RuleDatapoint<InputUsageData>[] = [...counts.entries()]\n .sort((a, b) => b[1].count - a[1].count || a[0].localeCompare(b[0]))\n .map(([coordinate, { kind, count }]) => ({\n ref: { kind: 'field', coordinate },\n message: `${coordinate} (${kind}) used ${count} time(s)`,\n weight: count,\n data: { kind, count },\n }));\n return datapoints;\n },\n };\n },\n};\n","import type { ScanRule } from '../types';\n\nexport interface DeprecatedUsageData {\n reason?: string | undefined;\n count: number;\n operations: string[];\n}\n\ninterface Accumulated {\n reason?: string | undefined;\n defIds: Set<string>;\n}\n\n/** Deprecated schema fields that are still selected, ranked by how many\n * operations reach them — the migration's remaining blast radius. */\nexport const deprecatedUsage: ScanRule<DeprecatedUsageData> = {\n name: 'deprecated-usage',\n description: 'Deprecated schema fields that are still in use.',\n create(context) {\n const byCoordinate = new Map<string, Accumulated>();\n\n return {\n visitor: {\n Field: {\n enter() {\n const parentType = context.getParentType();\n const fieldDef = context.getFieldDef();\n const definition = context.getCurrentDefinition();\n if (!parentType || !fieldDef || !definition) return;\n if (fieldDef.deprecationReason == null) return;\n\n const coordinate = `${parentType.name}.${fieldDef.name}`;\n let entry = byCoordinate.get(coordinate);\n if (!entry) {\n byCoordinate.set(\n coordinate,\n (entry = { reason: fieldDef.deprecationReason ?? undefined, defIds: new Set() })\n );\n }\n entry.defIds.add(definition.id);\n },\n },\n },\n\n collect() {\n const operationIds = new Set(context.operations.map((op) => op.id));\n const fragments = context.getFragmentGraph();\n return [...byCoordinate.entries()]\n .map(([coordinate, entry]) => {\n const operations = new Set<string>();\n for (const defId of entry.defIds) {\n if (operationIds.has(defId)) operations.add(defId);\n else for (const id of fragments.operationsReaching(defId)) operations.add(id);\n }\n return { coordinate, reason: entry.reason, operations: [...operations] };\n })\n .sort((a, b) => b.operations.length - a.operations.length)\n .map(({ coordinate, reason, operations }) => ({\n ref: { kind: 'field', coordinate },\n message: `${coordinate} is deprecated but used by ${operations.length} operation(s)`,\n weight: operations.length,\n data: { reason, count: operations.length, operations },\n }));\n },\n };\n },\n};\n","import type { ScanRule } from '../types';\n\nexport interface OrphanFragmentData {\n typeCondition: string;\n module: string;\n}\n\n/** Fragments that are defined but never spread by any operation or fragment. */\nexport const orphanFragments: ScanRule<OrphanFragmentData> = {\n name: 'orphan-fragments',\n description: 'Fragments that are defined but never used.',\n create(context) {\n const spreadIds = new Set<string>();\n const fragments = context.getFragmentGraph();\n\n return {\n visitor: {\n FragmentSpread: {\n enter(node) {\n const definition = context.getCurrentDefinition();\n if (!definition) return;\n const id = fragments.resolve(definition.schemaName, node.name.value);\n if (id) spreadIds.add(id);\n },\n },\n },\n\n collect() {\n return context.fragments\n .filter((fragment) => !spreadIds.has(fragment.id))\n .map((fragment) => ({\n ref: { kind: 'fragment', id: fragment.id },\n message: `Fragment '${fragment.name}' is never spread`,\n data: { typeCondition: fragment.typeCondition, module: fragment.module },\n }));\n },\n };\n },\n};\n","import type { ScanRule, RuleDatapoint } from '../types';\n\nexport interface CrossFeatureData {\n definingArea: string;\n consumerAreas: string[];\n spreadCount: number;\n}\n\n/** Fragments consumed across area boundaries — a quantified signal of coupling\n * between features. The weight is the number of distinct consuming areas. */\nexport const crossFeatureFragments: ScanRule<CrossFeatureData> = {\n name: 'cross-feature-fragments',\n description: 'Fragments spread across multiple areas of the codebase.',\n create(context) {\n // fragment id -> areas of the definitions that spread it\n const consumerAreas = new Map<string, Set<string>>();\n const spreadCount = new Map<string, number>();\n\n const graph = context.getModuleGraph();\n const fragments = context.getFragmentGraph();\n\n return {\n visitor: {\n FragmentSpread: {\n enter(node) {\n const definition = context.getCurrentDefinition();\n if (!definition) return;\n const id = fragments.resolve(definition.schemaName, node.name.value);\n if (!id) return;\n let areas = consumerAreas.get(id);\n if (!areas) consumerAreas.set(id, (areas = new Set()));\n areas.add(graph.areaOf(definition.module));\n spreadCount.set(id, (spreadCount.get(id) || 0) + 1);\n },\n },\n },\n\n collect() {\n const byId = new Map(context.fragments.map((fragment) => [fragment.id, fragment]));\n const datapoints: RuleDatapoint<CrossFeatureData>[] = [];\n for (const [id, areas] of consumerAreas) {\n const fragment = byId.get(id);\n if (!fragment) continue;\n const definingArea = graph.areaOf(fragment.module);\n // Areas other than where the fragment itself lives.\n const externalAreas = [...areas].filter((area) => area !== definingArea).sort();\n if (!externalAreas.length) continue;\n\n datapoints.push({\n ref: { kind: 'fragment' as const, id },\n message: `Fragment '${fragment.name}' (${definingArea}) is consumed by ${externalAreas.length} other area(s)`,\n weight: externalAreas.length,\n data: {\n definingArea,\n consumerAreas: [...areas].sort(),\n spreadCount: spreadCount.get(id) || 0,\n },\n });\n }\n return datapoints.sort((a, b) => (b.weight || 0) - (a.weight || 0));\n },\n };\n },\n};\n","import { isListType, getNullableType } from 'graphql';\n\nimport type { ScanRule, RuleDatapoint } from '../types';\n\n/** Extra weight per list field — list selections drive response size / N+1 risk. */\nconst LIST_WEIGHT = 3;\n\nexport interface ComplexityData {\n /** Selection depth, expanded through fragment spreads. */\n depth: number;\n /** Number of distinct fields selected, expanded through fragment spreads. */\n fieldCount: number;\n /** How many of those distinct fields return a list. */\n listFields: number;\n /** The distinct schema coordinates selected (the operation's footprint). */\n fields: string[];\n /** Combined cost score. */\n score: number;\n}\n\n/** Per-definition metrics gathered during traversal (own selections only). */\ninterface DefMetrics {\n schemaName: string | null;\n ownDepth: number;\n /** Distinct coordinates selected directly in this definition. */\n fields: Set<string>;\n /** Subset of {@link fields} whose field returns a list. */\n listFields: Set<string>;\n /** Fragment spreads with the selection-set depth they occur at. */\n spreads: { name: string; depth: number }[];\n}\n\n/** Operations ranked by cost, expanded through fragment spreads (an operation\n * that delegates to a big fragment is correctly counted as large). Reports the\n * operation's full field footprint, its transitive depth, and how many of its\n * fields return lists (weighted more heavily as a proxy for response size /\n * N+1 risk). */\nexport const operationComplexity: ScanRule<ComplexityData> = {\n name: 'operation-complexity',\n description: 'Operations ranked by transitive footprint, depth, and list fan-out.',\n create(context) {\n const byDef = new Map<string, DefMetrics>();\n let current: DefMetrics | null = null;\n let depth = 0;\n\n const startDefinition = () => {\n const definition = context.getCurrentDefinition();\n if (!definition) {\n current = null;\n return;\n }\n current = {\n schemaName: definition.schemaName,\n ownDepth: 0,\n fields: new Set(),\n listFields: new Set(),\n spreads: [],\n };\n byDef.set(definition.id, current);\n depth = 0;\n };\n\n return {\n visitor: {\n OperationDefinition: { enter: startDefinition, leave: () => void (current = null) },\n FragmentDefinition: { enter: startDefinition, leave: () => void (current = null) },\n SelectionSet: {\n enter() {\n if (current && ++depth > current.ownDepth) current.ownDepth = depth;\n },\n leave() {\n if (current) depth--;\n },\n },\n Field: {\n enter() {\n const parentType = context.getParentType();\n const fieldDef = context.getFieldDef();\n if (!current || !parentType || !fieldDef || fieldDef.name.startsWith('__')) return;\n const coordinate = `${parentType.name}.${fieldDef.name}`;\n current.fields.add(coordinate);\n if (isListType(getNullableType(fieldDef.type))) current.listFields.add(coordinate);\n },\n },\n FragmentSpread: {\n enter(node) {\n if (current) current.spreads.push({ name: node.name.value, depth });\n },\n },\n },\n\n collect() {\n const fragments = context.getFragmentGraph();\n\n // Transitive selection depth, expanding spreads (memoised, cycle-guarded).\n const depthMemo = new Map<string, number>();\n const effectiveDepth = (defId: string, visiting: Set<string>): number => {\n const cached = depthMemo.get(defId);\n if (cached != null) return cached;\n const metrics = byDef.get(defId);\n if (!metrics) return 0;\n let result = metrics.ownDepth;\n for (const spread of metrics.spreads) {\n const fragmentId = fragments.resolve(metrics.schemaName, spread.name);\n if (!fragmentId || visiting.has(fragmentId)) continue;\n visiting.add(fragmentId);\n result = Math.max(result, spread.depth - 1 + effectiveDepth(fragmentId, visiting));\n visiting.delete(fragmentId);\n }\n depthMemo.set(defId, result);\n return result;\n };\n\n const datapoints: RuleDatapoint<ComplexityData>[] = context.operations.map((op) => {\n const fields = new Set<string>(byDef.get(op.id)?.fields);\n const listFields = new Set<string>(byDef.get(op.id)?.listFields);\n for (const fragmentId of fragments.reachableFragments(op.id)) {\n const metrics = byDef.get(fragmentId);\n if (!metrics) continue;\n for (const coordinate of metrics.fields) fields.add(coordinate);\n for (const coordinate of metrics.listFields) listFields.add(coordinate);\n }\n const operationDepth = effectiveDepth(op.id, new Set());\n const score =\n fields.size + operationDepth * operationDepth + listFields.size * LIST_WEIGHT;\n\n return {\n ref: { kind: 'operation', id: op.id },\n message: `${op.name || '(anonymous)'}: depth ${operationDepth}, ${fields.size} fields (${listFields.size} list)`,\n weight: score,\n data: {\n depth: operationDepth,\n fieldCount: fields.size,\n listFields: listFields.size,\n fields: [...fields].sort(),\n score,\n },\n };\n });\n\n return datapoints.sort((a, b) => b.data.score - a.data.score);\n },\n };\n },\n};\n","import type { ScanRule } from '../types';\n\nexport interface FetchDepthData {\n /** Shortest import-distance from an entry point to the defining module. */\n depth: number | null;\n area: string;\n module: string;\n}\n\n/** Where each query sits in the module graph: how far its defining module is\n * from an entry point. As a distribution this describes data-fetching placement\n * (hoisted to route boundaries vs. scattered deep in the tree, i.e. waterfalls).\n *\n * Restricted to queries: mutations and subscriptions are naturally triggered\n * deep in the tree (event handlers, forms), so their depth carries no signal. */\nexport const fetchDepth: ScanRule<FetchDepthData> = {\n name: 'fetch-depth',\n description: 'Distance from an entry point to where each query is defined.',\n create(context) {\n // Reads the static module graph in collect(); no traversal state needed.\n return {\n visitor: {},\n collect() {\n const graph = context.getModuleGraph();\n return context.operations\n .filter((op) => op.kind === 'query')\n .map((op) => {\n const depth = graph.distanceFromEntry(op.module);\n return { op, depth: depth ?? null };\n })\n .sort((a, b) => (b.depth ?? -1) - (a.depth ?? -1))\n .map(({ op, depth }) => ({\n ref: { kind: 'operation' as const, id: op.id },\n message: `${op.name || '(anonymous)'} is ${\n depth == null\n ? 'unreachable from any entry point'\n : `${depth} hop(s) from an entry point`\n }`,\n weight: depth ?? undefined,\n data: { depth, area: graph.areaOf(op.module), module: op.module },\n }));\n },\n };\n },\n};\n","import type { ScanRule } from '../types';\n\nexport interface DirectiveUsageData {\n count: number;\n}\n\n/** How often each directive is applied across all documents (e.g. `@skip`,\n * `@include`, `@defer`, `@_unmask`, custom client directives). Useful for\n * gauging adoption of directive-based features. */\nexport const directiveUsage: ScanRule<DirectiveUsageData> = {\n name: 'directive-usage',\n description: 'Application count per directive across documents.',\n create() {\n const counts = new Map<string, number>();\n return {\n visitor: {\n Directive: {\n enter(node) {\n counts.set(node.name.value, (counts.get(node.name.value) || 0) + 1);\n },\n },\n },\n collect() {\n return [...counts.entries()]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([name, count]) => ({\n ref: { kind: 'directive', name },\n message: `@${name} applied ${count} time(s)`,\n weight: count,\n data: { count },\n }));\n },\n };\n },\n};\n","import type { ScanContext } from '../context';\nimport type { RuleResults } from '../types';\nimport { allSchemaFields } from '../schema-util';\n\nexport interface ScanOverview {\n operations: number;\n fragments: number;\n modules: number;\n operationsByKind: { query: number; mutation: number; subscription: number };\n coverage: { usedFields: number; totalFields: number; percent: number };\n}\n\n/** Project-level totals, derived from the corpus, the schema, and the\n * field-usage rule. Shared so the JSON `overview` and the terminal header show\n * the same numbers. */\nexport function buildOverview(context: ScanContext, rules: RuleResults): ScanOverview {\n const operationsByKind = { query: 0, mutation: 0, subscription: 0 };\n for (const op of context.operations) operationsByKind[op.kind]++;\n\n // field-usage emits one datapoint per used schema field.\n const usedFields = (rules['field-usage'] || []).length;\n const totalFields = allSchemaFields(context.getSchemas()).length;\n const percent = totalFields ? Math.round((usedFields / totalFields) * 100) : 100;\n\n return {\n operations: context.operations.length,\n fragments: context.fragments.length,\n modules: context.modules.length,\n operationsByKind,\n coverage: { usedFields, totalFields, percent },\n };\n}\n","import { isObjectType, isInterfaceType } from 'graphql';\nimport type { GraphQLSchema } from 'graphql';\n\nimport type { SchemaName } from './types';\n\nexport interface SchemaFieldInfo {\n coordinate: string;\n typeName: string;\n fieldName: string;\n fieldType: string;\n deprecationReason?: string | undefined;\n}\n\n/** Enumerates every object/interface field across the schemas, deduped by\n * coordinate. A pure helper rules use to reconcile usage against the schema. */\nexport function allSchemaFields(schemas: Map<SchemaName, GraphQLSchema>): SchemaFieldInfo[] {\n const seen = new Map<string, SchemaFieldInfo>();\n for (const schema of schemas.values()) {\n for (const type of Object.values(schema.getTypeMap())) {\n if (type.name.startsWith('__')) continue;\n if (!isObjectType(type) && !isInterfaceType(type)) continue;\n for (const field of Object.values(type.getFields())) {\n const coordinate = `${type.name}.${field.name}`;\n if (!seen.has(coordinate)) {\n seen.set(coordinate, {\n coordinate,\n typeName: type.name,\n fieldName: field.name,\n fieldType: String(field.type),\n deprecationReason: field.deprecationReason ?? undefined,\n });\n }\n }\n }\n }\n return [...seen.values()];\n}\n","import type { ScanContext } from '../context';\nimport type { RuleResults, OperationInfo, FragmentInfo } from '../types';\nimport { buildOverview, type ScanOverview } from './overview';\n\nexport interface ScanJsonOutput {\n version: number;\n /** Project-level totals (same numbers the terminal header shows). */\n overview: ScanOverview;\n /** Discovered operations, with identity (kind, module, loc, variables, hash). */\n operations: OperationInfo[];\n /** Discovered fragments, with identity (type condition, module, loc, hash). */\n fragments: FragmentInfo[];\n /** Each rule's datapoints, keyed by rule name. */\n rules: RuleResults;\n}\n\n/** Serialises the analysis result — overview, operation/fragment identities, and\n * the rule datapoints the terminal report renders — to the stable JSON\n * substrate. The relationship graph is emitted separately via `--graph`. */\nexport function renderJson(context: ScanContext, rules: RuleResults): string {\n const output: ScanJsonOutput = {\n version: 1,\n overview: buildOverview(context, rules),\n operations: [...context.operations],\n fragments: [...context.fragments],\n rules,\n };\n return JSON.stringify(output, null, 2) + '\\n';\n}\n","import * as path from 'node:path';\n\nimport type { ScanContext } from '../context';\nimport type { RuleResults, ScanGraph, ScanGraphNode, ScanGraphEdge, SchemaName } from '../types';\nimport type { FieldUsageData } from '../rules';\n\nconst CWD = process.cwd();\nconst relative = (modulePath: string): string => path.relative(CWD, modulePath) || modulePath;\n\nconst moduleNodeId = (modulePath: string): string => `module:${modulePath}`;\nconst fieldNodeId = (coordinate: string): string => `field:${coordinate}`;\nconst typeNodeId = (typeName: string): string => `type:${typeName}`;\nconst fragmentKey = (schemaName: SchemaName, name: string): string =>\n `${schemaName ?? ''}\\0${name}`;\n\n/** Serialises the pure relationship graph (emitted via `--graph`). */\nexport function renderGraph(context: ScanContext, rules: RuleResults): string {\n return JSON.stringify(buildGraph(context, rules), null, 2) + '\\n';\n}\n\n/** Composes the module ↔ document ↔ fragment ↔ schema relationship graph from\n * the corpus (identities, spreads, imports) and the field-usage rule (the\n * field selections). A derived view assembled at output time. */\nexport function buildGraph(context: ScanContext, rules: RuleResults): ScanGraph {\n const nodes = new Map<string, ScanGraphNode>();\n const edges: ScanGraphEdge[] = [];\n const addNode = (node: ScanGraphNode): void => {\n if (!nodes.has(node.id)) nodes.set(node.id, node);\n };\n\n const fragmentIdByName = new Map<string, string>();\n for (const fragment of context.fragments) {\n fragmentIdByName.set(fragmentKey(fragment.schemaName, fragment.name), fragment.id);\n }\n\n const moduleNode = (modulePath: string): void => {\n addNode({ id: moduleNodeId(modulePath), kind: 'module', label: relative(modulePath) });\n };\n\n // The full project import graph (not just GraphQL-bearing modules), so the\n // emitted `imports` edges match what reachability/fetch-depth actually use.\n for (const [from, tos] of context.getModuleGraph().importMap()) {\n moduleNode(from);\n for (const target of tos) {\n moduleNode(target);\n edges.push({ from: moduleNodeId(from), to: moduleNodeId(target), kind: 'imports' });\n }\n }\n\n // Schema field/type nodes + `selects` edges come from the field-usage rule\n // (which only indexes used fields, so the graph is bounded to what's used).\n for (const datapoint of rules['field-usage'] || []) {\n if (datapoint.ref.kind !== 'field') continue;\n const coordinate = datapoint.ref.coordinate;\n const usage = datapoint.data as FieldUsageData;\n addNode({ id: fieldNodeId(coordinate), kind: 'schemaField', label: coordinate });\n addNode({ id: typeNodeId(usage.typeName), kind: 'schemaType', label: usage.typeName });\n edges.push({ from: fieldNodeId(coordinate), to: typeNodeId(usage.typeName), kind: 'onType' });\n for (const site of usage.directUsages) {\n edges.push({ from: site.defId, to: fieldNodeId(coordinate), kind: 'selects' });\n }\n }\n\n const addDefinition = (\n id: string,\n kind: 'operation' | 'fragment',\n label: string,\n module: string,\n spreads: readonly string[],\n schemaName: SchemaName\n ): void => {\n addNode({ id, kind, label });\n moduleNode(module); // ensure the defining module is a node even if it has no imports\n edges.push({ from: moduleNodeId(module), to: id, kind: 'defines' });\n for (const spreadName of spreads) {\n const target = fragmentIdByName.get(fragmentKey(schemaName, spreadName));\n if (target) edges.push({ from: id, to: target, kind: 'spreads' });\n }\n };\n\n for (const op of context.operations) {\n addDefinition(\n op.id,\n 'operation',\n op.name || '(anonymous)',\n op.module,\n op.fragmentSpreads,\n op.schemaName\n );\n }\n for (const fragment of context.fragments) {\n addDefinition(\n fragment.id,\n 'fragment',\n fragment.name,\n fragment.module,\n fragment.fragmentSpreads,\n fragment.schemaName\n );\n }\n\n return { nodes: [...nodes.values()], edges };\n}\n","import * as path from 'node:path';\nimport * as t from '../../../term';\n\nimport type { ScanContext } from '../context';\nimport type { RuleResults, DatapointRef } from '../types';\nimport { DEFAULT_RULES } from '../rules';\nimport { buildOverview } from './overview';\n\nconst CWD = process.cwd();\n/** Maximum datapoints shown per rule in the terminal report. */\nconst MAX_PER_RULE = 8;\n/** Below this many columns left for the message, the locator is dropped first. */\nconst MIN_MESSAGE_WIDTH = 24;\n\nconst RULE_DESCRIPTIONS = new Map(DEFAULT_RULES.map((rule) => [rule.name, rule.description]));\n\nconst truncate = (text: string, max: number): string =>\n text.length <= max\n ? text\n : max > 1\n ? text.slice(0, max - 1) + t.Chars.Ellipsis\n : t.Chars.Ellipsis;\n\nconst relative = (filePath: string): string => {\n const rel = path.relative(CWD, filePath);\n return !rel.startsWith('..') ? rel : filePath;\n};\n\n/** Resolves a datapoint's `ref` to a short `file:line` locator, where one exists. */\nfunction locator(ref: DatapointRef, context: ScanContext): string | undefined {\n switch (ref.kind) {\n case 'operation': {\n const op = context.operations.find((item) => item.id === ref.id);\n return op ? `${relative(op.loc.file)}:${op.loc.line}` : undefined;\n }\n case 'fragment': {\n const fragment = context.fragments.find((item) => item.id === ref.id);\n return fragment ? `${relative(fragment.loc.file)}:${fragment.loc.line}` : undefined;\n }\n default:\n return undefined;\n }\n}\n\nfunction coverageLine(context: ScanContext, rules: RuleResults): string {\n const { usedFields, totalFields, percent } = buildOverview(context, rules).coverage;\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Foreground),\n 'Schema coverage: ',\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${percent}% `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `(${usedFields}/${totalFields} fields used)\\n`,\n ]);\n}\n\n/** Renders the default human-facing report: coverage plus the top datapoints of\n * each rule that produced findings. `width` (terminal columns) bounds each item\n * line so it doesn't wrap; omit it for unbounded output. */\nexport function renderTerminalReport(\n context: ScanContext,\n rules: RuleResults,\n width?: number\n): string {\n let out = '\\n' + coverageLine(context, rules);\n\n for (const [name, datapoints] of Object.entries(rules)) {\n if (!datapoints.length) continue;\n\n out += t.text([\n '\\n',\n t.cmd(t.CSI.Style, t.Style.Magenta),\n `${t.SmallTriangle.Right} `,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n name,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n ` (${datapoints.length})\\n`,\n ]);\n\n const description = RULE_DESCRIPTIONS.get(name);\n if (description) {\n const text = width ? truncate(description, Math.max(width - 2, 1)) : description;\n out += t.text([t.cmd(t.CSI.Style, t.Style.BrightBlack), ` ${text}\\n`]);\n }\n\n const shown = datapoints.slice(0, MAX_PER_RULE);\n const truncated = datapoints.length > shown.length;\n // \" \" + connector + \" \"\n const prefixWidth = 4;\n shown.forEach((datapoint, index) => {\n const isLast = !truncated && index === shown.length - 1;\n const weightText = datapoint.weight != null ? `~${datapoint.weight}` : '';\n let message = datapoint.message;\n let locText = locator(datapoint.ref, context);\n\n if (width) {\n const weightWidth = weightText ? weightText.length + 2 : 0;\n let locWidth = locText ? locText.length + 2 : 0;\n let budget = width - prefixWidth - weightWidth - locWidth;\n // Too cramped for the message — drop the (long) locator before the message.\n if (locText && budget < MIN_MESSAGE_WIDTH) {\n budget += locWidth;\n locText = undefined;\n locWidth = 0;\n }\n message = truncate(message, Math.max(budget, 1));\n }\n\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n ` ${isLast ? t.Box.BottomLeft : t.Box.VerticalRight} `,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n message,\n ...(weightText ? [t.cmd(t.CSI.Style, t.Style.BrightBlue), ` ${weightText}`] : []),\n ...(locText ? [t.cmd(t.CSI.Style, t.Style.BrightBlack), ` ${locText}`] : []),\n '\\n',\n ]);\n });\n\n if (truncated) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n ` ${t.Box.BottomLeft} ${t.Chars.Ellipsis} and ${datapoints.length - shown.length} more\\n`,\n ]);\n }\n }\n\n return out;\n}\n","import { pipe, interval, map, concat, fromValue } from 'wonka';\n\nimport * as path from 'node:path';\nimport * as t from '../../term';\n\nimport type { ScanWarning } from './types';\nimport { indent } from '../shared/logger';\n\nexport * from '../shared/logger';\n\nconst CWD = process.cwd();\nconst INDENT = ' ';\n\nexport function warningFile(filePath: string) {\n const relativePath = path.relative(CWD, filePath);\n if (!relativePath.startsWith('..')) filePath = relativePath;\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Underline),\n filePath,\n t.cmd(t.CSI.Style, t.Style.NoUnderline),\n '\\n',\n ]);\n}\n\nexport function warningMessage(message: ScanWarning) {\n return t.text([\n INDENT,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${message.line}:${message.col}`,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n indent(message.message.trim(), t.text([INDENT, t.Chars.Tab])),\n t.Chars.Newline,\n ]);\n}\n\nexport function warningGithub(message: ScanWarning): void {\n t.githubAnnotation('warning', message.message, {\n file: message.file,\n line: message.line,\n col: message.col,\n });\n}\n\nexport function runningScan(file?: number, ofFiles?: number) {\n const progress = file ? (ofFiles ? `(${file}/${ofFiles})` : `(${file})`) : '';\n const frame = (state: number) =>\n t.text([\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.dotSpinner[state % t.dotSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n `Scanning files${t.Chars.Ellipsis} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n progress,\n ]);\n return concat([\n fromValue(frame(0)),\n pipe(\n interval(150),\n map((state) => frame(state + 1))\n ),\n ]);\n}\n\nexport function summary(args: {\n warnings: number;\n operations: number;\n fragments: number;\n modules: number;\n}) {\n let out = '\\n';\n if (args.warnings) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ` ${args.warnings} warnings\\n`,\n ]);\n }\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Scan completed `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `(${args.operations} operations, ${args.fragments} fragments across ${args.modules} modules)\\n`,\n ]);\n return out;\n}\n\nexport function warningSummary(warningCount: number) {\n return t.error([t.cmd(t.CSI.Style, t.Style.Red), `${t.Icons.Cross} ${warningCount} warnings\\n`]);\n}\n\nexport function wroteOutput(label: string, filePath: string) {\n const relativePath = path.relative(CWD, filePath);\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `Wrote ${label} to `,\n t.cmd(t.CSI.Style, t.Style.Blue),\n `${!relativePath.startsWith('..') ? relativePath : filePath}\\n`,\n ]);\n}\n","import * as path from 'node:path';\nimport type { GraphQLSchema } from 'graphql';\nimport { loadRef } from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, writeOutput } from '../shared';\n\nimport type { SchemaName, RawScanDocument, ScanWarning } from './types';\nimport { analyze } from './analyze';\nimport { renderJson } from './output/json';\nimport { renderGraph } from './output/graph';\nimport { renderTerminalReport } from './output/terminal';\nimport * as logger from './logger';\n\nexport type ScanFormat = 'json';\n\nexport interface ScanOptions {\n /** The `tsconfig.json` to use for configurations and the TypeScript program. */\n tsconfig: string | undefined;\n /** When `json`, write the JSON report; otherwise show the terminal report. */\n format: ScanFormat | undefined;\n /** When set, output the pure relationship graph (implies machine output). */\n graph: boolean;\n /** Where to write machine output to. Defaults to standard output. */\n output: string | undefined;\n /** Whether to fail with a non-zero exit code if any warnings are reported. */\n failOnWarn: boolean;\n}\n\nasync function loadSchemas(project: ProjectContext): Promise<Map<SchemaName, GraphQLSchema>> {\n const ref = await loadRef(project.pluginConfig).load({ rootPath: project.projectPath });\n const schemas = new Map<SchemaName, GraphQLSchema>();\n if (ref.current) schemas.set(null, ref.current.schema);\n for (const name in ref.multi) {\n const result = ref.multi[name];\n if (result) schemas.set(name, result.schema);\n }\n return schemas;\n}\n\nexport async function* run(tty: TTY, opts: ScanOptions): AsyncIterable<ComposeInput> {\n if (opts.format && opts.format !== 'json') {\n throw logger.errorMessage(\n `Unknown ${logger.code('--format')} '${opts.format}'.\\n` +\n logger.hint(`The only supported format is ${logger.code('json')}.`)\n );\n }\n\n let projects: ProjectContext[];\n try {\n projects = await loadProjects(opts.tsconfig);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n // Machine output goes to a single destination, so it can't span projects.\n if (projects.length > 1 && (opts.format || opts.graph)) {\n throw logger.errorMessage(\n 'Machine output can only target a single project.\\n' +\n logger.hint(`Run scan per-project with an explicit ${logger.code('--tsconfig')}.`)\n );\n }\n\n let totalWarnings = 0;\n for (const project of projects) {\n if (projects.length > 1) yield logger.projectHeader(project.label);\n totalWarnings += yield* runProject(tty, opts, project);\n }\n\n if (opts.failOnWarn && totalWarnings) {\n throw logger.warningSummary(totalWarnings);\n }\n}\n\nasync function* runProject(\n tty: TTY,\n opts: ScanOptions,\n project: ProjectContext\n): AsyncGenerator<ComposeInput, number> {\n const { runScan } = await import('./thread');\n\n // `--graph` implies machine output (the pure relationship graph).\n const machine = !!opts.format || opts.graph;\n // When machine output shares the (single) stdout stream, human chatter would\n // corrupt it — so suppress progress/warnings/summary in that case.\n const quiet = machine && !opts.output && !tty.pipeTo;\n\n let schemas: Map<SchemaName, GraphQLSchema>;\n try {\n schemas = await loadSchemas(project);\n } catch (error) {\n throw logger.externalError('Failed to load schema.', error);\n }\n\n const generator = runScan({\n rootPath: project.configResult.rootPath,\n tsconfigPath: project.configResult.tsconfigPath,\n configPath: project.configResult.configPath,\n pluginConfig: project.pluginConfig,\n });\n\n const documents: RawScanDocument[] = [];\n const imports = new Map<string, string[]>();\n const warnings: ScanWarning[] = [];\n let totalFileCount = 0;\n let fileCount = 0;\n\n try {\n if (tty.isInteractive && !quiet) yield logger.runningScan();\n\n for await (const signal of generator) {\n if (signal.kind === 'EXTERNAL_WARNING') {\n if (!quiet) {\n yield logger.experimentMessage(\n `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n );\n }\n } else if (signal.kind === 'FILE_COUNT') {\n totalFileCount = signal.fileCount;\n } else {\n fileCount++;\n documents.push(...signal.documents);\n if (signal.imports.length) imports.set(signal.filePath, signal.imports);\n if (signal.warnings.length) {\n warnings.push(...signal.warnings);\n if (!quiet) {\n let buffer = logger.warningFile(signal.filePath);\n for (const warning of signal.warnings) {\n buffer += logger.warningMessage(warning);\n logger.warningGithub(warning);\n }\n yield buffer + '\\n';\n }\n }\n }\n\n if (tty.isInteractive && !quiet) yield logger.runningScan(fileCount, totalFileCount);\n }\n } catch (error) {\n throw logger.externalError('Could not scan files', error);\n }\n\n // Both outputs render from the same analysis result (the rule datapoints, plus\n // the context's identities for resolving locators).\n const { context, rules } = analyze({ documents, schemas, imports, warnings });\n\n if (machine) {\n const label = opts.graph ? 'graph' : 'JSON report';\n const render = opts.graph ? renderGraph : renderJson;\n // Default to stdout; `--output` writes a file instead.\n const destination: WriteTarget = opts.output\n ? path.resolve(process.cwd(), opts.output)\n : (tty.pipeTo ?? process.stdout);\n try {\n await writeOutput(destination, render(context, rules));\n } catch (error) {\n throw logger.externalError(`Something went wrong while writing the ${label}`, error);\n }\n if (!quiet && typeof destination === 'string') {\n yield logger.wroteOutput(label, destination);\n }\n } else {\n // Bound item lines to the terminal width so they don't wrap; unbounded when\n // not writing to an interactive terminal.\n const width = tty.isInteractive ? tty.output.columns || 80 : undefined;\n yield renderTerminalReport(context, rules, width);\n }\n\n if (!quiet) {\n yield logger.summary({\n warnings: context.warnings.length,\n operations: context.operations.length,\n fragments: context.fragments.length,\n modules: context.modules.length,\n });\n }\n\n return context.warnings.length;\n}\n","import { visit, visitInParallel, visitWithTypeInfo, TypeInfo, Kind } from 'graphql';\nimport type { DocumentNode } from 'graphql';\n\nimport { ScanContext } from './context';\nimport type { ScanContextParams } from './context';\nimport { DEFAULT_RULES } from './rules';\nimport type { ScanRule, RuleResults } from './types';\n\nexport interface ScanAnalysis {\n context: ScanContext;\n rules: RuleResults;\n}\n\n/**\n * Runs the analysis: builds the context (corpus + primitives), then walks every\n * definition once per schema with all rule visitors merged in parallel —\n * mirroring graphql-js `validate`. Each rule accumulates its own state during\n * the traversal and converts it to datapoints in `collect()`.\n */\nexport function analyze(\n params: ScanContextParams,\n rules: ScanRule[] = DEFAULT_RULES\n): ScanAnalysis {\n const context = new ScanContext(params);\n const instances = rules.map((rule) => ({ name: rule.name, instance: rule.create(context) }));\n\n for (const [schemaName, schema] of context.getSchemas()) {\n const definitions = context.definitionNodesForSchema(schemaName);\n if (!definitions.length) continue;\n\n const typeInfo = new TypeInfo(schema);\n context.setTypeInfo(typeInfo);\n\n // A fresh `visitInParallel` per schema (its skip-state is per-call), but the\n // same rule instances, so their accumulated state carries across schemas.\n const visitor = visitInParallel([\n context.trackingVisitor(),\n ...instances.map(({ instance }) => instance.visitor),\n ]);\n\n const document: DocumentNode = { kind: Kind.DOCUMENT, definitions };\n visit(document, visitWithTypeInfo(typeInfo, visitor));\n }\n\n const results: RuleResults = {};\n for (const { name, instance } of instances) results[name] = instance.collect();\n return { context, rules: results };\n}\n","import { Command, Option } from 'clipanion';\n\nimport type { ScanOptions, ScanFormat } from './runner';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class ScanCommand extends Command {\n static paths = [['scan']];\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` read for configuration.',\n });\n\n format = Option.String('--format,-f', {\n description: 'Emit the machine-readable `json` report.\\tDefault: a terminal report',\n });\n\n graph = Option.Boolean('--graph', false, {\n description: 'Emit only the relationship graph as JSON (implies machine output).',\n });\n\n output = Option.String('--output,-o', {\n description: 'Write machine output to this file.\\tDefault: standard output',\n });\n\n failOnWarn = Option.Boolean('--fail-on-warn,-w', false, {\n description: 'Triggers an error and a non-zero exit code if any warnings have been reported',\n });\n\n async execute() {\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n tsconfig: this.tsconfig,\n format: this.format as ScanFormat | undefined,\n graph: this.graph,\n output: this.output,\n failOnWarn: this.failOnWarn,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Scans a project for all GraphQL documents and fragments, keys them to the\n * schema, and emits a JSON report (when piped or given `--output`) or a\n * human-readable terminal report.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#scan}\n */\nexport async function scan(opts: ScanOptions) {\n const tty = initTTY({ disableTTY: true });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","import { pipe, interval, map, concat, fromValue } from 'wonka';\n\nimport * as path from 'node:path';\nimport * as t from '../../term';\nimport type { DiagnosticMessage } from './types';\nimport type { SeveritySummary } from './types';\n\nexport * from '../shared/logger';\nimport { indent } from '../shared/logger';\n\nconst CWD = process.cwd();\nconst INDENT = ' ';\n\nexport function diagnosticFile(filePath: string) {\n const relativePath = path.relative(CWD, filePath);\n if (!relativePath.startsWith('..')) filePath = relativePath;\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Underline),\n filePath,\n t.cmd(t.CSI.Style, t.Style.NoUnderline),\n '\\n',\n ]);\n}\n\nexport function diagnosticMessage(message: DiagnosticMessage) {\n let color = t.Style.Foreground;\n if (message.severity === 'info') {\n color = t.Style.BrightBlue;\n } else if (message.severity === 'warn') {\n color = t.Style.BrightYellow;\n } else if (message.severity === 'error') {\n color = t.Style.BrightRed;\n }\n\n return t.text([\n INDENT,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${message.line}:${message.col}`,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, color),\n message.severity,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n indent(message.message.trim(), t.text([INDENT, t.Chars.Tab, t.Chars.Tab])),\n t.Chars.Newline,\n ]);\n}\n\nexport function infoSummary(summary: SeveritySummary) {\n const { info, error, warn } = summary;\n let out = '';\n if (info) {\n out += t.text([t.cmd(t.CSI.Style, t.Style.Blue), t.Icons.Info, ` ${info} notices\\n`]);\n }\n if (error || warn) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ` ${error + warn} problems (${error} errors, ${warn} warnings)\\n`,\n ]);\n } else {\n out += t.text([t.cmd(t.CSI.Style, t.Style.BrightGreen), t.Icons.Tick, ` No problems found\\n`]);\n }\n return out;\n}\n\nexport function problemsSummary(summary: SeveritySummary) {\n const { info, error, warn } = summary;\n let out = '';\n if (info) {\n out += t.text([t.cmd(t.CSI.Style, t.Style.Blue), t.Icons.Info, ` ${info} notices\\n`]);\n }\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.Red),\n t.Icons.Cross,\n ` ${error + warn} problems (${error} errors, ${warn} warnings)\\n`,\n ]);\n return t.error(out);\n}\n\nexport function diagnosticMessageGithub(message: DiagnosticMessage): void {\n const kind =\n message.severity === 'warn' ? 'warning' : message.severity === 'error' ? 'error' : 'notice';\n t.githubAnnotation(kind, message.message, {\n file: message.file,\n line: message.line,\n col: message.col,\n endLine: message.endLine,\n endColumn: message.endColumn,\n });\n}\n\nexport function runningDiagnostics(file?: number, ofFiles?: number) {\n const progress = file ? (ofFiles ? `(${file}/${ofFiles})` : `(${file})`) : '';\n const frame = (state: number) =>\n t.text([\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.dotSpinner[state % t.dotSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n `Checking files${t.Chars.Ellipsis} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n progress,\n ]);\n return concat([\n fromValue(frame(0)),\n pipe(\n interval(150),\n map((state) => frame(state + 1))\n ),\n ]);\n}\n","import * as logger from './logger';\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext } from '../shared';\nimport { loadProjects } from '../shared';\nimport type { Severity, SeveritySummary } from './types';\n\nconst isMinSeverity = (severity: Severity, minSeverity: Severity) => {\n switch (severity) {\n case 'info':\n return minSeverity !== 'warn' && minSeverity !== 'error';\n case 'warn':\n return minSeverity !== 'error';\n case 'error':\n return true;\n }\n};\n\nexport interface FormattedDisplayableDiagnostic {\n severity: Severity;\n message: string;\n line: number;\n col: number;\n file: string | undefined;\n}\n\nexport interface Options {\n failOnWarn: boolean | undefined;\n minSeverity: Severity;\n tsconfig: string | undefined;\n}\n\nexport async function* run(tty: TTY, opts: Options): AsyncIterable<ComposeInput> {\n const { runDiagnostics } = await import('./thread');\n\n let projects: ProjectContext[];\n try {\n projects = await loadProjects(opts.tsconfig);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n const summary: SeveritySummary = { warn: 0, error: 0, info: 0 };\n const minSeverity = opts.minSeverity;\n let warnedAboutExternalFiles = false;\n\n for (const project of projects) {\n if (projects.length > 1) yield logger.projectHeader(project.label);\n\n const generator = runDiagnostics({\n rootPath: project.configResult.rootPath,\n tsconfigPath: project.configResult.tsconfigPath,\n configPath: project.configResult.configPath,\n pluginConfig: project.pluginConfig,\n });\n\n let totalFileCount = 0;\n let fileCount = 0;\n\n try {\n if (tty.isInteractive) yield logger.runningDiagnostics();\n\n for await (const signal of generator) {\n if (signal.kind === 'EXTERNAL_WARNING') {\n if (!warnedAboutExternalFiles) {\n warnedAboutExternalFiles = true;\n yield logger.experimentMessage(\n `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n );\n }\n } else if (signal.kind === 'FILE_COUNT') {\n totalFileCount = signal.fileCount;\n } else {\n fileCount++;\n let buffer = '';\n for (const message of signal.messages) {\n summary[message.severity]++;\n if (isMinSeverity(message.severity, minSeverity)) {\n buffer += logger.diagnosticMessage(message);\n logger.diagnosticMessageGithub(message);\n }\n }\n if (buffer) {\n yield logger.diagnosticFile(signal.filePath) + buffer + '\\n';\n }\n }\n\n if (tty.isInteractive) yield logger.runningDiagnostics(fileCount, totalFileCount);\n }\n } catch (error: any) {\n throw logger.externalError('Could not check files', error);\n }\n }\n\n // Reset notice count if it's outside of min severity\n if (minSeverity !== 'info') summary.info = 0;\n\n if ((opts.failOnWarn && summary.warn) || summary.error) {\n throw logger.problemsSummary(summary);\n } else {\n yield logger.infoSummary(summary);\n }\n}\n","import * as t from 'typanion';\nimport { Command, Option } from 'clipanion';\n\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class CheckCommand extends Command {\n static paths = [['check']];\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` used to read',\n });\n\n failOnWarn = Option.Boolean('--fail-on-warn,-w', false, {\n description: 'Triggers an error and a non-zero exit code if any warnings have been reported',\n });\n\n minSeverity =\n Option.String('--level,-l', {\n description: 'The minimum severity of diagnostics to display (info, warn, error)',\n validator: t.isOneOf([t.isLiteral('info'), t.isLiteral('warn'), t.isLiteral('error')]),\n }) || 'info';\n\n async execute() {\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n failOnWarn: this.failOnWarn,\n minSeverity: this.minSeverity,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n","var fn = new Intl.Collator(0, { numeric:1 }).compare;\n\nexport default function (a, b, bool) {\n\ta = a.split('.');\n\tb = b.split('.');\n\n\treturn fn(a[0], b[0]) || fn(a[1], b[1]) || (\n\t\tb[2] = b.slice(2).join('.'),\n\t\tbool = /[.-]/.test(a[2] = a.slice(2).join('.')),\n\t\tbool == /[.-]/.test(b[2]) ? fn(a[2], b[2]) : bool ? -1 : 1\n\t);\n}\n","import semiver from 'semiver';\n\nexport const MINIMUM_VERSIONS = {\n typescript_embed_lsp: '5.5.0',\n typescript: '4.1.0',\n tada: '1.0.0',\n lsp: '1.0.0',\n};\n\nexport const semverComply = (version: string, compare: string) => {\n const match = version.match(/\\d+\\.\\d+\\.\\d+/);\n return match ? semiver(match[0], compare) >= 0 : false;\n};\n","import type ts from 'typescript';\n\nexport interface SourcePosition {\n fileName: string;\n line: number;\n col: number;\n endLine: number | undefined;\n endColumn: number | undefined;\n}\n\nexport const spanToFilePosition = (\n file: ts.SourceFile,\n span: ts.TextSpan | number\n): SourcePosition => {\n const output: SourcePosition = {\n fileName: file.fileName,\n line: 1,\n col: 1,\n endLine: undefined,\n endColumn: undefined,\n };\n let lineAndChar = file.getLineAndCharacterOfPosition(\n typeof span === 'number' ? span : span.start\n );\n output.line = lineAndChar.line + 1;\n output.col = lineAndChar.character + 1;\n if (typeof span !== 'number' && span.length > 1) {\n lineAndChar = file.getLineAndCharacterOfPosition(span.start + span.length - 1);\n output.endLine = lineAndChar.line + 1;\n output.endColumn = lineAndChar.character + 1;\n }\n return output;\n};\n","/**!\n * The MIT License (MIT)\n * Copyright (c) Microsoft Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and\n * associated documentation files (the \"Software\"), to deal in the Software without restriction,\n * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial\n * portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n * @see {@link https://github.com/microsoft/TypeScript-Website/blob/7f1c6e0577a0df9f945530a876ec87145a8b1fee/packages/typescript-vfs/src/index.ts}\n */\n\nimport type {\n System,\n CompilerOptions,\n CustomTransformers,\n LanguageServiceHost,\n CompilerHost,\n SourceFile,\n} from 'typescript';\n\nimport * as path from 'node:path';\nimport * as fs from 'node:fs';\n\ntype TS = typeof import('typescript');\n\nexport interface VirtualTypeScriptEnvironment {\n sys: System;\n languageService: import('typescript').LanguageService;\n getSourceFile: (fileName: string) => import('typescript').SourceFile | undefined;\n createFile: (fileName: string, content: string) => void;\n updateFile: (\n fileName: string,\n content: string,\n replaceTextSpan?: import('typescript').TextSpan\n ) => void;\n}\n\n/**\n * Makes a virtual copy of the TypeScript environment. This is the main API you want to be using with\n * `@typescript/vfs`. A lot of the other exposed functions are used by this function to get set up.\n *\n * @param sys - an object which conforms to the TS Sys (a shim over read/write access to the fs)\n * @param rootFiles - a list of files which are considered inside the project\n * @param ts - a copy of the TypeScript module\n * @param compilerOptions - the options for this compiler run\n * @param customTransformers - custom transformers for this compiler run\n */\nexport function createVirtualTypeScriptEnvironment(\n sys: System,\n rootFiles: string[],\n ts: TS,\n compilerOptions: CompilerOptions = {},\n customTransformers?: CustomTransformers\n): VirtualTypeScriptEnvironment {\n const mergedCompilerOpts = { ...defaultCompilerOptions(ts), ...compilerOptions };\n\n const { languageServiceHost, updateFile } = createVirtualLanguageServiceHost(\n sys,\n rootFiles,\n mergedCompilerOpts,\n ts,\n customTransformers\n );\n const languageService = ts.createLanguageService(languageServiceHost);\n const diagnostics = languageService.getCompilerOptionsDiagnostics();\n\n if (diagnostics.length) {\n const compilerHost = createVirtualCompilerHost(sys, compilerOptions, ts);\n throw new Error(ts.formatDiagnostics(diagnostics, compilerHost.compilerHost));\n }\n\n return {\n // @ts-ignore\n name: 'vfs',\n sys,\n languageService,\n getSourceFile: (fileName) => languageService.getProgram()?.getSourceFile(fileName),\n\n createFile: (fileName, content) => {\n updateFile(ts.createSourceFile(fileName, content, mergedCompilerOpts.target!, false));\n },\n updateFile: (fileName, content, optPrevTextSpan) => {\n const prevSourceFile = languageService.getProgram()!.getSourceFile(fileName);\n if (!prevSourceFile) {\n throw new Error('Did not find a source file for ' + fileName);\n }\n const prevFullContents = prevSourceFile.text;\n\n // TODO: Validate if the default text span has a fencepost error?\n const prevTextSpan = optPrevTextSpan ?? ts.createTextSpan(0, prevFullContents.length);\n const newText =\n prevFullContents.slice(0, prevTextSpan.start) +\n content +\n prevFullContents.slice(prevTextSpan.start + prevTextSpan.length);\n const newSourceFile = ts.updateSourceFile(prevSourceFile, newText, {\n span: prevTextSpan,\n newLength: content.length,\n });\n\n updateFile(newSourceFile);\n },\n };\n}\n\n// TODO: This could be replaced by grabbing: https://github.com/microsoft/TypeScript/blob/main/src/lib/libs.json\n// and then using that to generate the list of files from the server, but it is not included in the npm package\n\n/**\n * Grab the list of lib files for a particular target, will return a bit more than necessary (by including\n * the dom) but that's OK, we're really working with the constraint that you can't get a list of files\n * when running in a browser.\n *\n * @param target - The compiler settings target baseline\n * @param ts - A copy of the TypeScript module\n */\nexport const knownLibFilesForCompilerOptions = (compilerOptions: CompilerOptions, ts: TS) => {\n const target = compilerOptions.target || ts.ScriptTarget.ES5;\n const lib = compilerOptions.lib || [];\n\n // Note that this will include files which can't be found for particular versions of TS\n // TODO: Replace this with some sort of API call if https://github.com/microsoft/TypeScript/pull/54011\n // or similar is merged.\n const files = [\n 'lib.d.ts',\n 'lib.decorators.d.ts',\n 'lib.decorators.legacy.d.ts',\n 'lib.dom.d.ts',\n 'lib.dom.iterable.d.ts',\n 'lib.webworker.d.ts',\n 'lib.webworker.importscripts.d.ts',\n 'lib.webworker.iterable.d.ts',\n 'lib.scripthost.d.ts',\n 'lib.es5.d.ts',\n 'lib.es6.d.ts',\n 'lib.es2015.collection.d.ts',\n 'lib.es2015.core.d.ts',\n 'lib.es2015.d.ts',\n 'lib.es2015.generator.d.ts',\n 'lib.es2015.iterable.d.ts',\n 'lib.es2015.promise.d.ts',\n 'lib.es2015.proxy.d.ts',\n 'lib.es2015.reflect.d.ts',\n 'lib.es2015.symbol.d.ts',\n 'lib.es2015.symbol.wellknown.d.ts',\n 'lib.es2016.array.include.d.ts',\n 'lib.es2016.d.ts',\n 'lib.es2016.full.d.ts',\n 'lib.es2017.d.ts',\n 'lib.es2017.date.d.ts',\n 'lib.es2017.full.d.ts',\n 'lib.es2017.intl.d.ts',\n 'lib.es2017.object.d.ts',\n 'lib.es2017.sharedmemory.d.ts',\n 'lib.es2017.string.d.ts',\n 'lib.es2017.typedarrays.d.ts',\n 'lib.es2018.asyncgenerator.d.ts',\n 'lib.es2018.asynciterable.d.ts',\n 'lib.es2018.d.ts',\n 'lib.es2018.full.d.ts',\n 'lib.es2018.intl.d.ts',\n 'lib.es2018.promise.d.ts',\n 'lib.es2018.regexp.d.ts',\n 'lib.es2019.array.d.ts',\n 'lib.es2019.d.ts',\n 'lib.es2019.full.d.ts',\n 'lib.es2019.intl.d.ts',\n 'lib.es2019.object.d.ts',\n 'lib.es2019.string.d.ts',\n 'lib.es2019.symbol.d.ts',\n 'lib.es2020.bigint.d.ts',\n 'lib.es2020.d.ts',\n 'lib.es2020.date.d.ts',\n 'lib.es2020.full.d.ts',\n 'lib.es2020.intl.d.ts',\n 'lib.es2020.number.d.ts',\n 'lib.es2020.promise.d.ts',\n 'lib.es2020.sharedmemory.d.ts',\n 'lib.es2020.string.d.ts',\n 'lib.es2020.symbol.wellknown.d.ts',\n 'lib.es2021.d.ts',\n 'lib.es2021.full.d.ts',\n 'lib.es2021.intl.d.ts',\n 'lib.es2021.promise.d.ts',\n 'lib.es2021.string.d.ts',\n 'lib.es2021.weakref.d.ts',\n 'lib.es2022.array.d.ts',\n 'lib.es2022.d.ts',\n 'lib.es2022.error.d.ts',\n 'lib.es2022.full.d.ts',\n 'lib.es2022.intl.d.ts',\n 'lib.es2022.object.d.ts',\n 'lib.es2022.regexp.d.ts',\n 'lib.es2022.sharedmemory.d.ts',\n 'lib.es2022.string.d.ts',\n 'lib.es2023.array.d.ts',\n 'lib.es2023.collection.d.ts',\n 'lib.es2023.d.ts',\n 'lib.es2023.full.d.ts',\n 'lib.esnext.array.d.ts',\n 'lib.esnext.asynciterable.d.ts',\n 'lib.esnext.bigint.d.ts',\n 'lib.esnext.d.ts',\n 'lib.esnext.decorators.d.ts',\n 'lib.esnext.disposable.d.ts',\n 'lib.esnext.full.d.ts',\n 'lib.esnext.intl.d.ts',\n 'lib.esnext.promise.d.ts',\n 'lib.esnext.string.d.ts',\n 'lib.esnext.symbol.d.ts',\n 'lib.esnext.weakref.d.ts',\n ];\n\n const targetToCut = ts.ScriptTarget[target];\n const matches = files.filter((f) => f.startsWith(`lib.${targetToCut.toLowerCase()}`));\n const targetCutIndex = files.indexOf(matches.pop()!);\n\n const getMax = (array: number[]) =>\n array && array.length\n ? array.reduce((max, current) => (current > max ? current : max))\n : undefined;\n\n // Find the index for everything in\n const indexesForCutting = lib.map((lib) => {\n const matches = files.filter((f) => f.startsWith(`lib.${lib.toLowerCase()}`));\n if (matches.length === 0) return 0;\n\n const cutIndex = files.indexOf(matches.pop()!);\n return cutIndex;\n });\n\n const libCutIndex = getMax(indexesForCutting) || 0;\n\n const finalCutIndex = Math.max(targetCutIndex, libCutIndex);\n return files.slice(0, finalCutIndex + 1);\n};\n\n/**\n * Sets up a Map with lib contents by grabbing the necessary files from\n * the local copy of typescript via the file system.\n *\n * The first two args are un-used, but kept around so as to not cause a\n * semver major bump for no gain to module users.\n */\nexport const createDefaultMapFromNodeModules = (\n _compilerOptions: CompilerOptions,\n _ts?: typeof import('typescript'),\n tsLibDirectory?: string\n) => {\n const getLib = (name: string) => {\n const lib = tsLibDirectory || path.dirname(require.resolve('typescript'));\n return fs.readFileSync(path.join(lib, name), 'utf8');\n };\n\n const libFiles = fs.readdirSync(tsLibDirectory || path.dirname(require.resolve('typescript')));\n const knownLibFiles = libFiles.filter((f) => f.startsWith('lib.') && f.endsWith('.d.ts'));\n\n const fsMap = new Map<string, string>();\n knownLibFiles.forEach((lib) => {\n fsMap.set('/' + lib, getLib(lib));\n });\n return fsMap;\n};\n\n/**\n * Adds recursively files from the FS into the map based on the folder\n */\nexport const addAllFilesFromFolder = (map: Map<string, string>, workingDir: string): void => {\n const walk = function (dir: string) {\n let results: string[] = [];\n const list = fs.readdirSync(dir);\n list.forEach(function (file: string) {\n file = path.join(dir, file);\n const stat = fs.statSync(file);\n if (stat && stat.isDirectory()) {\n /* Recurse into a subdirectory */\n results = results.concat(walk(file));\n } else {\n /* Is a file */\n results.push(file);\n }\n });\n return results;\n };\n\n const allFiles = walk(workingDir);\n\n allFiles.forEach((lib) => {\n const fsPath = '/node_modules/@types' + lib.replace(workingDir, '');\n const content = fs.readFileSync(lib, 'utf8');\n const validExtensions = ['.ts', '.tsx'];\n\n if (validExtensions.includes(path.extname(fsPath))) {\n map.set(fsPath, content);\n }\n });\n};\n\n/** Adds all files from `node_modules/@types` into the FS Map */\nexport const addFilesForTypesIntoFolder = (map: Map<string, string>) =>\n addAllFilesFromFolder(map, 'node_modules/@types');\n\nfunction notImplemented(methodName: string): any {\n throw new Error(`Method '${methodName}' is not implemented.`);\n}\n\n/** The default compiler options if TypeScript could ever change the compiler options */\nconst defaultCompilerOptions = (ts: typeof import('typescript')): CompilerOptions => {\n return {\n ...ts.getDefaultCompilerOptions(),\n jsx: ts.JsxEmit.React,\n strict: true,\n esModuleInterop: true,\n module: ts.ModuleKind.ESNext,\n suppressOutputPathCheck: true,\n skipLibCheck: true,\n skipDefaultLibCheck: true,\n moduleResolution: ts.ModuleResolutionKind.NodeJs,\n };\n};\n\n// \"/DOM.d.ts\" => \"/lib.dom.d.ts\"\nconst libize = (path: string) => path.replace('/', '/lib.').toLowerCase();\n\n/**\n * Creates an in-memory System object which can be used in a TypeScript program, this\n * is what provides read/write aspects of the virtual fs\n */\nexport function createSystem(files: Map<string, string>): System {\n return {\n args: [],\n createDirectory: () => notImplemented('createDirectory'),\n // TODO: could make a real file tree\n directoryExists: (directory) => {\n return Array.from(files.keys()).some((path) => path.startsWith(directory));\n },\n exit: () => notImplemented('exit'),\n fileExists: (fileName) => files.has(fileName) || files.has(libize(fileName)),\n getCurrentDirectory: () => '/',\n getDirectories: () => [],\n getExecutingFilePath: () => notImplemented('getExecutingFilePath'),\n readDirectory: (directory) => (directory === '/' ? Array.from(files.keys()) : []),\n readFile: (fileName) => files.get(fileName) || files.get(libize(fileName)),\n resolvePath: (path) => path,\n newLine: '\\n',\n useCaseSensitiveFileNames: true,\n write: () => notImplemented('write'),\n writeFile: (fileName, contents) => {\n files.set(fileName, contents);\n },\n };\n}\n\n/**\n * Creates a file-system backed System object which can be used in a TypeScript program, you provide\n * a set of virtual files which are prioritised over the FS versions, then a path to the root of your\n * project (basically the folder your node_modules lives)\n */\nexport function createFSBackedSystem(\n files: Map<string, string>,\n _projectRoot: string,\n ts: TS,\n tsLibDirectory?: string\n): System {\n // We need to make an isolated folder for the tsconfig, but also need to be able to resolve the\n // existing node_modules structures going back through the history\n const root = _projectRoot + '/vfs';\n\n // The default System in TypeScript\n const nodeSys = ts.sys;\n const tsLib = tsLibDirectory ?? path.dirname(require.resolve('typescript'));\n\n return {\n // @ts-ignore\n name: 'fs-vfs',\n root,\n args: [],\n realpath: (directory) => {\n if (nodeSys.realpath) return nodeSys.realpath(directory);\n return directory;\n },\n createDirectory: () => notImplemented('createDirectory'),\n // TODO: could make a real file tree\n directoryExists: (directory) => {\n return (\n Array.from(files.keys()).some((path) => path.startsWith(directory)) ||\n nodeSys.directoryExists(directory)\n );\n },\n exit: nodeSys.exit,\n fileExists: (fileName) => {\n if (files.has(fileName)) return true;\n // Don't let other tsconfigs end up touching the vfs\n if (fileName.includes('tsconfig.json') || fileName.includes('tsconfig.json')) return false;\n if (fileName.startsWith('/lib')) {\n const tsLibName = `${tsLib}/${fileName.replace('/', '')}`;\n return nodeSys.fileExists(tsLibName);\n }\n return nodeSys.fileExists(fileName);\n },\n getCurrentDirectory: () => root,\n getDirectories: nodeSys.getDirectories,\n getExecutingFilePath: () => notImplemented('getExecutingFilePath'),\n readDirectory: (...args) => {\n if (args[0] === '/') {\n return Array.from(files.keys());\n } else {\n return nodeSys.readDirectory(...args);\n }\n },\n readFile: (fileName) => {\n if (files.has(fileName)) return files.get(fileName);\n if (fileName.startsWith('/lib')) {\n const tsLibName = `${tsLib}/${fileName.replace('/', '')}`;\n const result = nodeSys.readFile(tsLibName);\n if (!result) {\n const libs = nodeSys.readDirectory(tsLib);\n throw new Error(\n `TSVFS: A request was made for ${tsLibName} but there wasn't a file found in the file map. You likely have a mismatch in the compiler options for the CDN download vs the compiler program. Existing Libs: ${libs}.`\n );\n }\n return result;\n }\n return nodeSys.readFile(fileName);\n },\n resolvePath: (path) => {\n if (files.has(path)) return path;\n return nodeSys.resolvePath(path);\n },\n newLine: '\\n',\n useCaseSensitiveFileNames: true,\n write: () => notImplemented('write'),\n writeFile: (fileName, contents) => {\n files.set(fileName, contents);\n },\n };\n}\n\n/**\n * Creates an in-memory CompilerHost -which is essentially an extra wrapper to System\n * which works with TypeScript objects - returns both a compiler host, and a way to add new SourceFile\n * instances to the in-memory file system.\n */\nexport function createVirtualCompilerHost(sys: System, compilerOptions: CompilerOptions, ts: TS) {\n const sourceFiles = new Map<string, SourceFile>();\n const save = (sourceFile: SourceFile) => {\n sourceFiles.set(sourceFile.fileName, sourceFile);\n return sourceFile;\n };\n\n type Return = {\n compilerHost: CompilerHost;\n updateFile: (sourceFile: SourceFile) => boolean;\n };\n\n const vHost: Return = {\n compilerHost: {\n ...sys,\n getCanonicalFileName: (fileName) => fileName,\n getDefaultLibFileName: () => '/' + ts.getDefaultLibFileName(compilerOptions), // '/lib.d.ts',\n // getDefaultLibLocation: () => '/',\n getDirectories: () => [],\n getNewLine: () => sys.newLine,\n getSourceFile: (fileName) => {\n return (\n sourceFiles.get(fileName) ||\n save(\n ts.createSourceFile(\n fileName,\n sys.readFile(fileName)!,\n compilerOptions.target || defaultCompilerOptions(ts).target!,\n false\n )\n )\n );\n },\n useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,\n },\n updateFile: (sourceFile) => {\n const alreadyExists = sourceFiles.has(sourceFile.fileName);\n sys.writeFile(sourceFile.fileName, sourceFile.text);\n sourceFiles.set(sourceFile.fileName, sourceFile);\n return alreadyExists;\n },\n };\n return vHost;\n}\n\n/**\n * Creates an object which can host a language service against the virtual file-system\n */\nexport function createVirtualLanguageServiceHost(\n sys: System,\n rootFiles: string[],\n compilerOptions: CompilerOptions,\n ts: TS,\n customTransformers?: CustomTransformers\n) {\n const fileNames = [...rootFiles];\n const { compilerHost, updateFile } = createVirtualCompilerHost(sys, compilerOptions, ts);\n const fileVersions = new Map<string, string>();\n let projectVersion = 0;\n const languageServiceHost: LanguageServiceHost = {\n ...compilerHost,\n getProjectVersion: () => projectVersion.toString(),\n getCompilationSettings: () => compilerOptions,\n getCustomTransformers: () => customTransformers,\n // A couple weeks of 4.8 TypeScript nightlies had a bug where the Program's\n // list of files was just a reference to the array returned by this host method,\n // which means mutations by the host that ought to result in a new Program being\n // created were not detected, since the old list of files and the new list of files\n // were in fact a reference to the same underlying array. That was fixed in\n // https://github.com/microsoft/TypeScript/pull/49813, but since the twoslash runner\n // is used in bisecting for changes, it needs to guard against being busted in that\n // couple-week period, so we defensively make a slice here.\n getScriptFileNames: () => fileNames.slice(),\n getScriptSnapshot: (fileName) => {\n const contents = sys.readFile(fileName);\n if (contents) {\n return ts.ScriptSnapshot.fromString(contents);\n }\n return;\n },\n getScriptVersion: (fileName) => {\n return fileVersions.get(fileName) || '0';\n },\n writeFile: sys.writeFile,\n };\n\n type Return = {\n languageServiceHost: LanguageServiceHost;\n updateFile: (sourceFile: import('typescript').SourceFile) => void;\n };\n\n const lsHost: Return = {\n languageServiceHost,\n updateFile: (sourceFile) => {\n projectVersion++;\n fileVersions.set(sourceFile.fileName, projectVersion.toString());\n if (!fileNames.includes(sourceFile.fileName)) {\n fileNames.push(sourceFile.fileName);\n }\n updateFile(sourceFile);\n },\n };\n return lsHost;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.binarySearch = void 0;\nfunction binarySearch(offsets, start) {\n let low = 0;\n let high = offsets.length - 1;\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const midValue = offsets[mid];\n if (midValue < start) {\n low = mid + 1;\n }\n else if (midValue > start) {\n high = mid - 1;\n }\n else {\n low = mid;\n high = mid;\n break;\n }\n }\n return Math.max(Math.min(low, high, offsets.length - 1), 0);\n}\nexports.binarySearch = binarySearch;\n//# sourceMappingURL=binarySearch.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getStack = exports.track = exports.resetOffsetStack = exports.offsetStack = exports.setTracking = void 0;\nlet tracking = true;\nlet stackOffset = 0;\nfunction setTracking(value) {\n tracking = value;\n}\nexports.setTracking = setTracking;\nfunction offsetStack() {\n stackOffset++;\n}\nexports.offsetStack = offsetStack;\nfunction resetOffsetStack() {\n stackOffset--;\n}\nexports.resetOffsetStack = resetOffsetStack;\nfunction track(segments, stacks = []) {\n return [\n new Proxy(segments, {\n get(target, prop, receiver) {\n if (tracking) {\n if (prop === 'push')\n return push;\n if (prop === 'pop')\n return pop;\n if (prop === 'shift')\n return shift;\n if (prop === 'unshift')\n return unshift;\n if (prop === 'splice')\n return splice;\n if (prop === 'sort')\n return sort;\n if (prop === 'reverse')\n return reverse;\n }\n return Reflect.get(target, prop, receiver);\n }\n }),\n stacks,\n ];\n function push(...items) {\n stacks.push({ stack: getStack(), length: items.length });\n return segments.push(...items);\n }\n function pop() {\n if (stacks.length) {\n const last = stacks[stacks.length - 1];\n if (last.length > 1) {\n last.length--;\n }\n else {\n stacks.pop();\n }\n }\n return segments.pop();\n }\n function shift() {\n if (stacks.length) {\n const first = stacks[0];\n if (first.length > 1) {\n first.length--;\n }\n else {\n stacks.shift();\n }\n }\n return segments.shift();\n }\n function unshift(...items) {\n stacks.unshift({ stack: getStack(), length: items.length });\n return segments.unshift(...items);\n }\n function splice(start, deleteCount, ...items) {\n if (deleteCount === undefined) {\n deleteCount = segments.length - start;\n }\n let _stackStart = 0;\n let operateIndex;\n for (let i = 0; i < stacks.length; i++) {\n const stack = stacks[i];\n const stackStart = _stackStart;\n const stackEnd = stackStart + stack.length;\n _stackStart = stackEnd;\n if (start >= stackStart) {\n operateIndex = i + 1;\n const originalLength = stack.length;\n stack.length = start - stackStart;\n stacks.splice(operateIndex, 0, { stack: stack.stack, length: originalLength - stack.length });\n break;\n }\n }\n if (operateIndex === undefined) {\n throw new Error('Invalid splice operation');\n }\n let _deleteCount = deleteCount;\n for (let i = operateIndex; i < stacks.length; i++) {\n const stack = stacks[i];\n while (_deleteCount > 0 && stack.length > 0) {\n stack.length--;\n _deleteCount--;\n }\n if (_deleteCount === 0) {\n break;\n }\n }\n stacks.splice(operateIndex, 0, { stack: getStack(), length: items.length });\n return segments.splice(start, deleteCount, ...items);\n }\n function sort(compareFn) {\n stacks.splice(0, stacks.length, { stack: getStack(), length: segments.length });\n return segments.sort(compareFn);\n }\n function reverse() {\n stacks.splice(0, stacks.length, { stack: getStack(), length: segments.length });\n return segments.reverse();\n }\n}\nexports.track = track;\nfunction getStack() {\n const stack = new Error().stack;\n let source = stack.split('\\n')[3 + stackOffset].trim();\n if (source.endsWith(')')) {\n source = source.slice(source.lastIndexOf('(') + 1, -1);\n }\n else {\n source = source.slice(source.lastIndexOf(' ') + 1);\n }\n return source;\n}\nexports.getStack = getStack;\n//# sourceMappingURL=track.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=types.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.replaceRange = exports.replaceSourceRange = exports.replaceAll = exports.replace = exports.create = exports.toString = exports.getLength = void 0;\nconst binarySearch_1 = require(\"./binarySearch\");\nconst track_1 = require(\"./track\");\n__exportStar(require(\"./types\"), exports);\n__exportStar(require(\"./track\"), exports);\nfunction getLength(segments) {\n let length = 0;\n for (const segment of segments) {\n length += typeof segment == 'string' ? segment.length : segment[0].length;\n }\n return length;\n}\nexports.getLength = getLength;\nfunction toString(segments) {\n return segments.map(s => typeof s === 'string' ? s : s[0]).join('');\n}\nexports.toString = toString;\nfunction create(source) {\n return [[source, undefined, 0]];\n}\nexports.create = create;\nfunction replace(segments, pattern, ...replacers) {\n const str = toString(segments);\n const match = str.match(pattern);\n if (match && match.index !== undefined) {\n const startOffset = match.index;\n const endOffset = startOffset + match[0].length;\n (0, track_1.offsetStack)();\n replaceRange(segments, startOffset, endOffset, ...replacers.map(replacer => typeof replacer === 'function' ? replacer(match[0]) : replacer));\n (0, track_1.resetOffsetStack)();\n }\n}\nexports.replace = replace;\nfunction replaceAll(segments, pattern, ...replacers) {\n const str = toString(segments);\n const allMatch = str.matchAll(pattern);\n let length = str.length;\n let lengthDiff = 0;\n for (const match of allMatch) {\n if (match.index !== undefined) {\n const startOffset = match.index + lengthDiff;\n const endOffset = startOffset + match[0].length;\n (0, track_1.offsetStack)();\n replaceRange(segments, startOffset, endOffset, ...replacers.map(replacer => typeof replacer === 'function' ? replacer(match[0]) : replacer));\n (0, track_1.resetOffsetStack)();\n const newLength = getLength(segments);\n lengthDiff += newLength - length;\n length = newLength;\n }\n }\n}\nexports.replaceAll = replaceAll;\nfunction replaceSourceRange(segments, source, startOffset, endOffset, ...newSegments) {\n for (const segment of segments) {\n if (typeof segment === 'string') {\n continue;\n }\n if (segment[1] === source) {\n const segmentStart = segment[2];\n const segmentEnd = segment[2] + segment[0].length;\n if (segmentStart <= startOffset && segmentEnd >= endOffset) {\n const inserts = [];\n if (startOffset > segmentStart) {\n inserts.push(trimSegmentEnd(segment, startOffset - segmentStart));\n }\n for (const newSegment of newSegments) {\n inserts.push(newSegment);\n }\n if (endOffset < segmentEnd) {\n inserts.push(trimSegmentStart(segment, endOffset - segmentEnd));\n }\n combineStrings(inserts);\n (0, track_1.offsetStack)();\n segments.splice(segments.indexOf(segment), 1, ...inserts);\n (0, track_1.resetOffsetStack)();\n return true;\n }\n }\n }\n return false;\n}\nexports.replaceSourceRange = replaceSourceRange;\nfunction replaceRange(segments, startOffset, endOffset, ...newSegments) {\n const offsets = toOffsets(segments);\n const startIndex = (0, binarySearch_1.binarySearch)(offsets, startOffset);\n const endIndex = (0, binarySearch_1.binarySearch)(offsets, endOffset);\n const startSegment = segments[startIndex];\n const endSegment = segments[endIndex];\n const startSegmentStart = offsets[startIndex];\n const endSegmentStart = offsets[endIndex];\n const endSegmentEnd = offsets[endIndex] + (typeof endSegment === 'string' ? endSegment.length : endSegment[0].length);\n const inserts = [];\n if (startOffset > startSegmentStart) {\n inserts.push(trimSegmentEnd(startSegment, startOffset - startSegmentStart));\n }\n for (const newSegment of newSegments) {\n inserts.push(newSegment);\n }\n if (endOffset < endSegmentEnd) {\n inserts.push(trimSegmentStart(endSegment, endOffset - endSegmentStart));\n }\n combineStrings(inserts);\n (0, track_1.offsetStack)();\n segments.splice(startIndex, endIndex - startIndex + 1, ...inserts);\n (0, track_1.resetOffsetStack)();\n}\nexports.replaceRange = replaceRange;\nfunction combineStrings(segments) {\n for (let i = segments.length - 1; i >= 1; i--) {\n if (typeof segments[i] === 'string' && typeof segments[i - 1] === 'string') {\n segments[i - 1] = segments[i - 1] + segments[i];\n (0, track_1.offsetStack)();\n segments.splice(i, 1);\n (0, track_1.resetOffsetStack)();\n }\n }\n}\nfunction trimSegmentEnd(segment, trimEnd) {\n if (typeof segment === 'string') {\n return segment.slice(0, trimEnd);\n }\n return [\n segment[0].slice(0, trimEnd),\n ...segment.slice(1),\n ];\n}\nfunction trimSegmentStart(segment, trimStart) {\n if (typeof segment === 'string') {\n return segment.slice(trimStart);\n }\n if (trimStart < 0) {\n trimStart += segment[0].length;\n }\n return [\n segment[0].slice(trimStart),\n segment[1],\n segment[2] + trimStart,\n ...segment.slice(3),\n ];\n}\nfunction toOffsets(segments) {\n const offsets = [];\n let offset = 0;\n for (const segment of segments) {\n offsets.push(offset);\n offset += typeof segment == 'string' ? segment.length : segment[0].length;\n }\n return offsets;\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.binarySearch = void 0;\nfunction binarySearch(values, searchValue) {\n let low = 0;\n let high = values.length - 1;\n let match;\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const midValue = values[mid];\n if (midValue < searchValue) {\n low = mid + 1;\n }\n else if (midValue > searchValue) {\n high = mid - 1;\n }\n else {\n low = mid;\n high = mid;\n match = mid;\n break;\n }\n }\n const finalLow = Math.max(Math.min(low, high, values.length - 1), 0);\n const finalHigh = Math.min(Math.max(low, high, 0), values.length - 1);\n return { low: finalLow, high: finalHigh, match };\n}\nexports.binarySearch = binarySearch;\n//# sourceMappingURL=binarySearch.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.translateOffset = void 0;\nfunction translateOffset(start, fromOffsets, toOffsets, lengths) {\n for (let i = 0; i < fromOffsets.length; i++) {\n const fromOffset = fromOffsets[i];\n const toOffset = toOffsets[i];\n const length = lengths[i];\n if (start >= fromOffset && start <= fromOffset + length) {\n return toOffset + start - fromOffset;\n }\n }\n}\nexports.translateOffset = translateOffset;\n//# sourceMappingURL=translateOffset.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SourceMap = void 0;\nconst binarySearch_1 = require(\"./binarySearch\");\nconst translateOffset_1 = require(\"./translateOffset\");\nclass SourceMap {\n constructor(mappings) {\n this.mappings = mappings;\n }\n getSourceOffset(generatedOffset) {\n for (const mapped of this.findMatching(generatedOffset, 'generatedOffsets', 'sourceOffsets')) {\n return mapped;\n }\n }\n getGeneratedOffset(sourceOffset) {\n for (const mapped of this.findMatching(sourceOffset, 'sourceOffsets', 'generatedOffsets')) {\n return mapped;\n }\n }\n getSourceOffsets(generatedOffset) {\n return this.findMatching(generatedOffset, 'generatedOffsets', 'sourceOffsets');\n }\n getGeneratedOffsets(sourceOffset) {\n return this.findMatching(sourceOffset, 'sourceOffsets', 'generatedOffsets');\n }\n *findMatching(offset, fromRange, toRange) {\n const memo = this.getMemoBasedOnRange(fromRange);\n if (memo.offsets.length === 0) {\n return;\n }\n const { low: start, high: end } = (0, binarySearch_1.binarySearch)(memo.offsets, offset);\n const skip = new Set();\n for (let i = start; i <= end; i++) {\n for (const mapping of memo.mappings[i]) {\n if (skip.has(mapping)) {\n continue;\n }\n skip.add(mapping);\n const mapped = (0, translateOffset_1.translateOffset)(offset, mapping[fromRange], mapping[toRange], mapping.lengths);\n if (mapped !== undefined) {\n yield [mapped, mapping];\n }\n }\n }\n }\n getMemoBasedOnRange(fromRange) {\n return fromRange === 'sourceOffsets'\n ? this.sourceCodeOffsetsMemo ??= this.createMemo('sourceOffsets')\n : this.generatedCodeOffsetsMemo ??= this.createMemo('generatedOffsets');\n }\n createMemo(key) {\n const offsetsSet = new Set();\n for (const mapping of this.mappings) {\n for (let i = 0; i < mapping[key].length; i++) {\n offsetsSet.add(mapping[key][i]);\n offsetsSet.add(mapping[key][i] + mapping.lengths[i]);\n }\n }\n const offsets = [...offsetsSet].sort((a, b) => a - b);\n const mappings = offsets.map(() => new Set());\n for (const mapping of this.mappings) {\n for (let i = 0; i < mapping[key].length; i++) {\n const startIndex = (0, binarySearch_1.binarySearch)(offsets, mapping[key][i]).match;\n const endIndex = (0, binarySearch_1.binarySearch)(offsets, mapping[key][i] + mapping.lengths[i]).match;\n for (let i = startIndex; i <= endIndex; i++) {\n mappings[i].add(mapping);\n }\n }\n }\n return { offsets, mappings };\n }\n}\nexports.SourceMap = SourceMap;\n//# sourceMappingURL=sourceMap.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.buildMappings = void 0;\nfunction buildMappings(chunks) {\n let length = 0;\n const mappings = [];\n for (const segment of chunks) {\n if (typeof segment === 'string') {\n length += segment.length;\n }\n else {\n mappings.push({\n source: segment[1],\n sourceOffsets: [segment[2]],\n generatedOffsets: [length],\n lengths: [segment[0].length],\n data: segment[3],\n });\n length += segment[0].length;\n }\n }\n return mappings;\n}\nexports.buildMappings = buildMappings;\n//# sourceMappingURL=buildMappings.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.buildStacks = void 0;\nfunction buildStacks(chunks, stacks) {\n let offset = 0;\n let index = 0;\n const result = [];\n for (const stack of stacks) {\n const start = offset;\n for (let i = 0; i < stack.length; i++) {\n const segment = chunks[index + i];\n if (typeof segment === 'string') {\n offset += segment.length;\n }\n else {\n offset += segment[0].length;\n }\n }\n index += stack.length;\n result.push({\n source: stack.stack,\n range: [start, offset],\n });\n }\n return result;\n}\nexports.buildStacks = buildStacks;\n//# sourceMappingURL=buildStacks.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"muggle-string\"), exports);\n__exportStar(require(\"./lib/sourceMap\"), exports);\n__exportStar(require(\"./lib/translateOffset\"), exports);\n__exportStar(require(\"./lib/buildMappings\"), exports);\n__exportStar(require(\"./lib/buildStacks\"), exports);\n//# sourceMappingURL=index.js.map","import type ts from 'typescript';\nimport { SourceMap } from '@volar/source-map';\nimport type { Mapping } from '@volar/source-map';\n\nexport type VirtualMap = Map<string, SourceMappedFile>;\nexport type { Mapping };\n\nexport interface FileSpan extends ts.TextSpan {\n fileName: string;\n}\n\nexport class SourceMappedFile extends SourceMap {\n readonly sourceFile: ts.SourceFile;\n readonly sourceFileId: string;\n readonly generatedFileId: string;\n\n constructor(\n mappings: readonly Mapping[],\n params: {\n sourceFile: ts.SourceFile;\n sourceFileId: string;\n generatedFileId: string;\n }\n ) {\n super(mappings as Mapping[]);\n this.sourceFile = params.sourceFile;\n this.sourceFileId = params.sourceFileId;\n this.generatedFileId = params.generatedFileId;\n }\n\n getSourceSpan(span: ts.TextSpan | number): FileSpan {\n const sourceStart = this.getSourceOffset(typeof span === 'number' ? span : span.start);\n if (sourceStart != null) {\n const sourceEnd =\n typeof span !== 'number' ? this.getSourceOffset(span.start + span.length - 1) : null;\n return {\n fileName: this.sourceFileId,\n start: sourceStart[0],\n length:\n sourceEnd != null\n ? sourceEnd[0] - sourceStart[0] + 1\n : typeof span !== 'number'\n ? span.length\n : 1,\n };\n } else {\n return {\n fileName: this.generatedFileId,\n start: typeof span !== 'number' ? span.start : span,\n length: typeof span !== 'number' ? span.length : 1,\n };\n }\n }\n}\n","import ts from 'typescript';\nimport * as path from 'node:path';\nimport type { GraphQLSPConfig } from '@gql.tada/internal';\nimport { createVirtualLanguageServiceHost } from './vendor/typescript-vfs';\n\nimport type { VirtualMap, SourceMappedFile, FileSpan } from './mapping';\n\nimport type { SourcePosition } from './utils';\nimport { spanToFilePosition } from './utils';\n\nfunction maybeBind<T extends Function>(that: object, fn: T): T;\nfunction maybeBind(that: object, fn: undefined): undefined;\nfunction maybeBind<T extends Function>(that: object, fn: T | undefined): T | undefined {\n return fn ? (fn.bind(that) as T) : undefined;\n}\n\nexport interface PluginCreateInfo<Config extends {} = GraphQLSPConfig>\n extends ts.server.PluginCreateInfo {\n config: Config;\n}\n\nexport interface ProgramContainer {\n readonly program: ts.Program;\n readonly languageService: ts.LanguageService;\n buildPluginInfo<Config extends {}>(config: Config): PluginCreateInfo<Config>;\n\n getSourceFile(fileId: string): ts.SourceFile | undefined;\n getSourceFiles(): readonly ts.SourceFile[];\n getSourceMappedFile(fileId: string | ts.SourceFile): SourceMappedFile | undefined;\n getSourceSpan(fileId: string | ts.SourceFile, span: ts.TextSpan | number): FileSpan;\n getSourcePosition(fileId: string | ts.SourceFile, span: ts.TextSpan | number): SourcePosition;\n}\n\nexport interface ContainerParams {\n virtualMap: VirtualMap;\n projectRoot: string;\n compilerHost: ts.CompilerHost;\n rootNames: readonly string[];\n options: ts.CompilerOptions;\n system: ts.System;\n documentRegistry?: ts.DocumentRegistry;\n}\n\nexport const buildContainer = (params: ContainerParams): ProgramContainer => {\n let program: ts.Program | undefined;\n let service: ts.LanguageService | undefined;\n let serviceHost: ts.LanguageServiceHost | undefined;\n let pluginInfo: PluginCreateInfo<any> | undefined;\n\n const getLanguageServiceHost = () =>\n serviceHost ||\n (serviceHost = createVirtualLanguageServiceHost(\n params.system,\n [...params.rootNames],\n params.options,\n ts\n ).languageServiceHost);\n\n const getLanguageService = () =>\n service ||\n (service = buildLanguageService({\n system: params.system,\n rootNames: params.rootNames,\n virtualMap: params.virtualMap,\n options: params.options,\n projectRoot: params.projectRoot,\n languageServiceHost: getLanguageServiceHost(),\n documentRegistry: params.documentRegistry,\n }));\n\n const getProgram = () => {\n if (!program) {\n program =\n getLanguageService().getProgram() ||\n ts.createProgram({\n rootNames: params.rootNames,\n options: params.options,\n host: params.compilerHost,\n });\n }\n return program;\n };\n\n return {\n get program() {\n return getProgram();\n },\n get languageService() {\n return getLanguageService();\n },\n buildPluginInfo(config) {\n return (\n pluginInfo ||\n (pluginInfo = buildPluginInfo({\n getLanguageService,\n getLanguageServiceHost,\n projectRoot: params.projectRoot,\n rootNames: params.rootNames,\n system: params.system,\n options: params.options,\n config,\n }))\n );\n },\n\n getSourceFile(fileId) {\n return getProgram().getSourceFile(fileId);\n },\n getSourceFiles() {\n return getProgram().getSourceFiles();\n },\n getSourceMappedFile(file) {\n const fileId = typeof file !== 'string' ? file.fileName : file;\n return params.virtualMap.get(fileId);\n },\n getSourceSpan(file, span) {\n const fileId = typeof file !== 'string' ? file.fileName : file;\n const mappedFile = params.virtualMap.get(fileId);\n return mappedFile\n ? mappedFile.getSourceSpan(span)\n : {\n fileName: fileId,\n start: typeof span !== 'number' ? span.start : span,\n length: typeof span !== 'number' ? span.length : 1,\n };\n },\n getSourcePosition(file, position) {\n const fileId = typeof file !== 'string' ? file.fileName : file;\n const mappedFile = params.virtualMap.get(fileId);\n if (mappedFile) {\n const span = mappedFile.getSourceSpan(position);\n if (span.fileName === mappedFile.sourceFileId)\n return spanToFilePosition(mappedFile.sourceFile, span);\n }\n return spanToFilePosition(\n typeof file === 'string' ? getProgram().getSourceFile(file)! : file,\n position\n );\n },\n };\n};\n\nconst buildProgram = (params: {\n program: ts.Program;\n virtualMap: VirtualMap;\n projectRoot: string;\n}): ts.Program => {\n const { program, virtualMap, projectRoot } = params;\n\n const isSourceFileFromExternalLibrary = maybeBind(\n program,\n program.isSourceFileFromExternalLibrary\n );\n const getModeForResolutionAtIndex = maybeBind(program, program.getModeForResolutionAtIndex);\n const getSourceFile = maybeBind(program, program.getSourceFile);\n const getSourceFiles = maybeBind(program, program.getSourceFiles);\n\n /** Remap source file to generated source file if it's a mapped file */\n const mapSourceFileFn =\n <TReturn, TArgs extends readonly any[]>(\n fileFn: (file: ts.SourceFile, ...args: TArgs) => TReturn\n ) =>\n (file: ts.SourceFile | undefined, ...args: TArgs): TReturn => {\n const mappedFile = file && virtualMap.get(file.fileName);\n if (mappedFile && mappedFile.sourceFileId === file?.fileName)\n file = getSourceFile(mappedFile.generatedFileId) || file;\n return fileFn.call(program, file!, ...args);\n };\n\n return Object.assign(program, {\n getSyntacticDiagnostics: mapSourceFileFn(program.getSyntacticDiagnostics),\n getSemanticDiagnostics: mapSourceFileFn(program.getSemanticDiagnostics),\n getDeclarationDiagnostics: mapSourceFileFn(program.getDeclarationDiagnostics),\n isSourceFileDefaultLibrary: mapSourceFileFn(program.isSourceFileDefaultLibrary),\n getModeForUsageLocation: mapSourceFileFn(program.getModeForUsageLocation),\n\n isSourceFileFromExternalLibrary(source) {\n const mappedFile = virtualMap.get(source.fileName);\n return (\n !!(mappedFile && mappedFile.sourceFileId === source.fileName) ||\n isSourceFileFromExternalLibrary(source)\n );\n },\n\n getSourceFiles() {\n const sourceFiles: ts.SourceFile[] = [];\n for (const sourceFile of getSourceFiles()) {\n const relativePath = path.relative(projectRoot, sourceFile.fileName);\n if (\n !relativePath.startsWith('..') &&\n !program.isSourceFileFromExternalLibrary(sourceFile)\n ) {\n sourceFiles.push(sourceFile);\n }\n }\n return sourceFiles;\n },\n\n getSourceFile(fileId) {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) fileId = mappedFile.generatedFileId;\n return getSourceFile(fileId);\n },\n\n getModeForResolutionAtIndex(file, index) {\n const mappedFile = virtualMap.get(file.fileName);\n if (mappedFile && mappedFile.sourceFileId === file.fileName) {\n file = getSourceFile(mappedFile.generatedFileId) || file;\n index = mappedFile.getGeneratedOffset(index)?.[0] ?? index;\n }\n return getModeForResolutionAtIndex(file, index);\n },\n } satisfies Partial<ts.Program>);\n};\n\nconst buildLanguageService = (params: {\n virtualMap: VirtualMap;\n languageServiceHost: ts.LanguageServiceHost;\n system: ts.System;\n rootNames: readonly string[];\n projectRoot: string;\n options: ts.CompilerOptions;\n documentRegistry?: ts.DocumentRegistry;\n}): ts.LanguageService => {\n const { virtualMap } = params;\n const languageService = ts.createLanguageService(\n params.languageServiceHost,\n params.documentRegistry\n );\n const getProgram = maybeBind(languageService, languageService.getProgram);\n\n /** Remap filename to generated file if it's a mapped file */\n const mapFileFn =\n <TReturn, TArgs extends readonly any[]>(fileFn: (fileId: string, ...args: TArgs) => TReturn) =>\n (fileId: string, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) fileId = mappedFile.generatedFileId;\n return fileFn.call(languageService, fileId, ...args);\n };\n\n /** Remap input to generated file and span if it's a mapped file */\n const mapFileTextSpanFn =\n <TReturn, TArgs extends readonly any[]>(\n textSpanFn: (fileId: string, span: ts.TextSpan, ...args: TArgs) => TReturn\n ) =>\n (fileId: string, span: ts.TextSpan, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) {\n fileId = mappedFile.generatedFileId;\n const start = mappedFile.getGeneratedOffset(span.start)?.[0];\n const end = mappedFile.getGeneratedOffset(span.start + span.length - 1)?.[0];\n if (start != null) {\n span = { start, length: span.length };\n if (end != null) span.length = end - start + 1;\n }\n }\n return textSpanFn.call(languageService, fileId, span, ...args);\n };\n\n /** Remap input to generated file and range if it's a mapped file */\n const mapFileTextRangeFn =\n <TReturn, TArgs extends readonly any[]>(\n textSpanFn: (fileId: string, range: ts.TextRange, ...args: TArgs) => TReturn\n ) =>\n (fileId: string, range: ts.TextRange, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) {\n fileId = mappedFile.generatedFileId;\n const pos = mappedFile.getGeneratedOffset(range.pos)?.[0];\n const end = mappedFile.getGeneratedOffset(range.end)?.[0];\n if (pos != null) {\n range = { pos, end: pos + (range.end - range.pos) };\n if (end != null) range.end = end;\n }\n }\n return textSpanFn.call(languageService, fileId, range, ...args);\n };\n\n /** Remap input to generated file and position if it's a mapped file */\n const mapFilePositionFn =\n <TReturn, TArgs extends readonly any[]>(\n positionFn: (fileId: string, position: number, ...args: TArgs) => TReturn\n ) =>\n (fileId: string, position: number, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) {\n fileId = mappedFile.generatedFileId;\n position = mappedFile.getGeneratedOffset(position)?.[0] ?? position;\n }\n return positionFn.call(languageService, fileId, position, ...args);\n };\n\n /** Remap input to generated file and position if it's a mapped file */\n const mapFileStartEndFn =\n <TReturn, TArgs extends readonly any[]>(\n positionFn: (fileId: string, start: number, end: number, ...args: TArgs) => TReturn\n ) =>\n (fileId: string, start: number, end: number, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) {\n fileId = mappedFile.generatedFileId;\n start = mappedFile.getGeneratedOffset(start)?.[0] ?? start;\n end = mappedFile.getGeneratedOffset(end)?.[0] ?? end;\n }\n return positionFn.call(languageService, fileId, start, end, ...args);\n };\n\n let program: ts.Program | undefined;\n\n return Object.assign(languageService, {\n getProgram() {\n if (program) {\n return program;\n } else {\n const serviceProgram = getProgram();\n return serviceProgram\n ? (program = buildProgram({\n program: serviceProgram,\n virtualMap: params.virtualMap,\n projectRoot: params.projectRoot,\n }))\n : undefined;\n }\n },\n\n getReferencesAtPosition: mapFilePositionFn(languageService.getReferencesAtPosition),\n findReferences: mapFilePositionFn(languageService.findReferences),\n getDefinitionAtPosition: mapFilePositionFn(languageService.getDefinitionAtPosition),\n getDefinitionAndBoundSpan: mapFilePositionFn(languageService.getDefinitionAndBoundSpan),\n getTypeDefinitionAtPosition: mapFilePositionFn(languageService.getTypeDefinitionAtPosition),\n getImplementationAtPosition: mapFilePositionFn(languageService.getImplementationAtPosition),\n getCompletionsAtPosition: mapFilePositionFn(languageService.getCompletionsAtPosition),\n getCompletionEntryDetails: mapFilePositionFn(languageService.getCompletionEntryDetails),\n getCompletionEntrySymbol: mapFilePositionFn(languageService.getCompletionEntrySymbol),\n getQuickInfoAtPosition: mapFilePositionFn(languageService.getQuickInfoAtPosition),\n getBreakpointStatementAtPosition: mapFilePositionFn(\n languageService.getBreakpointStatementAtPosition\n ),\n getSignatureHelpItems: mapFilePositionFn(languageService.getSignatureHelpItems),\n getRenameInfo: mapFilePositionFn(languageService.getRenameInfo),\n getSmartSelectionRange: mapFilePositionFn(languageService.getSmartSelectionRange),\n getDocumentHighlights: mapFilePositionFn(languageService.getDocumentHighlights),\n prepareCallHierarchy: mapFilePositionFn(languageService.prepareCallHierarchy),\n provideCallHierarchyIncomingCalls: mapFilePositionFn(\n languageService.provideCallHierarchyIncomingCalls\n ),\n provideCallHierarchyOutgoingCalls: mapFilePositionFn(\n languageService.provideCallHierarchyOutgoingCalls\n ),\n getBraceMatchingAtPosition: mapFilePositionFn(languageService.getBraceMatchingAtPosition),\n getIndentationAtPosition: mapFilePositionFn(languageService.getIndentationAtPosition),\n getFormattingEditsAfterKeystroke: mapFilePositionFn(\n languageService.getFormattingEditsAfterKeystroke\n ),\n getDocCommentTemplateAtPosition: mapFilePositionFn(\n languageService.getDocCommentTemplateAtPosition\n ),\n isValidBraceCompletionAtPosition: mapFilePositionFn(\n languageService.isValidBraceCompletionAtPosition\n ),\n getJsxClosingTagAtPosition: mapFilePositionFn(languageService.getJsxClosingTagAtPosition),\n getLinkedEditingRangeAtPosition: mapFilePositionFn(\n languageService.getLinkedEditingRangeAtPosition\n ),\n getSpanOfEnclosingComment: mapFilePositionFn(languageService.getSpanOfEnclosingComment),\n\n getSyntacticClassifications: mapFileTextSpanFn(\n languageService.getSyntacticClassifications\n ) as typeof languageService.getSyntacticClassifications,\n getSemanticClassifications: mapFileTextSpanFn(\n languageService.getSemanticClassifications\n ) as typeof languageService.getSemanticClassifications,\n getEncodedSyntacticClassifications: mapFileTextSpanFn(\n languageService.getEncodedSyntacticClassifications\n ),\n getEncodedSemanticClassifications: mapFileTextSpanFn(\n languageService.getEncodedSemanticClassifications\n ),\n provideInlayHints: mapFileTextSpanFn(languageService.provideInlayHints),\n\n getNameOrDottedNameSpan: mapFileStartEndFn(languageService.getNameOrDottedNameSpan),\n getFormattingEditsForRange: mapFileStartEndFn(languageService.getFormattingEditsForRange),\n getCodeFixesAtPosition: mapFileStartEndFn(languageService.getCodeFixesAtPosition),\n\n getFileReferences: mapFileFn(languageService.getFileReferences),\n getNavigationBarItems: mapFileFn(languageService.getNavigationBarItems),\n getNavigationTree: mapFileFn(languageService.getNavigationTree),\n getOutliningSpans: mapFileFn(languageService.getOutliningSpans),\n getTodoComments: mapFileFn(languageService.getTodoComments),\n getFormattingEditsForDocument: mapFileFn(languageService.getFormattingEditsForDocument),\n getEditsForRefactor: mapFileFn(languageService.getEditsForRefactor),\n getEmitOutput: mapFileFn(languageService.getEmitOutput),\n getSuggestionDiagnostics: mapFileFn(languageService.getSuggestionDiagnostics),\n getSemanticDiagnostics: mapFileFn(languageService.getSemanticDiagnostics),\n getSyntacticDiagnostics: mapFileFn(languageService.getSyntacticDiagnostics),\n getSupportedCodeFixes: mapFileFn(languageService.getSupportedCodeFixes),\n\n toggleLineComment: mapFileTextRangeFn(languageService.toggleLineComment),\n toggleMultilineComment: mapFileTextRangeFn(languageService.toggleMultilineComment),\n commentSelection: mapFileTextRangeFn(languageService.commentSelection),\n uncommentSelection: mapFileTextRangeFn(languageService.uncommentSelection),\n } satisfies Partial<ts.LanguageService>);\n};\n\nconst buildPluginInfo = <Config extends {}>(params: {\n config: Config;\n projectRoot: string;\n getLanguageService(): ts.LanguageService;\n getLanguageServiceHost(): ts.LanguageServiceHost;\n system: ts.System;\n rootNames: readonly string[];\n options: ts.CompilerOptions;\n}): PluginCreateInfo<Config> => {\n let languageServiceHost: ts.LanguageServiceHost | undefined;\n return {\n config: params.config,\n\n get languageService() {\n return params.getLanguageService();\n },\n\n get languageServiceHost() {\n return (\n languageServiceHost ||\n (languageServiceHost = createVirtualLanguageServiceHost(\n params.system,\n [...params.rootNames],\n params.options,\n ts\n ).languageServiceHost)\n );\n },\n\n // NOTE: this is an inexact and incomplete implementation\n project: {\n getProjectName: () => params.projectRoot,\n projectService: { logger: console } as any,\n } as PluginCreateInfo['project'],\n\n // NOTE: this is an inexact and incomplete implementation\n serverHost: {\n ...params.system,\n setImmediate,\n clearImmediate,\n } as PluginCreateInfo['serverHost'],\n };\n};\n","import type ts from 'typescript';\nimport * as path from 'node:path';\n\nimport { TadaError, TadaErrorCode } from '../utils/error';\n\nlet _svelte: typeof import('@gql.tada/svelte-support');\nlet _vue: typeof import('@gql.tada/vue-support');\n\nconst transformSvelte = async (\n ...args: Parameters<typeof _svelte.transform>\n): Promise<ReturnType<typeof _svelte.transform>> => {\n if (!_svelte) {\n try {\n _svelte = await import('@gql.tada/svelte-support');\n } catch (_error) {\n throw new TadaError(\n TadaErrorCode.SVELTE_SUPPORT,\n 'For Svelte support the `@gql.tada/svelte-support` package must be installed.\\n' +\n 'Install the package and try again.'\n );\n }\n }\n return _svelte.transform(...args);\n};\n\nconst transformVue = async (\n ...args: Parameters<typeof _vue.transform>\n): Promise<ReturnType<typeof _vue.transform>> => {\n if (!_vue) {\n try {\n _vue = await import('@gql.tada/vue-support');\n } catch (_error) {\n throw new TadaError(\n TadaErrorCode.VUE_SUPPORT,\n 'For Vue support the `@gql.tada/vue-support` package must be installed.\\n' +\n 'Install the package and try again.'\n );\n }\n }\n return _vue.transform(...args);\n};\n\nconst checkVue = async (): Promise<void> => {\n if (!_vue) {\n try {\n _vue = await import('@gql.tada/vue-support');\n } catch (_error) {\n throw new TadaError(\n TadaErrorCode.VUE_SUPPORT,\n 'For Vue support the `@gql.tada/vue-support` package must be installed.\\n' +\n 'Install the package and try again.'\n );\n }\n }\n return _vue.check();\n};\n\nexport const transformExtensions = ['.svelte', '.vue'] as const;\n\nexport const transform = async (sourceFile: ts.SourceFile) => {\n const extname = path.extname(sourceFile.fileName);\n if (extname === '.svelte') {\n return transformSvelte(sourceFile);\n } else if (extname === '.vue') {\n await checkVue();\n return transformVue(sourceFile);\n } else {\n throw new TadaError(\n TadaErrorCode.UNKNOWN_EXTERNAL_FILE,\n `Tried transforming unknown file type \"${extname}\". Supported: ${transformExtensions.join(\n ', '\n )}`\n );\n }\n};\n","import ts from 'typescript';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { init } from '@0no-co/graphqlsp/api';\n\nimport { createFSBackedSystem, createVirtualCompilerHost } from './vendor/typescript-vfs';\n\nimport type { VirtualMap, Mapping } from './mapping';\nimport type { ProgramContainer } from './container';\nimport { SourceMappedFile } from './mapping';\nimport { buildContainer } from './container';\nimport { transform, transformExtensions } from './transformers';\n\nexport type VirtualExtension = (typeof transformExtensions)[number];\n\nexport interface ProgramFactoryParams {\n rootPath: string;\n tsconfigPath?: string;\n configPath: string;\n}\n\nexport interface SourceFileParams {\n fileId: string;\n sourceText: string | ts.IScriptSnapshot;\n scriptKind?: ts.ScriptKind;\n}\n\nexport interface MappedFileParams {\n fileId: string;\n mappings: readonly Mapping[];\n}\n\nexport interface ProgramFactory {\n readonly projectPath: string;\n readonly wasOriginallyNodeNext: boolean;\n readonly projectDirectories: readonly string[];\n readonly rootFileNames: readonly string[];\n\n createSourceFile(params: SourceFileParams, scriptKind?: ts.ScriptKind): ts.SourceFile;\n createExternalFiles(exts?: readonly VirtualExtension[]): readonly ts.SourceFile[];\n\n addSourceFile(file: SourceFileParams | ts.SourceFile): this;\n addMappedFile(file: SourceFileParams | ts.SourceFile, params: MappedFileParams): this;\n\n addVirtualFiles(files: readonly ts.SourceFile[]): Promise<this>;\n\n resolveModulePath(importSpecifier: string, fromPath: string): string | undefined;\n resolveModuleName(importSpecifier: string, fromPath: string, toPath: string): string;\n\n build(): ProgramContainer;\n}\n\n/** Bumps the Error stack traces to a length of 25 for better debugging. */\nconst bumpStackTraceLimit = () => {\n if ('stackTraceLimit' in Error && Error.stackTraceLimit < 25) {\n Error.stackTraceLimit = 25;\n }\n};\n\nexport const programFactory = (params: ProgramFactoryParams): ProgramFactory => {\n const vfsMap = new Map<string, string>();\n const virtualMap: VirtualMap = new Map();\n\n const system = createFSBackedSystem(vfsMap, params.rootPath, ts, resolveDefaultLibsPath(params));\n const config = resolveConfig(params);\n\n const rootNames = new Set(config.fileNames);\n const options: ts.CompilerOptions = {\n ...ts.getDefaultCompilerOptions(),\n getDefaultLibFilePath: ts.getDefaultLibFilePath(config.options),\n noCheck: true,\n ...config.options,\n };\n\n let orignallyNodeNext = false;\n // NOTE: Using \"NodeNext\" instead of \"Bundler\" is almost always a mistake\n // this should be revisited in the next major version.\n if (\n 'Bundler' in ts.ModuleResolutionKind &&\n (options.moduleResolution === ts.ModuleResolutionKind.NodeNext ||\n options.moduleResolution === ts.ModuleResolutionKind.Node16)\n ) {\n orignallyNodeNext = true;\n options.moduleResolution = ts.ModuleResolutionKind.Bundler;\n }\n\n const host = createVirtualCompilerHost(system, options, ts);\n const documentRegistry = ts.createDocumentRegistry();\n\n const factory: ProgramFactory = {\n get projectPath() {\n return params.rootPath;\n },\n\n get wasOriginallyNodeNext() {\n return orignallyNodeNext;\n },\n\n get projectDirectories() {\n const directories = new Set([params.rootPath]);\n for (const rootName of rootNames) directories.add(path.dirname(rootName));\n return [...directories];\n },\n\n get rootFileNames() {\n return [...rootNames];\n },\n\n createSourceFile(params, scriptKind) {\n return ts.createSourceFile(\n params.fileId,\n typeof params.sourceText === 'object'\n ? params.sourceText.getText(0, params.sourceText.getLength())\n : params.sourceText,\n options.target || ts.ScriptTarget.ESNext,\n /*setParentNodes*/ true,\n scriptKind || (params.scriptKind != null ? params.scriptKind : ts.ScriptKind.TSX)\n );\n },\n\n createExternalFiles(exts: readonly VirtualExtension[] = transformExtensions) {\n const files: ts.SourceFile[] = [];\n const seen = new Set(rootNames);\n const directories = new Set([params.rootPath]);\n for (const rootName of rootNames) directories.add(path.dirname(rootName));\n for (const directory of directories) {\n for (const fileId of system.readDirectory(directory, exts, ['**/node_modules'])) {\n if (!seen.has(fileId)) {\n seen.add(fileId);\n const contents = system.readFile(fileId, 'utf8');\n if (contents) {\n files.push(\n factory.createSourceFile(\n {\n fileId,\n sourceText: contents,\n },\n ts.ScriptKind.External\n )\n );\n }\n }\n }\n }\n return files;\n },\n\n addSourceFile(input) {\n const sourceFile =\n 'fileName' in input ? input : factory.createSourceFile(input, ts.ScriptKind.TSX);\n host.updateFile(sourceFile);\n rootNames.add(sourceFile.fileName);\n return factory;\n },\n\n addMappedFile(input, params) {\n const sourceFile =\n 'fileName' in input ? input : factory.createSourceFile(input, ts.ScriptKind.External);\n if (params.mappings.length) rootNames.delete(sourceFile.fileName);\n const sourceMappedFile = new SourceMappedFile(params.mappings, {\n sourceFile,\n sourceFileId: sourceFile.fileName,\n generatedFileId: params.fileId,\n });\n virtualMap.set(sourceMappedFile.sourceFileId, sourceMappedFile);\n virtualMap.set(sourceMappedFile.generatedFileId, sourceMappedFile);\n return factory;\n },\n\n async addVirtualFiles(sourceFiles) {\n for (const sourceFile of sourceFiles) {\n const virtualFileId = `${sourceFile.fileName}.ts`;\n const virtualCode = await transform(sourceFile);\n if (virtualCode) {\n factory\n .addSourceFile({\n fileId: virtualFileId,\n sourceText: virtualCode.snapshot,\n })\n .addMappedFile(sourceFile, {\n mappings: virtualCode.mappings,\n fileId: virtualFileId,\n });\n }\n }\n return factory;\n },\n\n resolveModulePath(importSpecifier: string, fromPath: string): string | undefined {\n const resolved = ts.resolveModuleName(importSpecifier, fromPath, options, host.compilerHost);\n\n return resolved.resolvedModule?.resolvedFileName;\n },\n\n resolveModuleName(importSpecifier: string, fromPath: string, toPath: string): string {\n // For absolute imports (including path-mapped ones), keep them as-is\n // TypeScript's module resolution will handle them correctly\n if (!importSpecifier.startsWith('.')) {\n return importSpecifier;\n }\n\n // For relative imports, we need to adjust the path using the virtual compiler host\n // First, resolve the import from the original location to get the actual file\n const resolvedFileName = factory.resolveModulePath(importSpecifier, fromPath);\n\n if (resolvedFileName) {\n // Now create a relative path from the new location (toPath) to the target\n const fromDir = path.dirname(toPath);\n let relativePath = path.relative(fromDir, resolvedFileName);\n\n // Ensure it starts with ./ or ../\n if (!relativePath.startsWith('.')) {\n relativePath = './' + relativePath;\n }\n\n // Convert Windows backslashes to forward slashes for imports\n return relativePath.replace(/\\\\/g, '/');\n }\n\n // Fallback to simple path resolution if TypeScript resolution fails\n const fromDir = path.dirname(fromPath);\n const toDir = path.dirname(toPath);\n\n const absoluteImportPath = path.resolve(fromDir, importSpecifier);\n let relativeImportPath = path.relative(toDir, absoluteImportPath);\n\n // Ensure it starts with ./ if it's a relative path\n if (!relativeImportPath.startsWith('.')) {\n relativeImportPath = './' + relativeImportPath;\n }\n\n // Convert Windows backslashes to forward slashes for imports\n return relativeImportPath.replace(/\\\\/g, '/');\n },\n\n build() {\n bumpStackTraceLimit();\n\n // NOTE: This is necessary for `@0no-co/graphqlsp/api` to use the right instance\n // of the typescript library\n init({ typescript: ts });\n\n return buildContainer({\n virtualMap,\n projectRoot: params.rootPath,\n compilerHost: host.compilerHost,\n rootNames: [...rootNames],\n options,\n system,\n documentRegistry,\n });\n },\n };\n\n return factory;\n};\n\nconst resolveDefaultLibsPath = (params: ProgramFactoryParams): string => {\n const target = ts.getDefaultLibFilePath({});\n if (!ts.sys.fileExists(target)) {\n const require = createRequire(params.configPath);\n const request = 'typescript/package.json';\n try {\n return path.dirname(\n require.resolve(request, {\n paths: [\n path.join(path.dirname(params.configPath), 'node_modules'),\n path.join(params.rootPath, 'node_modules'),\n ...(require.resolve.paths(request) || []),\n ],\n })\n );\n } catch (_error) {\n return path.resolve(params.rootPath, 'node_modules', 'typescript', 'lib');\n }\n } else {\n return path.dirname(target);\n }\n};\n\nconst resolveConfig = (params: ProgramFactoryParams): ts.ParsedCommandLine => {\n const configPath = params.tsconfigPath || params.configPath;\n const text = ts.sys.readFile(configPath, 'utf8') || '{}';\n const parseResult = ts.parseConfigFileTextToJson(configPath, text);\n if (parseResult.error != null) throw new Error(parseResult.error.messageText.toString());\n const projectRoot = path.dirname(configPath);\n return ts.parseJsonConfigFileContent(\n parseResult.config,\n ts.sys,\n projectRoot,\n ts.getDefaultCompilerOptions(),\n configPath\n );\n};\n","import * as fs from 'node:fs/promises';\n\nexport const enum FileType {\n File,\n Directory,\n}\n\nexport const stat = async (file: string, type = FileType.File): Promise<boolean> =>\n await fs\n .stat(file)\n .then((stat) => {\n switch (type) {\n case FileType.File:\n return stat.isFile();\n case FileType.Directory:\n return stat.isDirectory();\n }\n })\n .catch(() => false);\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport { stat, FileType } from './fs';\nimport { findWorkspaceRoot } from './workspaceRoot';\n\nconst configFileRe = /^(?:graphql\\.config|\\.graphqlrc)\\.(?:cjs|[jt]s|json|toml|ya?ml)$/i;\n\n/** Loads list of suggested in-repo VSCode extensions */\nexport const findGraphQLConfig = async (targetPath?: string): Promise<string | null> => {\n let target = targetPath || process.cwd();\n const rootPath = path.resolve(target, '/');\n while (target !== rootPath) {\n let dir: readonly string[] = [];\n try {\n dir = await fs.readdir(target);\n } catch (_error) {}\n const configFile = dir.find((item) => configFileRe.test(item));\n if (configFile) return configFile;\n if (await stat(path.resolve(target, '.git'), FileType.Directory)) {\n break;\n } else if (await stat(path.resolve(target, '.vscode'), FileType.Directory)) {\n break;\n }\n target = path.resolve(target, '..');\n }\n\n const workspaceRoot = await findWorkspaceRoot(targetPath);\n if (workspaceRoot) {\n const packageJsonPath = path.resolve(workspaceRoot, 'package.json');\n if (await stat(packageJsonPath)) {\n try {\n const meta = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));\n if (\n meta &&\n typeof meta === 'object' &&\n 'graphql' in meta &&\n meta.graphql &&\n typeof meta.graphql === 'object'\n ) {\n return packageJsonPath;\n }\n } catch (_error) {}\n }\n }\n\n return null;\n};\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { stat, FileType } from './fs';\n\nexport const findWorkspaceRoot = async (targetPath?: string): Promise<string | null> => {\n let target = targetPath || process.cwd();\n const rootPath = path.resolve(target, '/');\n while (target !== rootPath) {\n if (await stat(path.resolve(target, '.git'), FileType.Directory)) {\n return target;\n } else if (await stat(path.resolve(target, '.vscode'), FileType.Directory)) {\n return target;\n } else if (await stat(path.resolve(target, 'pnpm-workspace.yml'))) {\n return target;\n }\n const packageJsonPath = path.resolve(target, 'package.json');\n if (await stat(packageJsonPath)) {\n try {\n const meta = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));\n if (meta && typeof meta === 'object' && Array.isArray(meta.workspaces)) {\n return target;\n }\n } catch (_error) {}\n }\n target = path.resolve(target, '..');\n }\n return null;\n};\n","/**\n * Version resolution utilities with support for workspace catalogs.\n *\n * Supports catalog-based dependency management for:\n * - pnpm (pnpm-workspace.yaml format)\n * - bun (package.json workspaces format)\n *\n * Catalog references follow the format:\n * - \"catalog:\" for default catalog\n * - \"catalog:name\" for named catalogs\n */\n\nimport { createRequire } from 'node:module';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nexport interface PackageJson {\n name?: string;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n}\n\nexport interface WorkspaceConfig {\n packages?: string[];\n catalog?: Record<string, string>;\n catalogs?: Record<string, Record<string, string>>;\n}\n\nexport interface PnpmWorkspaceConfig extends WorkspaceConfig {\n // Inherits from WorkspaceConfig - supports pnpm-workspace.yaml format\n}\n\nexport interface BunWorkspaceConfig extends WorkspaceConfig {\n // Inherits from WorkspaceConfig - supports package.json workspaces format\n}\n\nconst parseYaml = (content: string): PnpmWorkspaceConfig => {\n const lines = content.split('\\n');\n const result: PnpmWorkspaceConfig = {};\n let currentSection: string | null = null;\n let currentCatalog: string | null = null;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n if (trimmed.endsWith(':') && !trimmed.includes(' ')) {\n const key = trimmed.slice(0, -1).replace(/['\"]/g, '');\n if (key === 'packages') {\n currentSection = 'packages';\n result.packages = [];\n } else if (key === 'catalog') {\n currentSection = 'catalog';\n result.catalog = {};\n } else if (key === 'catalogs') {\n currentSection = 'catalogs';\n result.catalogs = {};\n } else if (currentSection === 'catalogs') {\n currentCatalog = key;\n result.catalogs![key] = {};\n }\n } else if (trimmed.startsWith('- ')) {\n if (currentSection === 'packages') {\n result.packages!.push(trimmed.slice(2).replace(/['\"]/g, ''));\n }\n } else if (trimmed.includes(':')) {\n const colonIndex = trimmed.indexOf(':');\n const key = trimmed.slice(0, colonIndex).trim().replace(/['\"]/g, '');\n const value = trimmed\n .slice(colonIndex + 1)\n .trim()\n .replace(/['\"]/g, '');\n\n if (currentSection === 'catalog') {\n result.catalog![key] = value;\n } else if (currentSection === 'catalogs' && currentCatalog) {\n result.catalogs![currentCatalog][key] = value;\n }\n }\n }\n\n return result;\n};\n\nconst findPnpmWorkspaceroot = async (startPath: string = process.cwd()): Promise<string | null> => {\n let currentPath = startPath;\n const root = path.parse(currentPath).root;\n\n while (currentPath !== root) {\n const workspaceFile = path.join(currentPath, 'pnpm-workspace.yaml');\n try {\n await fs.access(workspaceFile);\n return currentPath;\n } catch {\n // File doesn't exist, continue searching\n }\n currentPath = path.dirname(currentPath);\n }\n\n return null;\n};\n\nconst findBunWorkspaceRoot = async (startPath: string = process.cwd()): Promise<string | null> => {\n let currentPath = startPath;\n const root = path.parse(currentPath).root;\n\n while (currentPath !== root) {\n const packageJsonFile = path.join(currentPath, 'package.json');\n try {\n await fs.access(packageJsonFile);\n const content = await fs.readFile(packageJsonFile, 'utf-8');\n const packageJson: PackageJson & { workspaces?: any } = JSON.parse(content);\n\n // Check if this package.json has workspaces with catalog/catalogs\n // Bun stores catalogs in workspaces.catalog and workspaces.catalogs\n if (\n packageJson.workspaces &&\n (packageJson.workspaces.catalog || packageJson.workspaces.catalogs)\n ) {\n return currentPath;\n }\n } catch {\n // File doesn't exist or can't be parsed, continue searching\n }\n currentPath = path.dirname(currentPath);\n }\n\n return null;\n};\n\nconst loadPnpmWorkspaceCatalogs = async (): Promise<PnpmWorkspaceConfig | null> => {\n const workspaceRoot = await findPnpmWorkspaceroot();\n if (!workspaceRoot) return null;\n\n try {\n const workspaceFile = path.join(workspaceRoot, 'pnpm-workspace.yaml');\n const content = await fs.readFile(workspaceFile, 'utf-8');\n return parseYaml(content);\n } catch {\n return null;\n }\n};\n\nconst loadBunWorkspaceCatalogs = async (): Promise<BunWorkspaceConfig | null> => {\n const workspaceRoot = await findBunWorkspaceRoot();\n if (!workspaceRoot) return null;\n\n try {\n const packageJsonFile = path.join(workspaceRoot, 'package.json');\n const content = await fs.readFile(packageJsonFile, 'utf-8');\n const packageJson: PackageJson & { workspaces?: any } = JSON.parse(content);\n\n if (!packageJson.workspaces) return null;\n\n const result: BunWorkspaceConfig = {};\n\n if (packageJson.workspaces.packages) {\n result.packages = packageJson.workspaces.packages;\n }\n\n if (packageJson.workspaces.catalog) {\n result.catalog = packageJson.workspaces.catalog;\n }\n\n if (packageJson.workspaces.catalogs) {\n result.catalogs = packageJson.workspaces.catalogs;\n }\n\n return result;\n } catch {\n return null;\n }\n};\n\nconst loadWorkspaceCatalogs = async (): Promise<WorkspaceConfig | null> => {\n const pnpmCatalogs = await loadPnpmWorkspaceCatalogs();\n if (pnpmCatalogs) return pnpmCatalogs;\n\n const bunCatalogs = await loadBunWorkspaceCatalogs();\n if (bunCatalogs) return bunCatalogs;\n\n return null;\n};\n\nconst resolveCatalogVersion = (catalogRef: string): string | null => {\n if (!catalogRef.startsWith('catalog:')) return null;\n\n const catalogName = catalogRef.slice(8); // Remove 'catalog:' prefix\n\n if (!catalogName || catalogName === 'default') {\n return null; // Will be resolved by package name lookup\n }\n\n return catalogName;\n};\n\nconst getVersionFromCatalog = (\n packageName: string,\n catalogName: string | null,\n catalogs: WorkspaceConfig\n): string | null => {\n if (catalogName) {\n // Named catalog\n return catalogs.catalogs?.[catalogName]?.[packageName] || null;\n } else {\n // Default catalog\n return catalogs.catalog?.[packageName] || null;\n }\n};\n\nconst getPackageVersion = async (\n packageName: string,\n meta: PackageJson\n): Promise<string | null> => {\n const devVersion = meta.devDependencies?.[packageName];\n if (devVersion) {\n if (devVersion.startsWith('catalog:')) {\n const catalogs = await loadWorkspaceCatalogs();\n if (catalogs) {\n const catalogName = resolveCatalogVersion(devVersion);\n const resolvedVersion = getVersionFromCatalog(packageName, catalogName, catalogs);\n if (resolvedVersion) return resolvedVersion;\n }\n } else {\n return devVersion;\n }\n }\n\n const depVersion = meta.dependencies?.[packageName];\n if (depVersion) {\n if (depVersion.startsWith('catalog:')) {\n const catalogs = await loadWorkspaceCatalogs();\n if (catalogs) {\n const catalogName = resolveCatalogVersion(depVersion);\n const resolvedVersion = getVersionFromCatalog(packageName, catalogName, catalogs);\n if (resolvedVersion) return resolvedVersion;\n }\n } else {\n return depVersion;\n }\n }\n\n return null;\n};\n\nexport const readPackageJson = async (): Promise<PackageJson> => {\n const packageJsonPath = path.resolve(process.cwd(), 'package.json');\n const file = path.resolve(packageJsonPath);\n return JSON.parse(await fs.readFile(file, 'utf-8'));\n};\n\nexport const getTypeScriptVersion = async (meta: PackageJson): Promise<string | null> => {\n const pkg = 'typescript';\n\n // Try to get version with catalog support\n const catalogVersion = await getPackageVersion(pkg, meta);\n if (catalogVersion) return catalogVersion;\n\n // Fallback to direct resolution\n try {\n return (await import(pkg)).version || null;\n } catch (_error) {\n return null;\n }\n};\n\nexport const getGraphQLSPVersion = async (meta: PackageJson): Promise<string | null> => {\n const pkg = '@0no-co/graphqlsp';\n\n // Try to get version with catalog support\n const catalogVersion = await getPackageVersion(pkg, meta);\n if (catalogVersion) return catalogVersion;\n\n // Fallback to direct resolution\n try {\n // NOTE: Resolved from current folder, since it's a child dependency\n return createRequire(__dirname)(`${pkg}/package.json`)?.version || null;\n } catch (_error) {\n return null;\n }\n};\n\nexport const getGqlTadaVersion = async (meta: PackageJson): Promise<string | null> => {\n const pkg = 'gql.tada';\n\n // Try to get version with catalog support\n const catalogVersion = await getPackageVersion(pkg, meta);\n if (catalogVersion) return catalogVersion;\n\n // Fallback to direct resolution\n try {\n // NOTE: Resolved from working directory, since it's a parent dependency\n return createRequire(process.cwd())(`${pkg}/package.json`)?.version || null;\n } catch (_error) {\n return null;\n }\n};\n\nconst hasPackageSupport = async (packageName: string, meta: PackageJson): Promise<boolean> => {\n // Check if package is listed in dependencies with catalog support\n const catalogVersion = await getPackageVersion(packageName, meta);\n if (catalogVersion) return true;\n\n // Fallback to direct resolution\n try {\n // NOTE: Resolved from current folder, since it's a child dependency\n return !!createRequire(__dirname)(`${packageName}/package.json`)?.version;\n } catch (_error) {\n return false;\n }\n};\n\nexport const hasSvelteSupport = async (meta: PackageJson): Promise<boolean> => {\n return hasPackageSupport('@gql.tada/svelte-support', meta);\n};\n\nexport const hasVueSupport = async (meta: PackageJson): Promise<boolean> => {\n return hasPackageSupport('@gql.tada/vue-support', meta);\n};\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport ts from 'typescript';\nimport { stat, FileType } from './fs';\n\nconst jsonParse = async (fileName: string): Promise<unknown> => {\n const contents = await fs.readFile(fileName, 'utf8');\n const sourceFile = ts.parseJsonText(fileName, contents);\n return ts.convertToObject(sourceFile, []);\n};\n\nexport const isVSCodeInstalled = async (): Promise<boolean> => {\n if (!process.env.HOME) return false;\n const vscodeFolder = path.resolve(process.env.HOME, '.vscode');\n return !!(await stat(vscodeFolder, FileType.Directory));\n};\n\n/** Loads list of suggested in-repo VSCode extensions */\nexport const loadSuggestedExtensionsList = async (\n targetPath?: string\n): Promise<readonly string[]> => {\n let target = targetPath || process.cwd();\n const rootPath = path.resolve(target, '/');\n while (target !== rootPath) {\n if (await stat(path.resolve(target, '.git'), FileType.Directory)) {\n break;\n } else if (await stat(path.resolve(target, '.vscode'), FileType.Directory)) {\n break;\n }\n target = path.resolve(target, '..');\n }\n const configFile = path.resolve(target, '.vscode', 'extensions.json');\n if (!(await stat(configFile))) return [];\n let json: unknown;\n try {\n json = await jsonParse(configFile);\n } catch (_error) {\n return [];\n }\n if (json && typeof json === 'object' && 'recommendations' in json) {\n return Array.isArray(json.recommendations)\n ? json.recommendations\n .filter((x): x is string => x && typeof x === 'string')\n .map((x) => `${x}`.toLowerCase())\n : [];\n } else {\n return [];\n }\n};\n\n/** Loads list of installed VSCode extensions */\nexport const loadExtensionsList = async (): Promise<readonly string[]> => {\n if (!process.env.HOME) return [];\n const vscodeFolder = path.resolve(process.env.HOME, '.vscode');\n const configFile = path.resolve(vscodeFolder, 'extensions', 'extensions.json');\n if (!(await stat(configFile))) return [];\n let json: unknown;\n try {\n json = await jsonParse(configFile);\n } catch (_error) {\n return [];\n }\n return (Array.isArray(json) ? json : [])\n .map((entry) => {\n if (!entry || typeof entry !== 'object' || !('identifier' in entry)) return null;\n if (!entry.identifier || typeof entry.identifier !== 'object' || !('id' in entry.identifier))\n return null;\n return entry.identifier.id && typeof entry.identifier.id === 'string'\n ? `${entry.identifier.id}`.toLowerCase()\n : null;\n })\n .filter((x): x is string => !!x);\n};\n","import { pipe, interval, map, concat, fromValue } from 'wonka';\n\nimport * as t from '../../term';\nimport { indent } from '../shared/logger';\n\nexport * from '../shared/logger';\n\nexport function console(error: any) {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n error && error instanceof Error ? error.message : `${error}`,\n ]);\n}\n\nexport function emptyLine() {\n return t.text([t.cmd(t.CSI.Style, t.Style.BrightBlack), t.HeavyBox.Vertical, '\\n']);\n}\n\nexport function title(title: string, description?: string) {\n let out = t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n t.HeavyBox.TopLeft,\n ' ',\n t.cmd(t.CSI.Style, [t.Style.Magenta, t.Style.Invert]),\n ` ${title.trim()} `,\n t.cmd(t.CSI.Style, [t.Style.NoInvert]),\n '\\n',\n ]);\n if (description) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n t.HeavyBox.Vertical,\n ` ${description}\\n`,\n ]);\n }\n return out;\n}\n\nexport function completedTask(description: string, isLast = false) {\n return t.text([\n emptyLine(),\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n isLast ? t.HeavyBox.BottomLeft : t.HeavyBox.VerticalRight,\n ' ',\n t.cmd(t.CSI.Style, t.Style.Green),\n t.Icons.TickSwoosh,\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n description,\n '\\n',\n ]);\n}\n\nexport function failedTask(description: string) {\n return t.text([\n emptyLine(),\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n t.HeavyBox.BottomLeft,\n ' ',\n t.cmd(t.CSI.Style, t.Style.BrightRed),\n t.Icons.CrossSwoosh,\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n description,\n '\\n',\n ]);\n}\n\nexport function warningTask(description: string) {\n return t.text([\n emptyLine(),\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n t.HeavyBox.VerticalRight,\n ' ',\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n description,\n '\\n',\n ]);\n}\n\nexport function hintMessage(text: string) {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.VerticalRight} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${t.Icons.Info} `,\n t.cmd(t.CSI.Style, t.Style.Blue),\n indent(\n text,\n t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.Vertical} `,\n t.cmd(t.CSI.Style, t.Style.Blue),\n ])\n ),\n ]);\n}\n\nexport function runningTask(description: string) {\n const frame = (state: number) =>\n t.text([\n emptyLine(),\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.circleSpinner[state % t.circleSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n description.trim(),\n ]);\n return concat([\n fromValue(frame(0)),\n pipe(\n interval(150),\n map((state) => frame(state + 1))\n ),\n ]);\n}\n\nexport function success() {\n return t.text([\n '\\n',\n t.cmd(t.CSI.Style, [t.Style.Green, t.Style.Invert]),\n ' Done ',\n t.cmd(t.CSI.Style, t.Style.NoInvert),\n t.Chars.Space,\n 'You are all set and ready to go.\\n',\n ]);\n}\n\nexport function errorMessage(message: string) {\n return t.error([\n '\\n',\n t.cmd(t.CSI.Style, [t.Style.Red, t.Style.Invert]),\n ` ${t.Icons.Warning} Error `,\n t.cmd(t.CSI.Style, t.Style.NoInvert),\n `\\n${message.trim()}\\n`,\n ]);\n}\n","import type ts from 'typescript';\nimport path from 'node:path';\n\nimport type { LoadConfigResult } from '@gql.tada/internal';\nimport {\n loadRef,\n loadConfigs,\n parseConfig,\n validateUniqueOutputLocations,\n} from '@gql.tada/internal';\n\nimport type { ComposeInput } from '../../term';\nimport type { ProjectContext } from '../shared';\nimport { MINIMUM_VERSIONS, semverComply } from '../../utils/semver';\nimport { programFactory } from '../../ts';\nimport { findGraphQLConfig } from './helpers/graphqlConfig';\nimport * as versions from './helpers/versions';\nimport * as vscode from './helpers/vscode';\nimport * as logger from './logger';\n\n// NOTE: Currently, most tasks in this command complete too quickly\n// We slow them down to make the CLI output easier to follow along to\nconst delay = (ms = 700) => {\n if (process.env.CI) {\n return Promise.resolve();\n } else {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n};\n\nconst enum Messages {\n TITLE = 'Doctor',\n DESCRIPTION = 'Detects problems with your setup',\n CHECK_TS_VERSION = 'Checking TypeScript version',\n CHECK_DEPENDENCIES = 'Checking installed dependencies',\n CHECK_TSCONFIG = 'Checking tsconfig.json',\n CHECK_EXTERNAL_FILES = 'Checking external files support',\n CHECK_VSCODE = 'Checking VSCode setup',\n CHECK_SCHEMA = 'Checking schema',\n}\n\nexport async function* run(): AsyncIterable<ComposeInput> {\n yield logger.title(Messages.TITLE, Messages.DESCRIPTION);\n yield logger.runningTask(Messages.CHECK_TS_VERSION);\n await delay();\n\n // Check TypeScript version\n let packageJson: versions.PackageJson;\n try {\n packageJson = await versions.readPackageJson();\n } catch (_error) {\n yield logger.failedTask(Messages.CHECK_TS_VERSION);\n throw logger.errorMessage(\n `A ${logger.code('package.json')} file was not found in the current working directory.\\n` +\n logger.hint('Try running the doctor command in your workspace folder.')\n );\n }\n\n const typeScriptVersion = await versions.getTypeScriptVersion(packageJson);\n if (!typeScriptVersion) {\n yield logger.failedTask(Messages.CHECK_TS_VERSION);\n throw logger.errorMessage(\n `A version of ${logger.code('typescript')} was not found in your dependencies.\\n` +\n logger.hint(`Is ${logger.code('typescript')} installed in this package?`)\n );\n } else if (!semverComply(typeScriptVersion, MINIMUM_VERSIONS.typescript)) {\n // TypeScript version lower than v4.1 which is when they introduced template lits\n yield logger.failedTask(Messages.CHECK_TS_VERSION);\n throw logger.errorMessage(\n `The version of ${logger.code('typescript')} in your dependencies is out of date.\\n` +\n logger.hint(\n `${logger.code('gql.tada')} requires at least ${logger.bold(MINIMUM_VERSIONS.typescript)}`\n )\n );\n }\n\n yield logger.completedTask(Messages.CHECK_TS_VERSION);\n yield logger.runningTask(Messages.CHECK_DEPENDENCIES);\n await delay();\n\n const supportsEmbeddedLsp = semverComply(\n typeScriptVersion,\n MINIMUM_VERSIONS.typescript_embed_lsp\n );\n if (!supportsEmbeddedLsp) {\n const gqlspVersion = await versions.getGraphQLSPVersion(packageJson);\n if (!gqlspVersion) {\n yield logger.failedTask(Messages.CHECK_DEPENDENCIES);\n throw logger.errorMessage(\n `A version of ${logger.code('@0no-co/graphqlsp')} was not found in your dependencies.\\n` +\n logger.hint(`Is ${logger.code('@0no-co/graphqlsp')} installed?`)\n );\n } else if (!semverComply(gqlspVersion, MINIMUM_VERSIONS.lsp)) {\n yield logger.failedTask(Messages.CHECK_DEPENDENCIES);\n throw logger.errorMessage(\n `The version of ${logger.code(\n '@0no-co/graphqlsp'\n )} in your dependencies is out of date.\\n` +\n logger.hint(\n `${logger.code('gql.tada')} requires at least ${logger.bold(MINIMUM_VERSIONS.lsp)}`\n )\n );\n }\n }\n\n const gqlTadaVersion = await versions.getGqlTadaVersion(packageJson);\n if (!gqlTadaVersion) {\n yield logger.failedTask(Messages.CHECK_DEPENDENCIES);\n throw logger.errorMessage(\n `A version of ${logger.code('gql.tada')} was not found in your dependencies.\\n` +\n logger.hint(`Is ${logger.code('gql.tada')} installed?`)\n );\n } else if (!semverComply(gqlTadaVersion, '1.0.0')) {\n yield logger.failedTask(Messages.CHECK_DEPENDENCIES);\n throw logger.errorMessage(\n `The version of ${logger.code('gql.tada')} in your dependencies is out of date.\\n` +\n logger.hint(\n `It's recommended to upgrade ${logger.code('gql.tada')} to at least ${logger.bold(\n MINIMUM_VERSIONS.lsp\n )}`\n )\n );\n }\n\n yield logger.completedTask(Messages.CHECK_DEPENDENCIES);\n yield logger.runningTask(Messages.CHECK_TSCONFIG);\n await delay();\n\n let configResults: LoadConfigResult[];\n try {\n configResults = await loadConfigs();\n } catch (error) {\n yield logger.failedTask(Messages.CHECK_TSCONFIG);\n throw logger.externalError(\n `A ${logger.code('tsconfig.json')} file was not found in the current working directory.`,\n error\n );\n }\n\n const projects: ProjectContext[] = [];\n for (const configResult of configResults) {\n const label =\n path.relative(process.cwd(), configResult.tsconfigPath) || configResult.tsconfigPath;\n try {\n projects.push({\n configResult,\n pluginConfig: parseConfig(configResult.pluginConfig, configResult.rootPath),\n projectPath: path.dirname(configResult.tsconfigPath),\n label,\n });\n } catch (error) {\n yield logger.failedTask(Messages.CHECK_TSCONFIG);\n throw logger.externalError(\n `The plugin configuration for ${logger.code(\n supportsEmbeddedLsp ? '\"gql.tada/ts-plugin\"' : '\"@0no-co/graphqlsp\"'\n )} in ${logger.code(label)} seems to be invalid.`,\n error\n );\n }\n }\n\n try {\n validateUniqueOutputLocations(\n projects.map((project) => ({\n projectPath: project.projectPath,\n config: project.pluginConfig,\n label: project.label,\n }))\n );\n } catch (error) {\n yield logger.failedTask(Messages.CHECK_TSCONFIG);\n throw logger.externalError('The output locations of your configured projects overlap.', error);\n }\n\n yield logger.completedTask(Messages.CHECK_TSCONFIG);\n if (projects.length > 1) {\n yield logger.hintMessage(\n `Found ${projects.length} ${logger.code('gql.tada')} projects through ${logger.code(\n '\"references\"'\n )} in your ${logger.code('tsconfig.json')} files.\\n`\n );\n }\n\n yield* runExternalFilesChecks(projects, packageJson);\n\n yield* runVSCodeChecks();\n\n yield logger.runningTask(Messages.CHECK_SCHEMA);\n await delay();\n\n for (const project of projects) {\n try {\n await loadRef(project.pluginConfig).load({ rootPath: project.projectPath });\n } catch (error) {\n yield logger.failedTask(Messages.CHECK_SCHEMA);\n throw logger.externalError(\n projects.length > 1\n ? `Failed to load schema for project ${logger.code(project.label)}.`\n : 'Failed to load schema.',\n error\n );\n }\n }\n\n yield logger.completedTask(Messages.CHECK_SCHEMA, true);\n await delay();\n\n yield logger.success();\n}\n\nasync function* runVSCodeChecks(): AsyncIterable<ComposeInput> {\n const suggestedExtensions = await vscode.loadSuggestedExtensionsList();\n const isVSCodeInstalled = await vscode.isVSCodeInstalled();\n if (suggestedExtensions.length || isVSCodeInstalled) {\n yield logger.runningTask(Messages.CHECK_VSCODE);\n await delay();\n\n let hasEndedTask = false;\n let userExtensions: readonly string[] = [];\n if (isVSCodeInstalled) {\n userExtensions = await vscode.loadExtensionsList();\n if (!userExtensions.includes('graphql.vscode-graphql-syntax')) {\n if (!hasEndedTask) {\n hasEndedTask = true;\n yield logger.warningTask(Messages.CHECK_VSCODE);\n }\n yield logger.hintMessage(\n `We recommend you to install the ${logger.code(\n '\"GraphQL: Syntax Highlighting\"'\n )} extension for VSCode.\\n` +\n 'See: https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql-syntax\\n'\n );\n }\n }\n\n const hasProblemExtension =\n userExtensions.includes('graphql.vscode-graphql') ||\n suggestedExtensions.includes('graphql.vscode-graphql');\n const graphqlConfig = await findGraphQLConfig();\n if (hasProblemExtension && !!graphqlConfig) {\n if (!hasEndedTask) {\n hasEndedTask = true;\n yield logger.warningTask(Messages.CHECK_VSCODE);\n }\n const fileName = path.basename(graphqlConfig);\n yield logger.hintMessage(\n `The ${logger.code(\n '\"GraphQL: Language Feature Support\"'\n )} VSCode extension can cause problems!\\n` +\n `When enabled it may display invalid diagnostic errors for ${logger.code(\n 'gql.tada'\n )} code.\\n` +\n `Check whether your ${logger.code(fileName)} config only targets ${logger.code(\n '.graphql'\n )} documents.\\n`\n );\n }\n\n if (!hasEndedTask) {\n yield logger.completedTask(Messages.CHECK_VSCODE);\n }\n }\n}\n\nasync function* runExternalFilesChecks(\n projects: readonly ProjectContext[],\n packageJson: versions.PackageJson\n): AsyncIterable<ComposeInput> {\n const externalFiles: ts.SourceFile[] = [];\n for (const project of projects) {\n try {\n const factory = programFactory({\n rootPath: project.configResult.rootPath,\n configPath: project.configResult.tsconfigPath,\n });\n externalFiles.push(...factory.createExternalFiles());\n } catch (_error) {\n // NOTE: If a project fails to load, we currently just ignore this check and move on\n }\n }\n\n if (externalFiles.length) {\n yield logger.runningTask(Messages.CHECK_EXTERNAL_FILES);\n await delay();\n\n const extensions = new Set(\n externalFiles.map((sourceFile) => path.extname(sourceFile.fileName))\n );\n\n if (extensions.has('.svelte') && !(await versions.hasSvelteSupport(packageJson))) {\n yield logger.failedTask(Messages.CHECK_EXTERNAL_FILES);\n throw logger.errorMessage(\n `A version of ${logger.code(\n '@gql.tada/svelte-support'\n )} must be installed for Svelte file support.\\n` +\n logger.hint(`Have you installed ${logger.code('@gql.tada/svelte-support')}?`)\n );\n }\n\n if (extensions.has('.vue') && !(await versions.hasVueSupport(packageJson))) {\n yield logger.failedTask(Messages.CHECK_EXTERNAL_FILES);\n throw logger.errorMessage(\n `A version of ${logger.code(\n '@gql.tada/vue-support'\n )} must be installed for Vue file support.\\n` +\n logger.hint(`Have you installed ${logger.code('@gql.tada/vue-support')}?`)\n );\n }\n\n yield logger.completedTask(Messages.CHECK_EXTERNAL_FILES);\n }\n}\n","import { Command } from 'clipanion';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class DoctorCommand extends Command {\n static paths = [['doctor']];\n\n async execute() {\n const result = await initTTY().start(run());\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n","import * as path from 'node:path';\nimport { Command, Option } from 'clipanion';\n\nexport class InitCommand extends Command {\n static paths = [['init']];\n\n input = Option.String({ name: 'dir' });\n\n async execute() {\n const { run } = await import('./runner');\n const target = path.resolve(process.cwd(), this.input);\n await run(target);\n }\n}\n","import { Cli } from 'clipanion';\nimport * as api from './api';\n\nimport { CheckCommand } from './commands/check/index';\nimport { DoctorCommand } from './commands/doctor/index';\nimport { GenerateOutputCommand } from './commands/generate-output/index';\nimport { GeneratePersisted } from './commands/generate-persisted/index';\nimport { GenerateSchema } from './commands/generate-schema/index';\nimport { InitCommand } from './commands/init/index';\nimport { ScanCommand } from './commands/scan/index';\nimport { TurboCommand } from './commands/turbo/index';\n\nasync function _main() {\n const cli = new Cli({\n binaryVersion: process.env.npm_package_version || '0.0.0',\n binaryLabel: 'gql.tada CLI',\n binaryName: 'gql.tada',\n });\n\n cli.register(CheckCommand);\n cli.register(DoctorCommand);\n cli.register(GenerateOutputCommand);\n cli.register(GeneratePersisted);\n cli.register(GenerateSchema);\n cli.register(InitCommand);\n cli.register(ScanCommand);\n cli.register(TurboCommand);\n\n await cli.runExit(process.argv.slice(2));\n}\n\ntype MainFn = typeof _main & typeof api;\nconst main = Object.assign(_main, api) as MainFn;\n\nexport * from './api';\nexport default main;\n"],"names":["SpecialToken","NodeType","HELP_COMMAND_INDEX","HELP_REGEX","OPTION_REGEX","BATCH_REGEX","BINDING_REGEX","IS_DEBUG","process","env","DEBUG_CLI","UsageError","Error","constructor","message","super","this","clipanion","type","name","UnknownSyntaxError","input","candidates","length","every","candidate","reason","map","usage","join","whileRunning","index","padStart","AmbiguousSyntaxError","usages","filter","token","EndOfInput","EndOfPartialInput","json","JSON","stringify","match","richLine","Array","fill","t","richFormat","header","str","MAX_LINE_LENGTH","slice","bold","error","code","textFormat","formatMarkdownish","text","format","paragraphs","dedent","lines","split","nonEmptyLines","line","indent","reduce","minLength","Math","min","trimStart","Number","MAX_VALUE","trimRight","replace","$0","$1","paragraph","bulletMatch","RegExp","repeat","$2","isOptionSymbol","Symbol","makeCommandOption","spec","rerouteArguments","a","b","isArray","undefined","cleanValidationError","mergeName","path","toLowerCase","formatError","errors","applyValidator","value","validator","coercions","coercion","v","orig","bind","op","Command","help","Usage","catch","validateAndExecute","cascade","schema","isDict","isUnknown","applyCascade","Promise","resolve","then","exitCode","execute","isOption","Default","debug","console","log","basicHelpState","candidateUsage","requiredOptions","errorMessage","ignoreOptions","positionals","options","remainder","selectedIndex","tokens","makeStateMachine","stateMachine","nodes","CustomNode","push","dynamics","shortcuts","statics","injectNode","machine","node","runMachineInternal","partial","branches","InitialNode","state","debugMachine","prefix","StartOfInput","segment","isEOI","segmentIndex","nextBranches","nodeDef","ErrorNode","assert","hasExactMatch","Object","prototype","hasOwnProperty","call","transitions","to","reducer","reducers","hasMatches","keys","startsWith","test","tests","trimSmallerBranches","branch","runMachine","endToken","selectBestState","states","terminalStates","requiredOptionsSetStates","names","some","find","opt","maxPathSize","bestPathBranches","getPositionalCount","extra","statesWithPositionalCount","positionalCount","maxPositionalCount","fixedStates","aggregateHelpStates","notHelps","helps","findCommonPrefix","concat","firstPath","secondPath","rest","from","i","isTerminalNode","SuccessNode","cloneTransition","offset","cloneNode","output","transition","entries","registerDynamic","registerShortcut","registerStatic","store","callback","args","always","isOptionLike","isNotOptionLike","isBatchOption","has","isBoundOption","optionParsing","nameSet","includes","allowBinding","isNegatedOption","isHelp","isUnsupportedOption","isInvalidOption","setCandidateState","candidateState","setSelectedIndex","pushBatch","get","option","pushBound","pushPath","pushPositional","pushExtra","pushExtraNoLimits","NoLimits","pushTrue","pushFalse","pushUndefined","pushStringValue","_a","lastOption","setStringValue","inhibateOptions","useHelp","command","String","setError","setOptionArityError","CommandBuilder","cliIndex","cliOpts","allOptionNames","Map","arity","leading","trailing","proxy","paths","addPath","setArity","assign","addPositional","required","addRest","addProxy","addOption","description","hidden","isInteger","preferredName","longestName","set","setContext","context","detailed","inlineOptions","segments","binaryName","detailedOptionList","definition","compile","firstNode","positionalArgument","lastPathNode","optionPathNode","registerOptions","nextPathNode","helpNode","lastLeadingNode","nextLeadingNode","lastExtraNode","extraShortcutNode","extraNode","nextExtraNode","lastTrailingNode","nextTrailingNode","lastNode","nextNode","CliBuilder","builders","opts","build","cbs","commands","getBuilderByIndex","n","cb","builder","machines","contexts","makeAnyOfMachine","inputs","heads","head","simplifyMachine","visited","Set","add","values","shift","toDef","_loop","_loop2","_transition","otherTest","HelpCommand","stdout","write","cli","commandClass","errorCommandSymbol","Cli","binaryLabel","binaryNameOpt","binaryVersion","enableCapture","enableColors","registrations","commandClasses","resolvedCommandClasses","register","specs","key","contextArg","userContext","defaultContext","record","transformer","run","_b","colored","colorDepth","definitions","subContext","activate","getCaptureActivator","noopCaptureActivator","runExit","getUsageByRegistration","category","details","examples","label","data","isDocumented","isDefault","result","commandsByCategories","categoryCommands","getUsageByIndex","categoryNames","sort","localeCompare","caseFirst","hasLabel","hasVersion","categoryName","trim","doc","toUpperCase","maxDefinitionLength","max","padEnd","example","meta","stack","klass","stdin","stderr","fn","Boolean","descriptor","initialValueBase","optsBase","initialValue","optNames","builer","currentValue","StringOption","tolerateBoolean","usedName","StringPositional","positional","splice","TadaErrorCode","TadaError","isTadaError","parseInt","hasColor","_setColor","color","CSI","EraseLine","Mode","PrivateMode","Style","escapeCSI","cmd","out","SetPrivateMode","SetMode","UnsetPrivateMode","UnsetMode","ansiRegex","stripAnsi","CLIError","exit","toString","argIndex","arg","commit","source","make","observer","last","subscription","pipe","onPush","next","onEnd","endsWith","complete","subscribe","unsubscribe","compose","outputs","reset","Reset","NoInvert","outputs$","fromAsyncIterable","async","convertError","concatMap","fromValue","x","share","output$","merge","never","takeUntil","scan","prev","clear","charCodeAt","PrevLine","DeleteLines","Backward","ToColumn","takeLast","Chars","Box","HeavyBox","SmallTriangle","Icons","dotSpinner","circleSpinner","isGithubCI","GITHUB_ACTIONS","toCommandValue","escapeData","escapeProperty","githubAnnotation","kind","properties","propsOut","initTTY","params","isTTY","TERM","CI","disableTTY","pipeTo","hasColorArg","argv","hasColorEnv","NO_COLOR","_terminate","_restore","setRawMode","ResetPrivateMode","ShowCursor","_signal","signal","inputSource","fromReadStream","stream","onTerminate","onKeypress","event","ctrl","cleanup","removeListener","unref","emitKeypressEvents","setEncoding","resume","addListener","onStart","_start","on","_end","cancelSource","isInteractive","silent","start","toPromise","mode","modes","normalModes","privateModes","Insert","AutomaticNewline","modeOff","Newline","Underline","NoUnderline","Bold","Normal","hint","BrightBlack","BottomLeft","BrightBlue","Info","Blue","projectHeader","Magenta","Right","Foreground","Red","Invert","Warning","externalError","title","experimentMessage","Yellow","loadProjects","projects","loadConfigs","tsconfig","configResult","projectPath","dirname","tsconfigPath","pluginConfig","parseConfig","rootPath","relative","cwd","validateUniqueOutputLocations","project","config","directoryExists","stat","fs","file","isDirectory","isSymbolicLink","realpath","readOutput","target","readFile","writeOutput","contents","reject","targetDirectory","mkdir","recursive","isFile","writeFile","tempTarget","rename","unlink","now","Date","utimes","_error","touchFile","summary","showHint","BrightGreen","Tick","tty","logger","runProject","schemaRef","loadRef","load","current","destination","tadaOutputLocation","existing","outputIntrospectionFile","minifyIntrospection","introspection","fileType","forceTSFormat","shouldPreprocess","disablePreprocessing","preamble","extractIntrospectionHeader","schemaName","multi","GenerateOutputCommand","static","Option","generateOutput","CWD","INDENT","warningFile","filePath","relativePath","documentSummary","documentCount","warningSummary","warningCount","Cross","infoSummary","BrightYellow","warningGithub","col","runningPersisted","ofFiles","progress","frame","Ellipsis","interval","totalWarnings","failedProjects","warnings","failed","deferWarnings","runPersisted","require","generator","disableNormalization","configPath","documents","totalFileCount","fileCount","buffer","warning","Tab","tadaPersistedLocation","failOnWarn","item","hashKey","document","schemaConfig","schemas","GeneratePersisted","generatePersisted","simpleKeyRegExp","getPrintable","computeKey","_c","p","pushError","makeCoercionFn","previous","isLiteral","expected","makeValidator","isString","delimiter","originalValue","valid","T","isTuple","lengthValidator","hasExactLength","isRecord","keySpec","isArrayValidator","fromEntries","sub","isOneOf","exclusive","matches","errorBuffer","subErrors","subCoercions","makeTrait","matchesRegExp","regExp","followups","resolvedFollowups","subCoercion","reverts","revert","KeyRelationship","origin","headers","url","loader","extname","printSchema","isHeaderEntries","parseHeaders","entry","indexOf","trimEnd","GenerateSchema","generateSchema","reusedLabel","count","cachedCount","cachedLabel","runningTurbo","PREAMBLE_IGNORE","runTurbo","destinations","tadaTurboLocation","hintMessage","turboOutputPath","graphqlSources","cachedDocumentCount","sources","isCached","createCacheContents","cache","turboDestination","documentsByKey","argumentKey","documentHash","documentType","imports","isFilePath","addedImports","importInfo","turboPath","sourceDir","absolutePath","specifier","importClause","TurboCommand","generateTurbo","ModuleGraph","_dependents","edges","_edges","_cwd","importMap","areaOf","modulePath","rel","dir","entryPoints","_entryPoints","targets","tos","dependents","cached","reverse","_reverseGraph","pop","distanceFromEntry","_distance","distance","frontier","depth","reach","modules","areas","reachedEntries","module","_reverse","importers","FragmentGraph","_byId","_idByName","_operationIds","_reachable","id","reachableFragments","definitionId","fragmentSpreads","fragment","operationsReaching","fragmentId","_operationsReaching","operationId","reachableId","hashOf","crypto","createHash","update","digest","collectFragmentSpreads","visit","FragmentSpread","spread","ScanContext","_operations","_fragments","_definitions","_recordByNode","_recordById","_typeInfo","_currentDefinition","_schemas","_warnings","_importGraph","_buildCorpus","_modules","_buildModules","operations","fragments","getSchemas","definitionNodesForSchema","setTypeInfo","typeInfo","trackingVisitor","OperationDefinition","enter","leave","FragmentDefinition","getCurrentDefinition","getParentType","getType","getFieldDef","getInputType","getParentInputType","getEnumValue","getModuleGraph","_moduleGraph","getFragmentGraph","_fragmentGraph","_addWarning","_uniqueId","base","_register","defKind","_node","_defKind","info","anonCount","parse","noLocation","loc","Kind","OPERATION_DEFINITION","operation","variables","variableDefinitions","variable","print","defaultValue","hash","FRAGMENT_DEFINITION","typeCondition","byPath","ensure","resolved","fieldUsage","create","byCoordinate","seen","resetSeen","visitor","Field","parentType","fieldDef","coordinate","typeName","fieldName","fieldType","deprecationReason","directUsages","defId","collect","operationIds","moduleById","graph","hasEntryPoints","size","datapoints","sourceModules","u","reachModules","reachAreas","reachEntries","m","e","ref","weight","deprecated","coordinateOf","d","DEFAULT_RULES","counts","bump","EnumValue","inputType","getNamedType","ObjectField","parentInput","defIds","spreadIds","consumerAreas","spreadCount","byId","definingArea","externalAreas","area","byDef","startDefinition","ownDepth","fields","listFields","spreads","SelectionSet","isListType","getNullableType","depthMemo","effectiveDepth","visiting","metrics","delete","operationDepth","score","fieldCount","Directive","buildOverview","rules","operationsByKind","query","mutation","usedFields","totalFields","allSchemaFields","getTypeMap","isObjectType","isInterfaceType","field","getFields","percent","round","coverage","renderJson","version","overview","moduleNodeId","fieldNodeId","typeNodeId","fragmentKey","renderGraph","buildGraph","addNode","fragmentIdByName","moduleNode","datapoint","site","addDefinition","spreadName","MAX_PER_RULE","MIN_MESSAGE_WIDTH","RULE_DESCRIPTIONS","rule","truncate","renderTerminalReport","width","coverageLine","shown","truncated","forEach","isLast","weightText","locText","locator","locWidth","budget","VerticalRight","runningScan","runScan","quiet","loadSchemas","analyze","instances","instance","TypeInfo","visitInParallel","DOCUMENT","visitWithTypeInfo","results","render","wroteOutput","columns","ScanCommand","diagnosticFile","diagnosticMessage","severity","BrightRed","diagnosticMessageGithub","endLine","endColumn","runningDiagnostics","isMinSeverity","minSeverity","runDiagnostics","warn","warnedAboutExternalFiles","messages","problemsSummary","CheckCommand","Intl","Collator","numeric","compare","MINIMUM_VERSIONS","typescript_embed_lsp","typescript","tada","lsp","semverComply","semiver","bool","spanToFilePosition","span","fileName","lineAndChar","getLineAndCharacterOfPosition","character","notImplemented","methodName","defaultCompilerOptions","ts","getDefaultCompilerOptions","jsx","JsxEmit","React","strict","esModuleInterop","ModuleKind","ESNext","suppressOutputPathCheck","skipLibCheck","skipDefaultLibCheck","moduleResolution","ModuleResolutionKind","NodeJs","createVirtualCompilerHost","sys","compilerOptions","sourceFiles","compilerHost","getCanonicalFileName","getDefaultLibFileName","getDirectories","getNewLine","newLine","getSourceFile","sourceFile","save","createSourceFile","useCaseSensitiveFileNames","updateFile","alreadyExists","createVirtualLanguageServiceHost","rootFiles","customTransformers","fileNames","fileVersions","projectVersion","languageServiceHost","getProjectVersion","getCompilationSettings","getCustomTransformers","getScriptFileNames","getScriptSnapshot","ScriptSnapshot","fromString","getScriptVersion","defineProperty","binarySearch_1","binarySearch","offsets","low","high","mid","floor","midValue","track_1","getStack","track","resetOffsetStack","offsetStack","setTracking","tracking","stackOffset","stacks","Proxy","prop","receiver","unshift","Reflect","items","first","deleteCount","_stackStart","operateIndex","stackStart","originalLength","_deleteCount","compareFn","lastIndexOf","types","__createBinding","o","k","k2","desc","getOwnPropertyDescriptor","__esModule","writable","configurable","enumerable","__exportStar","exports","replaceRange","replaceSourceRange","getLength","require$$0","require$$1","require$$2","s","pattern","replacers","startOffset","endOffset","replacer","replaceAll","allMatch","matchAll","lengthDiff","newLength","newSegments","segmentStart","segmentEnd","inserts","trimSegmentEnd","newSegment","trimSegmentStart","combineStrings","toOffsets","startIndex","endIndex","endSegment","startSegmentStart","endSegmentStart","endSegmentEnd","searchValue","translateOffset_1","translateOffset","fromOffsets","lengths","fromOffset","sourceMap","SourceMap","mappings","getSourceOffset","generatedOffset","mapped","findMatching","getGeneratedOffset","sourceOffset","getSourceOffsets","getGeneratedOffsets","fromRange","toRange","memo","getMemoBasedOnRange","end","skip","mapping","sourceCodeOffsetsMemo","createMemo","generatedCodeOffsetsMemo","offsetsSet","buildMappings_1","buildMappings","chunks","sourceOffsets","generatedOffsets","buildStacks_1","buildStacks","range","require$$3","require$$4","SourceMappedFile","sourceFileId","generatedFileId","getSourceSpan","sourceStart","sourceEnd","maybeBind","that","buildLanguageService","virtualMap","languageService","createLanguageService","documentRegistry","getProgram","mapFileFn","fileFn","fileId","mappedFile","mapFileTextSpanFn","textSpanFn","mapFileTextRangeFn","pos","mapFilePositionFn","positionFn","position","mapFileStartEndFn","program","serviceProgram","projectRoot","isSourceFileFromExternalLibrary","getModeForResolutionAtIndex","getSourceFiles","mapSourceFileFn","getSyntacticDiagnostics","getSemanticDiagnostics","getDeclarationDiagnostics","isSourceFileDefaultLibrary","getModeForUsageLocation","buildProgram","getReferencesAtPosition","findReferences","getDefinitionAtPosition","getDefinitionAndBoundSpan","getTypeDefinitionAtPosition","getImplementationAtPosition","getCompletionsAtPosition","getCompletionEntryDetails","getCompletionEntrySymbol","getQuickInfoAtPosition","getBreakpointStatementAtPosition","getSignatureHelpItems","getRenameInfo","getSmartSelectionRange","getDocumentHighlights","prepareCallHierarchy","provideCallHierarchyIncomingCalls","provideCallHierarchyOutgoingCalls","getBraceMatchingAtPosition","getIndentationAtPosition","getFormattingEditsAfterKeystroke","getDocCommentTemplateAtPosition","isValidBraceCompletionAtPosition","getJsxClosingTagAtPosition","getLinkedEditingRangeAtPosition","getSpanOfEnclosingComment","getSyntacticClassifications","getSemanticClassifications","getEncodedSyntacticClassifications","getEncodedSemanticClassifications","provideInlayHints","getNameOrDottedNameSpan","getFormattingEditsForRange","getCodeFixesAtPosition","getFileReferences","getNavigationBarItems","getNavigationTree","getOutliningSpans","getTodoComments","getFormattingEditsForDocument","getEditsForRefactor","getEmitOutput","getSuggestionDiagnostics","getSupportedCodeFixes","toggleLineComment","toggleMultilineComment","commentSelection","uncommentSelection","buildPluginInfo","getLanguageService","system","rootNames","getProjectName","projectService","serverHost","setImmediate","clearImmediate","_svelte","_vue","transformExtensions","transform","import","SVELTE_SUPPORT","transformSvelte","VUE_SUPPORT","check","checkVue","transformVue","UNKNOWN_EXTERNAL_FILE","programFactory","vfsMap","createFSBackedSystem","files","_projectRoot","tsLibDirectory","root","nodeSys","tsLib","directory","createDirectory","fileExists","tsLibName","getCurrentDirectory","getExecutingFilePath","readDirectory","libs","resolvePath","resolveDefaultLibsPath","resolveConfig","getDefaultLibFilePath","noCheck","orignallyNodeNext","NodeNext","Node16","Bundler","host","createDocumentRegistry","factory","wasOriginallyNodeNext","projectDirectories","directories","rootName","rootFileNames","scriptKind","sourceText","getText","ScriptTarget","ScriptKind","TSX","createExternalFiles","exts","External","addSourceFile","addMappedFile","sourceMappedFile","addVirtualFiles","virtualFileId","virtualCode","snapshot","resolveModulePath","importSpecifier","fromPath","resolveModuleName","resolvedModule","resolvedFileName","toPath","fromDir","toDir","absoluteImportPath","relativeImportPath","bumpStackTraceLimit","stackTraceLimit","init","service","serviceHost","pluginInfo","getLanguageServiceHost","createProgram","getSourceMappedFile","getSourcePosition","buildContainer","createRequire","request","parseResult","parseConfigFileTextToJson","messageText","parseJsonConfigFileContent","FileType","File","Directory","configFileRe","findGraphQLConfig","readdir","configFile","workspaceRoot","targetPath","packageJsonPath","workspaces","findWorkspaceRoot","graphql","loadPnpmWorkspaceCatalogs","startPath","currentPath","workspaceFile","access","findPnpmWorkspaceroot","content","currentSection","currentCatalog","trimmed","packages","catalog","catalogs","colonIndex","parseYaml","loadBunWorkspaceCatalogs","packageJsonFile","packageJson","findBunWorkspaceRoot","loadWorkspaceCatalogs","pnpmCatalogs","bunCatalogs","resolveCatalogVersion","catalogRef","catalogName","getVersionFromCatalog","packageName","getPackageVersion","devVersion","devDependencies","resolvedVersion","depVersion","dependencies","hasPackageSupport","__dirname","hasSvelteSupport","hasVueSupport","jsonParse","parseJsonText","convertToObject","isVSCodeInstalled","HOME","vscodeFolder","loadSuggestedExtensionsList","recommendations","loadExtensionsList","identifier","emptyLine","Vertical","completedTask","Green","TickSwoosh","failedTask","CrossSwoosh","warningTask","runningTask","delay","ms","setTimeout","Messages","TopLeft","TITLE","DESCRIPTION","CHECK_TS_VERSION","versions","typeScriptVersion","pkg","catalogVersion","CHECK_DEPENDENCIES","supportsEmbeddedLsp","gqlspVersion","gqlTadaVersion","CHECK_TSCONFIG","configResults","runExternalFilesChecks","externalFiles","CHECK_EXTERNAL_FILES","extensions","runVSCodeChecks","suggestedExtensions","vscode","CHECK_VSCODE","hasEndedTask","userExtensions","hasProblemExtension","graphqlConfig","basename","CHECK_SCHEMA","success","Space","DoctorCommand","InitCommand","main","_main","npm_package_version","api"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAIA;;CACJ,SAAWA;EACPA,EAA2B,eAAI;EAC/BA,EAAyB,aAAI;EAC7BA,EAAgC,oBAAI;AACvC,CAJD,CAIGA,MAAiBA,IAAe,CAAE;;AACrC,IAAIC;;CACJ,SAAWA;EACPA,EAASA,EAAsB,cAAI,KAAK;EACxCA,EAASA,EAAsB,cAAI,KAAK;EACxCA,EAASA,EAAoB,YAAI,KAAK;EACtCA,EAASA,EAAqB,aAAI,KAAK;AAC1C,CALD,CAKGA,MAAaA,IAAW,CAAE;;AAC7B,IAAMC,KAAsB;;AAC5B,IAAMC,IAAa;;AACnB,IAAMC,IAAe;;AACrB,IAAMC,IAAc;;AACpB,IAAMC,IAAgB;;AACtB,IAAMC,IAAqC,QAA1BC,QAAQC,IAAIC;;ACX7B,MAAMC,mBAAmBC;EACrBC,WAAAA,CAAYC;IACRC,MAAMD;IACNE,KAAKC,YAAY;MAAEC,MAAM;;IACzBF,KAAKG,OAAO;AAChB;;;AAEJ,MAAMC,2BAA2BR;EAC7BC,WAAAA,CAAYQ,GAAOC;IACfP;IACAC,KAAKK,QAAQA;IACbL,KAAKM,aAAaA;IAClBN,KAAKC,Y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O;AACnE;;;ACRK,MAAMijC,oBAAoB53C;EAC/BihB,aAAe,EAAC,EAAC;EAEjBtmB,MAAQumB,SAAc;IAAEzmB,MAAM;;EAE9B,aAAMqG;IACJ,KAAM+O,KAAEA,WAAcnP,QAAOC,UAAAC,MAAA;MAAA,OAAAkiB,QAAA;;IAC7B,IAAMzE,IAASlf,EAAKwB,QAAQ7G,QAAQ2jB,OAAOnjB,KAAKK;UAC1CkV,EAAIwO;AACZ;;;ACoBIw5B,IAAAA,KAAOp0C,OAAO4G,QApBpB+L,eAAe0hC;EACb,IAAMrpC,IAAM,IAAIG,IAAI;IAClBG,eAAejV,QAAQC,IAAIg+C,uBAAuB;IAClDlpC,aAAa;IACbvD,YAAY;;EAGdmD,EAAIY,SAAS4qB;EACbxrB,EAAIY,SAASsoC;EACblpC,EAAIY,SAAS2R;EACbvS,EAAIY,SAAS0U;EACbtV,EAAIY,SAAS8X;EACb1Y,EAAIY,SAASuoC;EACbnpC,EAAIY,SAAS4pB;EACbxqB,EAAIY,SAAS+Z;QAEP3a,EAAI6B,QAAQxW,QAAQif,KAAKtc,MAAM;AACvC,IAGkCu7C;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,26,30,58,62,63,64,65,66,67,68,69,70,71]}
1
+ {"version":3,"file":"index-chunk.js","sources":["../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/constants.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/errors.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/format.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/utils.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/Command.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/core.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/HelpCommand.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/Cli.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/platform/browser.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Boolean.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/String.mjs","../../src/utils/error.ts","../../src/term/csi.ts","../../src/term/write.ts","../../src/term/symbols.ts","../../src/term/github.ts","../../src/term/tty.ts","../../src/commands/shared/logger.ts","../../src/commands/shared/projects.ts","../../src/commands/shared/utils.ts","../../src/commands/generate-output/logger.ts","../../src/commands/generate-output/runner.ts","../../src/commands/generate-output/index.ts","../../src/commands/generate-persisted/logger.ts","../../src/commands/generate-persisted/runner.ts","../../src/commands/generate-persisted/index.ts","../../../../node_modules/.pnpm/typanion@3.14.0/node_modules/typanion/lib/index.mjs","../../src/commands/generate-schema/runner.ts","../../src/commands/generate-schema/logger.ts","../../src/commands/generate-schema/index.ts","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Array.mjs","../../src/commands/turbo/logger.ts","../../src/commands/turbo/runner.ts","../../src/commands/turbo/index.ts","../../src/commands/scan/module-graph.ts","../../src/commands/scan/fragment-graph.ts","../../src/commands/scan/context.ts","../../src/commands/scan/rules/field-usage.ts","../../src/commands/scan/rules/index.ts","../../src/commands/scan/rules/input-usage.ts","../../src/commands/scan/rules/deprecated-usage.ts","../../src/commands/scan/rules/orphan-fragments.ts","../../src/commands/scan/rules/cross-feature-fragments.ts","../../src/commands/scan/rules/operation-complexity.ts","../../src/commands/scan/rules/fetch-depth.ts","../../src/commands/scan/rules/directive-usage.ts","../../src/commands/scan/output/overview.ts","../../src/commands/scan/schema-util.ts","../../src/commands/scan/output/json.ts","../../src/commands/scan/output/graph.ts","../../src/commands/scan/output/terminal.ts","../../src/commands/scan/logger.ts","../../src/commands/scan/runner.ts","../../src/commands/scan/analyze.ts","../../src/commands/scan/index.ts","../../src/commands/check/logger.ts","../../src/commands/check/runner.ts","../../src/commands/check/index.ts","../../../../node_modules/.pnpm/semiver@1.1.0/node_modules/semiver/dist/semiver.mjs","../../src/utils/semver.ts","../../src/ts/utils.ts","../../src/ts/vendor/typescript-vfs.ts","../../../../node_modules/.pnpm/muggle-string@0.4.1/node_modules/muggle-string/out/binarySearch.js","../../../../node_modules/.pnpm/muggle-string@0.4.1/node_modules/muggle-string/out/track.js","../../../../node_modules/.pnpm/muggle-string@0.4.1/node_modules/muggle-string/out/types.js","../../../../node_modules/.pnpm/muggle-string@0.4.1/node_modules/muggle-string/out/index.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/binarySearch.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/translateOffset.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/sourceMap.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/buildMappings.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/buildStacks.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/index.js","../../src/ts/mapping.ts","../../src/ts/container.ts","../../src/ts/transformers.ts","../../src/ts/factory.ts","../../src/commands/doctor/helpers/fs.ts","../../src/commands/doctor/helpers/graphqlConfig.ts","../../src/commands/doctor/helpers/workspaceRoot.ts","../../src/commands/doctor/helpers/versions.ts","../../src/commands/doctor/helpers/vscode.ts","../../src/commands/doctor/logger.ts","../../src/commands/doctor/runner.ts","../../src/commands/doctor/index.ts","../../src/commands/init/index.ts","../../src/index.ts"],"sourcesContent":["var SpecialToken;\n(function (SpecialToken) {\n SpecialToken[\"StartOfInput\"] = \"\\0\";\n SpecialToken[\"EndOfInput\"] = \"\\u0001\";\n SpecialToken[\"EndOfPartialInput\"] = \"\\u0002\";\n})(SpecialToken || (SpecialToken = {}));\nvar NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"InitialNode\"] = 0] = \"InitialNode\";\n NodeType[NodeType[\"SuccessNode\"] = 1] = \"SuccessNode\";\n NodeType[NodeType[\"ErrorNode\"] = 2] = \"ErrorNode\";\n NodeType[NodeType[\"CustomNode\"] = 3] = \"CustomNode\";\n})(NodeType || (NodeType = {}));\nconst HELP_COMMAND_INDEX = -1;\nconst HELP_REGEX = /^(-h|--help)(?:=([0-9]+))?$/;\nconst OPTION_REGEX = /^(--[a-z]+(?:-[a-z]+)*|-[a-zA-Z]+)$/;\nconst BATCH_REGEX = /^-[a-zA-Z]{2,}$/;\nconst BINDING_REGEX = /^([^=]+)=([\\s\\S]*)$/;\nconst IS_DEBUG = process.env.DEBUG_CLI === `1`;\n\nexport { BATCH_REGEX, BINDING_REGEX, HELP_COMMAND_INDEX, HELP_REGEX, IS_DEBUG, NodeType, OPTION_REGEX, SpecialToken };\n","import { SpecialToken } from './constants.mjs';\n\n/**\n * A generic usage error with the name `UsageError`.\n *\n * It should be used over `Error` only when it's the user's fault.\n */\nclass UsageError extends Error {\n constructor(message) {\n super(message);\n this.clipanion = { type: `usage` };\n this.name = `UsageError`;\n }\n}\nclass UnknownSyntaxError extends Error {\n constructor(input, candidates) {\n super();\n this.input = input;\n this.candidates = candidates;\n this.clipanion = { type: `none` };\n this.name = `UnknownSyntaxError`;\n if (this.candidates.length === 0) {\n this.message = `Command not found, but we're not sure what's the alternative.`;\n }\n else if (this.candidates.every(candidate => candidate.reason !== null && candidate.reason === candidates[0].reason)) {\n const [{ reason }] = this.candidates;\n this.message = `${reason}\\n\\n${this.candidates.map(({ usage }) => `$ ${usage}`).join(`\\n`)}`;\n }\n else if (this.candidates.length === 1) {\n const [{ usage }] = this.candidates;\n this.message = `Command not found; did you mean:\\n\\n$ ${usage}\\n${whileRunning(input)}`;\n }\n else {\n this.message = `Command not found; did you mean one of:\\n\\n${this.candidates.map(({ usage }, index) => {\n return `${`${index}.`.padStart(4)} ${usage}`;\n }).join(`\\n`)}\\n\\n${whileRunning(input)}`;\n }\n }\n}\nclass AmbiguousSyntaxError extends Error {\n constructor(input, usages) {\n super();\n this.input = input;\n this.usages = usages;\n this.clipanion = { type: `none` };\n this.name = `AmbiguousSyntaxError`;\n this.message = `Cannot find which to pick amongst the following alternatives:\\n\\n${this.usages.map((usage, index) => {\n return `${`${index}.`.padStart(4)} ${usage}`;\n }).join(`\\n`)}\\n\\n${whileRunning(input)}`;\n }\n}\nconst whileRunning = (input) => `While running ${input.filter(token => {\n return token !== SpecialToken.EndOfInput && token !== SpecialToken.EndOfPartialInput;\n}).map(token => {\n const json = JSON.stringify(token);\n if (token.match(/\\s/) || token.length === 0 || json !== `\"${token}\"`) {\n return json;\n }\n else {\n return token;\n }\n}).join(` `)}`;\n\nexport { AmbiguousSyntaxError, UnknownSyntaxError, UsageError };\n","const MAX_LINE_LENGTH = 80;\nconst richLine = Array(MAX_LINE_LENGTH).fill(`━`);\nfor (let t = 0; t <= 24; ++t)\n richLine[richLine.length - t] = `\\x1b[38;5;${232 + t}m━`;\nconst richFormat = {\n header: str => `\\x1b[1m━━━ ${str}${str.length < MAX_LINE_LENGTH - 5 ? ` ${richLine.slice(str.length + 5).join(``)}` : `:`}\\x1b[0m`,\n bold: str => `\\x1b[1m${str}\\x1b[22m`,\n error: str => `\\x1b[31m\\x1b[1m${str}\\x1b[22m\\x1b[39m`,\n code: str => `\\x1b[36m${str}\\x1b[39m`,\n};\nconst textFormat = {\n header: str => str,\n bold: str => str,\n error: str => str,\n code: str => str,\n};\nfunction dedent(text) {\n const lines = text.split(`\\n`);\n const nonEmptyLines = lines.filter(line => line.match(/\\S/));\n const indent = nonEmptyLines.length > 0 ? nonEmptyLines.reduce((minLength, line) => Math.min(minLength, line.length - line.trimStart().length), Number.MAX_VALUE) : 0;\n return lines\n .map(line => line.slice(indent).trimRight())\n .join(`\\n`);\n}\n/**\n * Formats markdown text to be displayed to the console. Not all markdown features are supported.\n *\n * @param text The markdown text to format.\n * @param opts.format The format to use.\n * @param opts.paragraphs Whether to cut the text into paragraphs of 80 characters at most.\n */\nfunction formatMarkdownish(text, { format, paragraphs }) {\n // Enforce \\n as newline character\n text = text.replace(/\\r\\n?/g, `\\n`);\n // Remove the indentation, since it got messed up with the JS indentation\n text = dedent(text);\n // Remove surrounding newlines, since they got added for JS formatting\n text = text.replace(/^\\n+|\\n+$/g, ``);\n // List items always end with at least two newlines (in order to not be collapsed)\n text = text.replace(/^(\\s*)-([^\\n]*?)\\n+/gm, `$1-$2\\n\\n`);\n // Single newlines are removed; larger than that are collapsed into one\n text = text.replace(/\\n(\\n)?\\n*/g, ($0, $1) => $1 ? $1 : ` `);\n if (paragraphs) {\n text = text.split(/\\n/).map(paragraph => {\n // Does the paragraph starts with a list?\n const bulletMatch = paragraph.match(/^\\s*[*-][\\t ]+(.*)/);\n if (!bulletMatch)\n // No, cut the paragraphs into segments of 80 characters\n return paragraph.match(/(.{1,80})(?: |$)/g).join(`\\n`);\n const indent = paragraph.length - paragraph.trimStart().length;\n // Yes, cut the paragraphs into segments of (78 - indent) characters (to account for the prefix)\n return bulletMatch[1].match(new RegExp(`(.{1,${78 - indent}})(?: |$)`, `g`)).map((line, index) => {\n return ` `.repeat(indent) + (index === 0 ? `- ` : ` `) + line;\n }).join(`\\n`);\n }).join(`\\n\\n`);\n }\n // Highlight the code segments\n text = text.replace(/(`+)((?:.|[\\n])*?)\\1/g, ($0, $1, $2) => {\n return format.code($1 + $2 + $1);\n });\n // Highlight the bold segments\n text = text.replace(/(\\*\\*)((?:.|[\\n])*?)\\1/g, ($0, $1, $2) => {\n return format.bold($1 + $2 + $1);\n });\n return text ? `${text}\\n` : ``;\n}\n\nexport { formatMarkdownish, richFormat, textFormat };\n","import { UsageError } from '../../errors.mjs';\n\nconst isOptionSymbol = Symbol(`clipanion/isOption`);\nfunction makeCommandOption(spec) {\n // We lie! But it's for the good cause: the cli engine will turn the specs into proper values after instantiation.\n return { ...spec, [isOptionSymbol]: true };\n}\nfunction rerouteArguments(a, b) {\n if (typeof a === `undefined`)\n return [a, b];\n if (typeof a === `object` && a !== null && !Array.isArray(a)) {\n return [undefined, a];\n }\n else {\n return [a, b];\n }\n}\nfunction cleanValidationError(message, { mergeName = false } = {}) {\n const match = message.match(/^([^:]+): (.*)$/m);\n if (!match)\n return `validation failed`;\n let [, path, line] = match;\n if (mergeName)\n line = line[0].toLowerCase() + line.slice(1);\n line = path !== `.` || !mergeName\n ? `${path.replace(/^\\.(\\[|$)/, `$1`)}: ${line}`\n : `: ${line}`;\n return line;\n}\nfunction formatError(message, errors) {\n if (errors.length === 1) {\n return new UsageError(`${message}${cleanValidationError(errors[0], { mergeName: true })}`);\n }\n else {\n return new UsageError(`${message}:\\n${errors.map(error => `\\n- ${cleanValidationError(error)}`).join(``)}`);\n }\n}\nfunction applyValidator(name, value, validator) {\n if (typeof validator === `undefined`)\n return value;\n const errors = [];\n const coercions = [];\n const coercion = (v) => {\n const orig = value;\n value = v;\n return coercion.bind(null, orig);\n };\n const check = validator(value, { errors, coercions, coercion });\n if (!check)\n throw formatError(`Invalid value for ${name}`, errors);\n for (const [, op] of coercions)\n op();\n return value;\n}\n\nexport { applyValidator, cleanValidationError, formatError, isOptionSymbol, makeCommandOption, rerouteArguments };\n","import { formatError, isOptionSymbol } from './options/utils.mjs';\n\n/**\n * Base abstract class for CLI commands. The main thing to remember is to\n * declare an async `execute` member function that will be called when the\n * command is invoked from the CLI, and optionally a `paths` property to\n * declare the set of paths under which the command should be exposed.\n */\nclass Command {\n constructor() {\n /**\n * Predefined that will be set to true if `-h,--help` has been used, in\n * which case `Command#execute` won't be called.\n */\n this.help = false;\n }\n /**\n * Defines the usage information for the given command.\n */\n static Usage(usage) {\n return usage;\n }\n /**\n * Standard error handler which will simply rethrow the error. Can be used\n * to add custom logic to handle errors from the command or simply return\n * the parent class error handling.\n */\n async catch(error) {\n throw error;\n }\n async validateAndExecute() {\n const commandClass = this.constructor;\n const cascade = commandClass.schema;\n if (Array.isArray(cascade)) {\n const { isDict, isUnknown, applyCascade } = await import('typanion');\n const schema = applyCascade(isDict(isUnknown()), cascade);\n const errors = [];\n const coercions = [];\n const check = schema(this, { errors, coercions });\n if (!check)\n throw formatError(`Invalid option schema`, errors);\n for (const [, op] of coercions) {\n op();\n }\n }\n else if (cascade != null) {\n throw new Error(`Invalid command schema`);\n }\n const exitCode = await this.execute();\n if (typeof exitCode !== `undefined`) {\n return exitCode;\n }\n else {\n return 0;\n }\n }\n}\n/**\n * Used to detect option definitions.\n */\nCommand.isOption = isOptionSymbol;\n/**\n * Just an helper to use along with the `paths` fields, to make it\n * clearer that a command is the default one.\n *\n * @example\n * class MyCommand extends Command {\n * static paths = [Command.Default];\n * }\n */\nCommand.Default = [];\n\nexport { Command };\n","import { IS_DEBUG, NodeType, SpecialToken, HELP_COMMAND_INDEX, BATCH_REGEX, BINDING_REGEX, OPTION_REGEX, HELP_REGEX } from './constants.mjs';\nimport { UnknownSyntaxError, AmbiguousSyntaxError } from './errors.mjs';\n\n// ------------------------------------------------------------------------\nfunction debug(str) {\n if (IS_DEBUG) {\n console.log(str);\n }\n}\nconst basicHelpState = {\n candidateUsage: null,\n requiredOptions: [],\n errorMessage: null,\n ignoreOptions: false,\n path: [],\n positionals: [],\n options: [],\n remainder: null,\n selectedIndex: HELP_COMMAND_INDEX,\n tokens: [],\n};\nfunction makeStateMachine() {\n const stateMachine = {\n nodes: [],\n };\n for (let t = 0; t < NodeType.CustomNode; ++t)\n stateMachine.nodes.push(makeNode());\n return stateMachine;\n}\nfunction makeAnyOfMachine(inputs) {\n const output = makeStateMachine();\n const heads = [];\n let offset = output.nodes.length;\n for (const input of inputs) {\n heads.push(offset);\n for (let t = 0; t < input.nodes.length; ++t)\n if (!isTerminalNode(t))\n output.nodes.push(cloneNode(input.nodes[t], offset));\n offset += input.nodes.length - NodeType.CustomNode + 1;\n }\n for (const head of heads)\n registerShortcut(output, NodeType.InitialNode, head);\n return output;\n}\nfunction injectNode(machine, node) {\n machine.nodes.push(node);\n return machine.nodes.length - 1;\n}\nfunction simplifyMachine(input) {\n const visited = new Set();\n const process = (node) => {\n if (visited.has(node))\n return;\n visited.add(node);\n const nodeDef = input.nodes[node];\n for (const transitions of Object.values(nodeDef.statics))\n for (const { to } of transitions)\n process(to);\n for (const [, { to }] of nodeDef.dynamics)\n process(to);\n for (const { to } of nodeDef.shortcuts)\n process(to);\n const shortcuts = new Set(nodeDef.shortcuts.map(({ to }) => to));\n while (nodeDef.shortcuts.length > 0) {\n const { to } = nodeDef.shortcuts.shift();\n const toDef = input.nodes[to];\n for (const [segment, transitions] of Object.entries(toDef.statics)) {\n const store = !Object.prototype.hasOwnProperty.call(nodeDef.statics, segment)\n ? nodeDef.statics[segment] = []\n : nodeDef.statics[segment];\n for (const transition of transitions) {\n if (!store.some(({ to }) => transition.to === to)) {\n store.push(transition);\n }\n }\n }\n for (const [test, transition] of toDef.dynamics)\n if (!nodeDef.dynamics.some(([otherTest, { to }]) => test === otherTest && transition.to === to))\n nodeDef.dynamics.push([test, transition]);\n for (const transition of toDef.shortcuts) {\n if (!shortcuts.has(transition.to)) {\n nodeDef.shortcuts.push(transition);\n shortcuts.add(transition.to);\n }\n }\n }\n };\n process(NodeType.InitialNode);\n}\nfunction debugMachine(machine, { prefix = `` } = {}) {\n // Don't iterate unless it's needed\n if (IS_DEBUG) {\n debug(`${prefix}Nodes are:`);\n for (let t = 0; t < machine.nodes.length; ++t) {\n debug(`${prefix} ${t}: ${JSON.stringify(machine.nodes[t])}`);\n }\n }\n}\nfunction runMachineInternal(machine, input, partial = false) {\n debug(`Running a vm on ${JSON.stringify(input)}`);\n let branches = [{\n node: NodeType.InitialNode,\n state: {\n candidateUsage: null,\n requiredOptions: [],\n errorMessage: null,\n ignoreOptions: false,\n options: [],\n path: [],\n positionals: [],\n remainder: null,\n selectedIndex: null,\n tokens: [],\n },\n }];\n debugMachine(machine, { prefix: ` ` });\n const tokens = [SpecialToken.StartOfInput, ...input];\n for (let t = 0; t < tokens.length; ++t) {\n const segment = tokens[t];\n const isEOI = segment === SpecialToken.EndOfInput || segment === SpecialToken.EndOfPartialInput;\n // The -1 is because we added a START_OF_INPUT token\n const segmentIndex = t - 1;\n debug(` Processing ${JSON.stringify(segment)}`);\n const nextBranches = [];\n for (const { node, state } of branches) {\n debug(` Current node is ${node}`);\n const nodeDef = machine.nodes[node];\n if (node === NodeType.ErrorNode) {\n nextBranches.push({ node, state });\n continue;\n }\n console.assert(nodeDef.shortcuts.length === 0, `Shortcuts should have been eliminated by now`);\n const hasExactMatch = Object.prototype.hasOwnProperty.call(nodeDef.statics, segment);\n if (!partial || t < tokens.length - 1 || hasExactMatch) {\n if (hasExactMatch) {\n const transitions = nodeDef.statics[segment];\n for (const { to, reducer } of transitions) {\n nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });\n debug(` Static transition to ${to} found`);\n }\n }\n else {\n debug(` No static transition found`);\n }\n }\n else {\n let hasMatches = false;\n for (const candidate of Object.keys(nodeDef.statics)) {\n if (!candidate.startsWith(segment))\n continue;\n if (segment === candidate) {\n for (const { to, reducer } of nodeDef.statics[candidate]) {\n nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });\n debug(` Static transition to ${to} found`);\n }\n }\n else {\n for (const { to } of nodeDef.statics[candidate]) {\n nextBranches.push({ node: to, state: { ...state, remainder: candidate.slice(segment.length) } });\n debug(` Static transition to ${to} found (partial match)`);\n }\n }\n hasMatches = true;\n }\n if (!hasMatches) {\n debug(` No partial static transition found`);\n }\n }\n if (!isEOI) {\n for (const [test, { to, reducer }] of nodeDef.dynamics) {\n if (execute(tests, test, state, segment, segmentIndex)) {\n nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });\n debug(` Dynamic transition to ${to} found (via ${test})`);\n }\n }\n }\n }\n if (nextBranches.length === 0 && isEOI && input.length === 1) {\n return [{\n node: NodeType.InitialNode,\n state: basicHelpState,\n }];\n }\n if (nextBranches.length === 0) {\n throw new UnknownSyntaxError(input, branches.filter(({ node }) => {\n return node !== NodeType.ErrorNode;\n }).map(({ state }) => {\n return { usage: state.candidateUsage, reason: null };\n }));\n }\n if (nextBranches.every(({ node }) => node === NodeType.ErrorNode)) {\n throw new UnknownSyntaxError(input, nextBranches.map(({ state }) => {\n return { usage: state.candidateUsage, reason: state.errorMessage };\n }));\n }\n branches = trimSmallerBranches(nextBranches);\n }\n if (branches.length > 0) {\n debug(` Results:`);\n for (const branch of branches) {\n debug(` - ${branch.node} -> ${JSON.stringify(branch.state)}`);\n }\n }\n else {\n debug(` No results`);\n }\n return branches;\n}\nfunction runMachine(machine, input, { endToken = SpecialToken.EndOfInput } = {}) {\n const branches = runMachineInternal(machine, [...input, endToken]);\n return selectBestState(input, branches.map(({ state }) => {\n return state;\n }));\n}\nfunction trimSmallerBranches(branches) {\n let maxPathSize = 0;\n for (const { state } of branches)\n if (state.path.length > maxPathSize)\n maxPathSize = state.path.length;\n return branches.filter(({ state }) => {\n return state.path.length === maxPathSize;\n });\n}\nfunction selectBestState(input, states) {\n const terminalStates = states.filter(state => {\n return state.selectedIndex !== null;\n });\n if (terminalStates.length === 0)\n throw new Error();\n const requiredOptionsSetStates = terminalStates.filter(state => state.selectedIndex === HELP_COMMAND_INDEX || state.requiredOptions.every(names => names.some(name => state.options.find(opt => opt.name === name))));\n if (requiredOptionsSetStates.length === 0) {\n throw new UnknownSyntaxError(input, terminalStates.map(state => ({\n usage: state.candidateUsage,\n reason: null,\n })));\n }\n let maxPathSize = 0;\n for (const state of requiredOptionsSetStates)\n if (state.path.length > maxPathSize)\n maxPathSize = state.path.length;\n const bestPathBranches = requiredOptionsSetStates.filter(state => {\n return state.path.length === maxPathSize;\n });\n const getPositionalCount = (state) => state.positionals.filter(({ extra }) => {\n return !extra;\n }).length + state.options.length;\n const statesWithPositionalCount = bestPathBranches.map(state => {\n return { state, positionalCount: getPositionalCount(state) };\n });\n let maxPositionalCount = 0;\n for (const { positionalCount } of statesWithPositionalCount)\n if (positionalCount > maxPositionalCount)\n maxPositionalCount = positionalCount;\n const bestPositionalStates = statesWithPositionalCount.filter(({ positionalCount }) => {\n return positionalCount === maxPositionalCount;\n }).map(({ state }) => {\n return state;\n });\n const fixedStates = aggregateHelpStates(bestPositionalStates);\n if (fixedStates.length > 1)\n throw new AmbiguousSyntaxError(input, fixedStates.map(state => state.candidateUsage));\n return fixedStates[0];\n}\nfunction aggregateHelpStates(states) {\n const notHelps = [];\n const helps = [];\n for (const state of states) {\n if (state.selectedIndex === HELP_COMMAND_INDEX) {\n helps.push(state);\n }\n else {\n notHelps.push(state);\n }\n }\n if (helps.length > 0) {\n notHelps.push({\n ...basicHelpState,\n path: findCommonPrefix(...helps.map(state => state.path)),\n options: helps.reduce((options, state) => options.concat(state.options), []),\n });\n }\n return notHelps;\n}\nfunction findCommonPrefix(firstPath, secondPath, ...rest) {\n if (secondPath === undefined)\n return Array.from(firstPath);\n return findCommonPrefix(firstPath.filter((segment, i) => segment === secondPath[i]), ...rest);\n}\nfunction makeNode() {\n return {\n dynamics: [],\n shortcuts: [],\n statics: {},\n };\n}\nfunction isTerminalNode(node) {\n return node === NodeType.SuccessNode || node === NodeType.ErrorNode;\n}\nfunction cloneTransition(input, offset = 0) {\n const to = !isTerminalNode(input.to)\n ? input.to >= NodeType.CustomNode\n ? input.to + offset - NodeType.CustomNode + 1\n : input.to + offset\n : input.to;\n return {\n to,\n reducer: input.reducer,\n };\n}\nfunction cloneNode(input, offset = 0) {\n const output = makeNode();\n for (const [test, transition] of input.dynamics)\n output.dynamics.push([test, cloneTransition(transition, offset)]);\n for (const transition of input.shortcuts)\n output.shortcuts.push(cloneTransition(transition, offset));\n for (const [segment, transitions] of Object.entries(input.statics))\n output.statics[segment] = transitions.map(transition => cloneTransition(transition, offset));\n return output;\n}\nfunction registerDynamic(machine, from, test, to, reducer) {\n machine.nodes[from].dynamics.push([\n test,\n { to, reducer: reducer },\n ]);\n}\nfunction registerShortcut(machine, from, to, reducer) {\n machine.nodes[from].shortcuts.push({ to, reducer: reducer });\n}\nfunction registerStatic(machine, from, test, to, reducer) {\n const store = !Object.prototype.hasOwnProperty.call(machine.nodes[from].statics, test)\n ? machine.nodes[from].statics[test] = []\n : machine.nodes[from].statics[test];\n store.push({ to, reducer: reducer });\n}\nfunction execute(store, callback, state, segment, segmentIndex) {\n // TypeScript's control flow can't properly narrow\n // generic conditionals for some mysterious reason\n if (Array.isArray(callback)) {\n const [name, ...args] = callback;\n return store[name](state, segment, segmentIndex, ...args);\n }\n else {\n return store[callback](state, segment, segmentIndex);\n }\n}\nconst tests = {\n always: () => {\n return true;\n },\n isOptionLike: (state, segment) => {\n return !state.ignoreOptions && (segment !== `-` && segment.startsWith(`-`));\n },\n isNotOptionLike: (state, segment) => {\n return state.ignoreOptions || segment === `-` || !segment.startsWith(`-`);\n },\n isOption: (state, segment, segmentIndex, name) => {\n return !state.ignoreOptions && segment === name;\n },\n isBatchOption: (state, segment, segmentIndex, names) => {\n return !state.ignoreOptions && BATCH_REGEX.test(segment) && [...segment.slice(1)].every(name => names.has(`-${name}`));\n },\n isBoundOption: (state, segment, segmentIndex, names, options) => {\n const optionParsing = segment.match(BINDING_REGEX);\n return !state.ignoreOptions && !!optionParsing && OPTION_REGEX.test(optionParsing[1]) && names.has(optionParsing[1])\n // Disallow bound options with no arguments (i.e. booleans)\n && options.filter(opt => opt.nameSet.includes(optionParsing[1])).every(opt => opt.allowBinding);\n },\n isNegatedOption: (state, segment, segmentIndex, name) => {\n return !state.ignoreOptions && segment === `--no-${name.slice(2)}`;\n },\n isHelp: (state, segment) => {\n return !state.ignoreOptions && HELP_REGEX.test(segment);\n },\n isUnsupportedOption: (state, segment, segmentIndex, names) => {\n return !state.ignoreOptions && segment.startsWith(`-`) && OPTION_REGEX.test(segment) && !names.has(segment);\n },\n isInvalidOption: (state, segment) => {\n return !state.ignoreOptions && segment.startsWith(`-`) && !OPTION_REGEX.test(segment);\n },\n};\nconst reducers = {\n setCandidateState: (state, segment, segmentIndex, candidateState) => {\n return { ...state, ...candidateState };\n },\n setSelectedIndex: (state, segment, segmentIndex, index) => {\n return { ...state, selectedIndex: index };\n },\n pushBatch: (state, segment, segmentIndex, names) => {\n const options = state.options.slice();\n const tokens = state.tokens.slice();\n for (let t = 1; t < segment.length; ++t) {\n const name = names.get(`-${segment[t]}`);\n const slice = t === 1 ? [0, 2] : [t, t + 1];\n options.push({ name, value: true });\n tokens.push({ segmentIndex, type: `option`, option: name, slice });\n }\n return { ...state, options, tokens };\n },\n pushBound: (state, segment, segmentIndex) => {\n const [, name, value] = segment.match(BINDING_REGEX);\n const options = state.options.concat({ name, value });\n const tokens = state.tokens.concat([\n { segmentIndex, type: `option`, slice: [0, name.length], option: name },\n { segmentIndex, type: `assign`, slice: [name.length, name.length + 1] },\n { segmentIndex, type: `value`, slice: [name.length + 1, name.length + value.length + 1] },\n ]);\n return { ...state, options, tokens };\n },\n pushPath: (state, segment, segmentIndex) => {\n const path = state.path.concat(segment);\n const tokens = state.tokens.concat({ segmentIndex, type: `path` });\n return { ...state, path, tokens };\n },\n pushPositional: (state, segment, segmentIndex) => {\n const positionals = state.positionals.concat({ value: segment, extra: false });\n const tokens = state.tokens.concat({ segmentIndex, type: `positional` });\n return { ...state, positionals, tokens };\n },\n pushExtra: (state, segment, segmentIndex) => {\n const positionals = state.positionals.concat({ value: segment, extra: true });\n const tokens = state.tokens.concat({ segmentIndex, type: `positional` });\n return { ...state, positionals, tokens };\n },\n pushExtraNoLimits: (state, segment, segmentIndex) => {\n const positionals = state.positionals.concat({ value: segment, extra: NoLimits });\n const tokens = state.tokens.concat({ segmentIndex, type: `positional` });\n return { ...state, positionals, tokens };\n },\n pushTrue: (state, segment, segmentIndex, name) => {\n const options = state.options.concat({ name, value: true });\n const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: name });\n return { ...state, options, tokens };\n },\n pushFalse: (state, segment, segmentIndex, name) => {\n const options = state.options.concat({ name, value: false });\n const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: name });\n return { ...state, options, tokens };\n },\n pushUndefined: (state, segment, segmentIndex, name) => {\n const options = state.options.concat({ name: segment, value: undefined });\n const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: segment });\n return { ...state, options, tokens };\n },\n pushStringValue: (state, segment, segmentIndex) => {\n var _a;\n const lastOption = state.options[state.options.length - 1];\n const options = state.options.slice();\n const tokens = state.tokens.concat({ segmentIndex, type: `value` });\n lastOption.value = ((_a = lastOption.value) !== null && _a !== void 0 ? _a : []).concat([segment]);\n return { ...state, options, tokens };\n },\n setStringValue: (state, segment, segmentIndex) => {\n const lastOption = state.options[state.options.length - 1];\n const options = state.options.slice();\n const tokens = state.tokens.concat({ segmentIndex, type: `value` });\n lastOption.value = segment;\n return { ...state, options, tokens };\n },\n inhibateOptions: (state) => {\n return { ...state, ignoreOptions: true };\n },\n useHelp: (state, segment, segmentIndex, command) => {\n const [, /* name */ , index] = segment.match(HELP_REGEX);\n if (typeof index !== `undefined`) {\n return { ...state, options: [{ name: `-c`, value: String(command) }, { name: `-i`, value: index }] };\n }\n else {\n return { ...state, options: [{ name: `-c`, value: String(command) }] };\n }\n },\n setError: (state, segment, segmentIndex, errorMessage) => {\n if (segment === SpecialToken.EndOfInput || segment === SpecialToken.EndOfPartialInput) {\n return { ...state, errorMessage: `${errorMessage}.` };\n }\n else {\n return { ...state, errorMessage: `${errorMessage} (\"${segment}\").` };\n }\n },\n setOptionArityError: (state, segment) => {\n const lastOption = state.options[state.options.length - 1];\n return { ...state, errorMessage: `Not enough arguments to option ${lastOption.name}.` };\n },\n};\n// ------------------------------------------------------------------------\nconst NoLimits = Symbol();\nclass CommandBuilder {\n constructor(cliIndex, cliOpts) {\n this.allOptionNames = new Map();\n this.arity = { leading: [], trailing: [], extra: [], proxy: false };\n this.options = [];\n this.paths = [];\n this.cliIndex = cliIndex;\n this.cliOpts = cliOpts;\n }\n addPath(path) {\n this.paths.push(path);\n }\n setArity({ leading = this.arity.leading, trailing = this.arity.trailing, extra = this.arity.extra, proxy = this.arity.proxy }) {\n Object.assign(this.arity, { leading, trailing, extra, proxy });\n }\n addPositional({ name = `arg`, required = true } = {}) {\n if (!required && this.arity.extra === NoLimits)\n throw new Error(`Optional parameters cannot be declared when using .rest() or .proxy()`);\n if (!required && this.arity.trailing.length > 0)\n throw new Error(`Optional parameters cannot be declared after the required trailing positional arguments`);\n if (!required && this.arity.extra !== NoLimits) {\n this.arity.extra.push(name);\n }\n else if (this.arity.extra !== NoLimits && this.arity.extra.length === 0) {\n this.arity.leading.push(name);\n }\n else {\n this.arity.trailing.push(name);\n }\n }\n addRest({ name = `arg`, required = 0 } = {}) {\n if (this.arity.extra === NoLimits)\n throw new Error(`Infinite lists cannot be declared multiple times in the same command`);\n if (this.arity.trailing.length > 0)\n throw new Error(`Infinite lists cannot be declared after the required trailing positional arguments`);\n for (let t = 0; t < required; ++t)\n this.addPositional({ name });\n this.arity.extra = NoLimits;\n }\n addProxy({ required = 0 } = {}) {\n this.addRest({ required });\n this.arity.proxy = true;\n }\n addOption({ names: nameSet, description, arity = 0, hidden = false, required = false, allowBinding = true }) {\n if (!allowBinding && arity > 1)\n throw new Error(`The arity cannot be higher than 1 when the option only supports the --arg=value syntax`);\n if (!Number.isInteger(arity))\n throw new Error(`The arity must be an integer, got ${arity}`);\n if (arity < 0)\n throw new Error(`The arity must be positive, got ${arity}`);\n const preferredName = nameSet.reduce((longestName, name) => {\n return name.length > longestName.length ? name : longestName;\n }, ``);\n for (const name of nameSet)\n this.allOptionNames.set(name, preferredName);\n this.options.push({ preferredName, nameSet, description, arity, hidden, required, allowBinding });\n }\n setContext(context) {\n this.context = context;\n }\n usage({ detailed = true, inlineOptions = true } = {}) {\n const segments = [this.cliOpts.binaryName];\n const detailedOptionList = [];\n if (this.paths.length > 0)\n segments.push(...this.paths[0]);\n if (detailed) {\n for (const { preferredName, nameSet, arity, hidden, description, required } of this.options) {\n if (hidden)\n continue;\n const args = [];\n for (let t = 0; t < arity; ++t)\n args.push(` #${t}`);\n const definition = `${nameSet.join(`,`)}${args.join(``)}`;\n if (!inlineOptions && description) {\n detailedOptionList.push({ preferredName, nameSet, definition, description, required });\n }\n else {\n segments.push(required ? `<${definition}>` : `[${definition}]`);\n }\n }\n segments.push(...this.arity.leading.map(name => `<${name}>`));\n if (this.arity.extra === NoLimits)\n segments.push(`...`);\n else\n segments.push(...this.arity.extra.map(name => `[${name}]`));\n segments.push(...this.arity.trailing.map(name => `<${name}>`));\n }\n const usage = segments.join(` `);\n return { usage, options: detailedOptionList };\n }\n compile() {\n if (typeof this.context === `undefined`)\n throw new Error(`Assertion failed: No context attached`);\n const machine = makeStateMachine();\n let firstNode = NodeType.InitialNode;\n const candidateUsage = this.usage().usage;\n const requiredOptions = this.options\n .filter(opt => opt.required)\n .map(opt => opt.nameSet);\n firstNode = injectNode(machine, makeNode());\n registerStatic(machine, NodeType.InitialNode, SpecialToken.StartOfInput, firstNode, [`setCandidateState`, { candidateUsage, requiredOptions }]);\n const positionalArgument = this.arity.proxy\n ? `always`\n : `isNotOptionLike`;\n const paths = this.paths.length > 0\n ? this.paths\n : [[]];\n for (const path of paths) {\n let lastPathNode = firstNode;\n // We allow options to be specified before the path. Note that we\n // only do this when there is a path, otherwise there would be\n // some redundancy with the options attached later.\n if (path.length > 0) {\n const optionPathNode = injectNode(machine, makeNode());\n registerShortcut(machine, lastPathNode, optionPathNode);\n this.registerOptions(machine, optionPathNode);\n lastPathNode = optionPathNode;\n }\n for (let t = 0; t < path.length; ++t) {\n const nextPathNode = injectNode(machine, makeNode());\n registerStatic(machine, lastPathNode, path[t], nextPathNode, `pushPath`);\n lastPathNode = nextPathNode;\n if (t + 1 < path.length) {\n // Allow to pass `-h` (without anything after it) after each part of a path.\n // Note that we do not do this for the last part, otherwise there would be\n // some redundancy with the `useHelp` attached later.\n const helpNode = injectNode(machine, makeNode());\n registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]);\n registerStatic(machine, helpNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, HELP_COMMAND_INDEX]);\n }\n }\n if (this.arity.leading.length > 0 || !this.arity.proxy) {\n const helpNode = injectNode(machine, makeNode());\n registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]);\n registerDynamic(machine, helpNode, `always`, helpNode, `pushExtra`);\n registerStatic(machine, helpNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, HELP_COMMAND_INDEX]);\n this.registerOptions(machine, lastPathNode);\n }\n if (this.arity.leading.length > 0) {\n registerStatic(machine, lastPathNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, lastPathNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n let lastLeadingNode = lastPathNode;\n for (let t = 0; t < this.arity.leading.length; ++t) {\n const nextLeadingNode = injectNode(machine, makeNode());\n if (!this.arity.proxy || t + 1 !== this.arity.leading.length)\n this.registerOptions(machine, nextLeadingNode);\n if (this.arity.trailing.length > 0 || t + 1 !== this.arity.leading.length) {\n registerStatic(machine, nextLeadingNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, nextLeadingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n registerDynamic(machine, lastLeadingNode, `isNotOptionLike`, nextLeadingNode, `pushPositional`);\n lastLeadingNode = nextLeadingNode;\n }\n let lastExtraNode = lastLeadingNode;\n if (this.arity.extra === NoLimits || this.arity.extra.length > 0) {\n const extraShortcutNode = injectNode(machine, makeNode());\n registerShortcut(machine, lastLeadingNode, extraShortcutNode);\n if (this.arity.extra === NoLimits) {\n const extraNode = injectNode(machine, makeNode());\n if (!this.arity.proxy)\n this.registerOptions(machine, extraNode);\n registerDynamic(machine, lastLeadingNode, positionalArgument, extraNode, `pushExtraNoLimits`);\n registerDynamic(machine, extraNode, positionalArgument, extraNode, `pushExtraNoLimits`);\n registerShortcut(machine, extraNode, extraShortcutNode);\n }\n else {\n for (let t = 0; t < this.arity.extra.length; ++t) {\n const nextExtraNode = injectNode(machine, makeNode());\n if (!this.arity.proxy || t > 0)\n this.registerOptions(machine, nextExtraNode);\n registerDynamic(machine, lastExtraNode, positionalArgument, nextExtraNode, `pushExtra`);\n registerShortcut(machine, nextExtraNode, extraShortcutNode);\n lastExtraNode = nextExtraNode;\n }\n }\n lastExtraNode = extraShortcutNode;\n }\n if (this.arity.trailing.length > 0) {\n registerStatic(machine, lastExtraNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, lastExtraNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n let lastTrailingNode = lastExtraNode;\n for (let t = 0; t < this.arity.trailing.length; ++t) {\n const nextTrailingNode = injectNode(machine, makeNode());\n if (!this.arity.proxy)\n this.registerOptions(machine, nextTrailingNode);\n if (t + 1 < this.arity.trailing.length) {\n registerStatic(machine, nextTrailingNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, nextTrailingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n registerDynamic(machine, lastTrailingNode, `isNotOptionLike`, nextTrailingNode, `pushPositional`);\n lastTrailingNode = nextTrailingNode;\n }\n registerDynamic(machine, lastTrailingNode, positionalArgument, NodeType.ErrorNode, [`setError`, `Extraneous positional argument`]);\n registerStatic(machine, lastTrailingNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n registerStatic(machine, lastTrailingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n return {\n machine,\n context: this.context,\n };\n }\n registerOptions(machine, node) {\n registerDynamic(machine, node, [`isOption`, `--`], node, `inhibateOptions`);\n registerDynamic(machine, node, [`isBatchOption`, this.allOptionNames], node, [`pushBatch`, this.allOptionNames]);\n registerDynamic(machine, node, [`isBoundOption`, this.allOptionNames, this.options], node, `pushBound`);\n registerDynamic(machine, node, [`isUnsupportedOption`, this.allOptionNames], NodeType.ErrorNode, [`setError`, `Unsupported option name`]);\n registerDynamic(machine, node, [`isInvalidOption`], NodeType.ErrorNode, [`setError`, `Invalid option name`]);\n for (const option of this.options) {\n if (option.arity === 0) {\n for (const name of option.nameSet) {\n registerDynamic(machine, node, [`isOption`, name], node, [`pushTrue`, option.preferredName]);\n if (name.startsWith(`--`) && !name.startsWith(`--no-`)) {\n registerDynamic(machine, node, [`isNegatedOption`, name], node, [`pushFalse`, option.preferredName]);\n }\n }\n }\n else {\n // We inject a new node at the end of the state machine\n let lastNode = injectNode(machine, makeNode());\n // We register transitions from the starting node to this new node\n for (const name of option.nameSet)\n registerDynamic(machine, node, [`isOption`, name], lastNode, [`pushUndefined`, option.preferredName]);\n // For each argument, we inject a new node at the end and we\n // register a transition from the current node to this new node\n for (let t = 0; t < option.arity; ++t) {\n const nextNode = injectNode(machine, makeNode());\n // We can provide better errors when another option or EndOfInput is encountered\n registerStatic(machine, lastNode, SpecialToken.EndOfInput, NodeType.ErrorNode, `setOptionArityError`);\n registerStatic(machine, lastNode, SpecialToken.EndOfPartialInput, NodeType.ErrorNode, `setOptionArityError`);\n registerDynamic(machine, lastNode, `isOptionLike`, NodeType.ErrorNode, `setOptionArityError`);\n // If the option has a single argument, no need to store it in an array\n const action = option.arity === 1\n ? `setStringValue`\n : `pushStringValue`;\n registerDynamic(machine, lastNode, `isNotOptionLike`, nextNode, action);\n lastNode = nextNode;\n }\n // In the end, we register a shortcut from\n // the last node back to the starting node\n registerShortcut(machine, lastNode, node);\n }\n }\n }\n}\nclass CliBuilder {\n constructor({ binaryName = `...` } = {}) {\n this.builders = [];\n this.opts = { binaryName };\n }\n static build(cbs, opts = {}) {\n return new CliBuilder(opts).commands(cbs).compile();\n }\n getBuilderByIndex(n) {\n if (!(n >= 0 && n < this.builders.length))\n throw new Error(`Assertion failed: Out-of-bound command index (${n})`);\n return this.builders[n];\n }\n commands(cbs) {\n for (const cb of cbs)\n cb(this.command());\n return this;\n }\n command() {\n const builder = new CommandBuilder(this.builders.length, this.opts);\n this.builders.push(builder);\n return builder;\n }\n compile() {\n const machines = [];\n const contexts = [];\n for (const builder of this.builders) {\n const { machine, context } = builder.compile();\n machines.push(machine);\n contexts.push(context);\n }\n const machine = makeAnyOfMachine(machines);\n simplifyMachine(machine);\n return {\n machine,\n contexts,\n process: (input, { partial } = {}) => {\n const endToken = partial\n ? SpecialToken.EndOfPartialInput\n : SpecialToken.EndOfInput;\n return runMachine(machine, input, { endToken });\n },\n };\n }\n}\n\nexport { CliBuilder, CommandBuilder, NoLimits, aggregateHelpStates, cloneNode, cloneTransition, debug, debugMachine, execute, injectNode, isTerminalNode, makeAnyOfMachine, makeNode, makeStateMachine, reducers, registerDynamic, registerShortcut, registerStatic, runMachineInternal, selectBestState, simplifyMachine, tests, trimSmallerBranches };\n","import { Command } from './Command.mjs';\n\nclass HelpCommand extends Command {\n constructor(contexts) {\n super();\n this.contexts = contexts;\n this.commands = [];\n }\n static from(state, contexts) {\n const command = new HelpCommand(contexts);\n command.path = state.path;\n for (const opt of state.options) {\n switch (opt.name) {\n case `-c`:\n {\n command.commands.push(Number(opt.value));\n }\n break;\n case `-i`:\n {\n command.index = Number(opt.value);\n }\n break;\n }\n }\n return command;\n }\n async execute() {\n let commands = this.commands;\n if (typeof this.index !== `undefined` && this.index >= 0 && this.index < commands.length)\n commands = [commands[this.index]];\n if (commands.length === 0) {\n this.context.stdout.write(this.cli.usage());\n }\n else if (commands.length === 1) {\n this.context.stdout.write(this.cli.usage(this.contexts[commands[0]].commandClass, { detailed: true }));\n }\n else if (commands.length > 1) {\n this.context.stdout.write(`Multiple commands match your selection:\\n`);\n this.context.stdout.write(`\\n`);\n let index = 0;\n for (const command of this.commands)\n this.context.stdout.write(this.cli.usage(this.contexts[command].commandClass, { prefix: `${index++}. `.padStart(5) }));\n this.context.stdout.write(`\\n`);\n this.context.stdout.write(`Run again with -h=<index> to see the longer details of any of those commands.\\n`);\n }\n }\n}\n\nexport { HelpCommand };\n","import { HELP_COMMAND_INDEX } from '../constants.mjs';\nimport { CliBuilder } from '../core.mjs';\nimport { formatMarkdownish, richFormat, textFormat } from '../format.mjs';\nimport { getCaptureActivator, getDefaultColorDepth } from '../platform/node.mjs';\nimport { Command } from './Command.mjs';\nimport { HelpCommand } from './HelpCommand.mjs';\n\nconst errorCommandSymbol = Symbol(`clipanion/errorCommand`);\nasync function runExit(...args) {\n const { resolvedOptions, resolvedCommandClasses, resolvedArgv, resolvedContext, } = resolveRunParameters(args);\n const cli = Cli.from(resolvedCommandClasses, resolvedOptions);\n return cli.runExit(resolvedArgv, resolvedContext);\n}\nasync function run(...args) {\n const { resolvedOptions, resolvedCommandClasses, resolvedArgv, resolvedContext, } = resolveRunParameters(args);\n const cli = Cli.from(resolvedCommandClasses, resolvedOptions);\n return cli.run(resolvedArgv, resolvedContext);\n}\nfunction resolveRunParameters(args) {\n let resolvedOptions;\n let resolvedCommandClasses;\n let resolvedArgv;\n let resolvedContext;\n if (typeof process !== `undefined` && typeof process.argv !== `undefined`)\n resolvedArgv = process.argv.slice(2);\n switch (args.length) {\n case 1:\n {\n resolvedCommandClasses = args[0];\n }\n break;\n case 2:\n {\n if (args[0] && (args[0].prototype instanceof Command) || Array.isArray(args[0])) {\n resolvedCommandClasses = args[0];\n if (Array.isArray(args[1])) {\n resolvedArgv = args[1];\n }\n else {\n resolvedContext = args[1];\n }\n }\n else {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n }\n }\n break;\n case 3:\n {\n if (Array.isArray(args[2])) {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n resolvedArgv = args[2];\n }\n else if (args[0] && (args[0].prototype instanceof Command) || Array.isArray(args[0])) {\n resolvedCommandClasses = args[0];\n resolvedArgv = args[1];\n resolvedContext = args[2];\n }\n else {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n resolvedContext = args[2];\n }\n }\n break;\n default:\n {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n resolvedArgv = args[2];\n resolvedContext = args[3];\n }\n break;\n }\n if (typeof resolvedArgv === `undefined`)\n throw new Error(`The argv parameter must be provided when running Clipanion outside of a Node context`);\n return {\n resolvedOptions,\n resolvedCommandClasses,\n resolvedArgv,\n resolvedContext,\n };\n}\n/**\n * @template Context The context shared by all commands. Contexts are a set of values, defined when calling the `run`/`runExit` functions from the CLI instance, that will be made available to the commands via `this.context`.\n */\nclass Cli {\n constructor({ binaryLabel, binaryName: binaryNameOpt = `...`, binaryVersion, enableCapture = false, enableColors } = {}) {\n this.registrations = new Map();\n this.builder = new CliBuilder({ binaryName: binaryNameOpt });\n this.binaryLabel = binaryLabel;\n this.binaryName = binaryNameOpt;\n this.binaryVersion = binaryVersion;\n this.enableCapture = enableCapture;\n this.enableColors = enableColors;\n }\n /**\n * Creates a new Cli and registers all commands passed as parameters.\n *\n * @param commandClasses The Commands to register\n * @returns The created `Cli` instance\n */\n static from(commandClasses, options = {}) {\n const cli = new Cli(options);\n const resolvedCommandClasses = Array.isArray(commandClasses)\n ? commandClasses\n : [commandClasses];\n for (const commandClass of resolvedCommandClasses)\n cli.register(commandClass);\n return cli;\n }\n /**\n * Registers a command inside the CLI.\n */\n register(commandClass) {\n var _a;\n const specs = new Map();\n const command = new commandClass();\n for (const key in command) {\n const value = command[key];\n if (typeof value === `object` && value !== null && value[Command.isOption]) {\n specs.set(key, value);\n }\n }\n const builder = this.builder.command();\n const index = builder.cliIndex;\n const paths = (_a = commandClass.paths) !== null && _a !== void 0 ? _a : command.paths;\n if (typeof paths !== `undefined`)\n for (const path of paths)\n builder.addPath(path);\n this.registrations.set(commandClass, { specs, builder, index });\n for (const [key, { definition }] of specs.entries())\n definition(builder, key);\n builder.setContext({\n commandClass,\n });\n }\n process(opts, contextArg) {\n const { input, context: userContext, partial } = typeof opts === `object` && Array.isArray(opts)\n ? { input: opts, context: contextArg }\n : opts;\n const { contexts, process } = this.builder.compile();\n const state = process(input, { partial });\n const context = {\n ...Cli.defaultContext,\n ...userContext,\n };\n switch (state.selectedIndex) {\n case HELP_COMMAND_INDEX:\n {\n const command = HelpCommand.from(state, contexts);\n command.context = context;\n command.tokens = state.tokens;\n return command;\n }\n default:\n {\n const { commandClass } = contexts[state.selectedIndex];\n const record = this.registrations.get(commandClass);\n if (typeof record === `undefined`)\n throw new Error(`Assertion failed: Expected the command class to have been registered.`);\n const command = new commandClass();\n command.context = context;\n command.tokens = state.tokens;\n command.path = state.path;\n try {\n for (const [key, { transformer }] of record.specs.entries())\n command[key] = transformer(record.builder, key, state, context);\n return command;\n }\n catch (error) {\n error[errorCommandSymbol] = command;\n throw error;\n }\n }\n break;\n }\n }\n async run(input, userContext) {\n var _a, _b;\n let command;\n const context = {\n ...Cli.defaultContext,\n ...userContext,\n };\n const colored = (_a = this.enableColors) !== null && _a !== void 0 ? _a : context.colorDepth > 1;\n if (!Array.isArray(input)) {\n command = input;\n }\n else {\n try {\n command = this.process(input, context);\n }\n catch (error) {\n context.stdout.write(this.error(error, { colored }));\n return 1;\n }\n }\n if (command.help) {\n context.stdout.write(this.usage(command, { colored, detailed: true }));\n return 0;\n }\n command.context = context;\n command.cli = {\n binaryLabel: this.binaryLabel,\n binaryName: this.binaryName,\n binaryVersion: this.binaryVersion,\n enableCapture: this.enableCapture,\n enableColors: this.enableColors,\n definitions: () => this.definitions(),\n definition: command => this.definition(command),\n error: (error, opts) => this.error(error, opts),\n format: colored => this.format(colored),\n process: (input, subContext) => this.process(input, { ...context, ...subContext }),\n run: (input, subContext) => this.run(input, { ...context, ...subContext }),\n usage: (command, opts) => this.usage(command, opts),\n };\n const activate = this.enableCapture\n ? (_b = getCaptureActivator(context)) !== null && _b !== void 0 ? _b : noopCaptureActivator\n : noopCaptureActivator;\n let exitCode;\n try {\n exitCode = await activate(() => command.validateAndExecute().catch(error => command.catch(error).then(() => 0)));\n }\n catch (error) {\n context.stdout.write(this.error(error, { colored, command }));\n return 1;\n }\n return exitCode;\n }\n async runExit(input, context) {\n process.exitCode = await this.run(input, context);\n }\n definition(commandClass, { colored = false } = {}) {\n if (!commandClass.usage)\n return null;\n const { usage: path } = this.getUsageByRegistration(commandClass, { detailed: false });\n const { usage, options } = this.getUsageByRegistration(commandClass, { detailed: true, inlineOptions: false });\n const category = typeof commandClass.usage.category !== `undefined`\n ? formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false })\n : undefined;\n const description = typeof commandClass.usage.description !== `undefined`\n ? formatMarkdownish(commandClass.usage.description, { format: this.format(colored), paragraphs: false })\n : undefined;\n const details = typeof commandClass.usage.details !== `undefined`\n ? formatMarkdownish(commandClass.usage.details, { format: this.format(colored), paragraphs: true })\n : undefined;\n const examples = typeof commandClass.usage.examples !== `undefined`\n ? commandClass.usage.examples.map(([label, cli]) => [formatMarkdownish(label, { format: this.format(colored), paragraphs: false }), cli.replace(/\\$0/g, this.binaryName)])\n : undefined;\n return { path, usage, category, description, details, examples, options };\n }\n definitions({ colored = false } = {}) {\n const data = [];\n for (const commandClass of this.registrations.keys()) {\n const usage = this.definition(commandClass, { colored });\n if (!usage)\n continue;\n data.push(usage);\n }\n return data;\n }\n usage(command = null, { colored, detailed = false, prefix = `$ ` } = {}) {\n var _a;\n // In case the default command is the only one, we can just show the command help rather than the general one\n if (command === null) {\n for (const commandClass of this.registrations.keys()) {\n const paths = commandClass.paths;\n const isDocumented = typeof commandClass.usage !== `undefined`;\n const isExclusivelyDefault = !paths || paths.length === 0 || (paths.length === 1 && paths[0].length === 0);\n const isDefault = isExclusivelyDefault || ((_a = paths === null || paths === void 0 ? void 0 : paths.some(path => path.length === 0)) !== null && _a !== void 0 ? _a : false);\n if (isDefault) {\n if (command) {\n command = null;\n break;\n }\n else {\n command = commandClass;\n }\n }\n else {\n if (isDocumented) {\n command = null;\n continue;\n }\n }\n }\n if (command) {\n detailed = true;\n }\n }\n // @ts-ignore\n const commandClass = command !== null && command instanceof Command\n ? command.constructor\n : command;\n let result = ``;\n if (!commandClass) {\n const commandsByCategories = new Map();\n for (const [commandClass, { index }] of this.registrations.entries()) {\n if (typeof commandClass.usage === `undefined`)\n continue;\n const category = typeof commandClass.usage.category !== `undefined`\n ? formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false })\n : null;\n let categoryCommands = commandsByCategories.get(category);\n if (typeof categoryCommands === `undefined`)\n commandsByCategories.set(category, categoryCommands = []);\n const { usage } = this.getUsageByIndex(index);\n categoryCommands.push({ commandClass, usage });\n }\n const categoryNames = Array.from(commandsByCategories.keys()).sort((a, b) => {\n if (a === null)\n return -1;\n if (b === null)\n return +1;\n return a.localeCompare(b, `en`, { usage: `sort`, caseFirst: `upper` });\n });\n const hasLabel = typeof this.binaryLabel !== `undefined`;\n const hasVersion = typeof this.binaryVersion !== `undefined`;\n if (hasLabel || hasVersion) {\n if (hasLabel && hasVersion)\n result += `${this.format(colored).header(`${this.binaryLabel} - ${this.binaryVersion}`)}\\n\\n`;\n else if (hasLabel)\n result += `${this.format(colored).header(`${this.binaryLabel}`)}\\n`;\n else\n result += `${this.format(colored).header(`${this.binaryVersion}`)}\\n`;\n result += ` ${this.format(colored).bold(prefix)}${this.binaryName} <command>\\n`;\n }\n else {\n result += `${this.format(colored).bold(prefix)}${this.binaryName} <command>\\n`;\n }\n for (const categoryName of categoryNames) {\n const commands = commandsByCategories.get(categoryName).slice().sort((a, b) => {\n return a.usage.localeCompare(b.usage, `en`, { usage: `sort`, caseFirst: `upper` });\n });\n const header = categoryName !== null\n ? categoryName.trim()\n : `General commands`;\n result += `\\n`;\n result += `${this.format(colored).header(`${header}`)}\\n`;\n for (const { commandClass, usage } of commands) {\n const doc = commandClass.usage.description || `undocumented`;\n result += `\\n`;\n result += ` ${this.format(colored).bold(usage)}\\n`;\n result += ` ${formatMarkdownish(doc, { format: this.format(colored), paragraphs: false })}`;\n }\n }\n result += `\\n`;\n result += formatMarkdownish(`You can also print more details about any of these commands by calling them with the \\`-h,--help\\` flag right after the command name.`, { format: this.format(colored), paragraphs: true });\n }\n else {\n if (!detailed) {\n const { usage } = this.getUsageByRegistration(commandClass);\n result += `${this.format(colored).bold(prefix)}${usage}\\n`;\n }\n else {\n const { description = ``, details = ``, examples = [], } = commandClass.usage || {};\n if (description !== ``) {\n result += formatMarkdownish(description, { format: this.format(colored), paragraphs: false }).replace(/^./, $0 => $0.toUpperCase());\n result += `\\n`;\n }\n if (details !== `` || examples.length > 0) {\n result += `${this.format(colored).header(`Usage`)}\\n`;\n result += `\\n`;\n }\n const { usage, options } = this.getUsageByRegistration(commandClass, { inlineOptions: false });\n result += `${this.format(colored).bold(prefix)}${usage}\\n`;\n if (options.length > 0) {\n result += `\\n`;\n result += `${this.format(colored).header(`Options`)}\\n`;\n const maxDefinitionLength = options.reduce((length, option) => {\n return Math.max(length, option.definition.length);\n }, 0);\n result += `\\n`;\n for (const { definition, description } of options) {\n result += ` ${this.format(colored).bold(definition.padEnd(maxDefinitionLength))} ${formatMarkdownish(description, { format: this.format(colored), paragraphs: false })}`;\n }\n }\n if (details !== ``) {\n result += `\\n`;\n result += `${this.format(colored).header(`Details`)}\\n`;\n result += `\\n`;\n result += formatMarkdownish(details, { format: this.format(colored), paragraphs: true });\n }\n if (examples.length > 0) {\n result += `\\n`;\n result += `${this.format(colored).header(`Examples`)}\\n`;\n for (const [description, example] of examples) {\n result += `\\n`;\n result += formatMarkdownish(description, { format: this.format(colored), paragraphs: false });\n result += `${example\n .replace(/^/m, ` ${this.format(colored).bold(prefix)}`)\n .replace(/\\$0/g, this.binaryName)}\\n`;\n }\n }\n }\n }\n return result;\n }\n error(error, _a) {\n var _b;\n var { colored, command = (_b = error[errorCommandSymbol]) !== null && _b !== void 0 ? _b : null } = _a === void 0 ? {} : _a;\n if (!error || typeof error !== `object` || !(`stack` in error))\n error = new Error(`Execution failed with a non-error rejection (rejected value: ${JSON.stringify(error)})`);\n let result = ``;\n let name = error.name.replace(/([a-z])([A-Z])/g, `$1 $2`);\n if (name === `Error`)\n name = `Internal Error`;\n result += `${this.format(colored).error(name)}: ${error.message}\\n`;\n const meta = error.clipanion;\n if (typeof meta !== `undefined`) {\n if (meta.type === `usage`) {\n result += `\\n`;\n result += this.usage(command);\n }\n }\n else {\n if (error.stack) {\n result += `${error.stack.replace(/^.*\\n/, ``)}\\n`;\n }\n }\n return result;\n }\n format(colored) {\n var _a;\n return ((_a = colored !== null && colored !== void 0 ? colored : this.enableColors) !== null && _a !== void 0 ? _a : Cli.defaultContext.colorDepth > 1) ? richFormat : textFormat;\n }\n getUsageByRegistration(klass, opts) {\n const record = this.registrations.get(klass);\n if (typeof record === `undefined`)\n throw new Error(`Assertion failed: Unregistered command`);\n return this.getUsageByIndex(record.index, opts);\n }\n getUsageByIndex(n, opts) {\n return this.builder.getBuilderByIndex(n).usage(opts);\n }\n}\n/**\n * The default context of the CLI.\n *\n * Contains the stdio of the current `process`.\n */\nCli.defaultContext = {\n env: process.env,\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n colorDepth: getDefaultColorDepth(),\n};\nfunction noopCaptureActivator(fn) {\n return fn();\n}\n\nexport { Cli, run, runExit };\n","function getDefaultColorDepth() {\n return 1;\n}\nfunction getCaptureActivator() {\n throw new Error(`The enableCapture option cannot be used from within a browser environment`);\n}\n\nexport { getCaptureActivator, getDefaultColorDepth };\n","import { makeCommandOption, rerouteArguments } from './utils.mjs';\n\nfunction Boolean(descriptor, initialValueBase, optsBase) {\n const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});\n const optNames = descriptor.split(`,`);\n const nameSet = new Set(optNames);\n return makeCommandOption({\n definition(builder) {\n builder.addOption({\n names: optNames,\n allowBinding: false,\n arity: 0,\n hidden: opts.hidden,\n description: opts.description,\n required: opts.required,\n });\n },\n transformer(builer, key, state) {\n let currentValue = initialValue;\n for (const { name, value } of state.options) {\n if (!nameSet.has(name))\n continue;\n currentValue = value;\n }\n return currentValue;\n },\n });\n}\n\nexport { Boolean };\n","import { NoLimits } from '../../core.mjs';\nimport { makeCommandOption, applyValidator, rerouteArguments } from './utils.mjs';\n\nfunction StringOption(descriptor, initialValueBase, optsBase) {\n const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});\n const { arity = 1 } = opts;\n const optNames = descriptor.split(`,`);\n const nameSet = new Set(optNames);\n return makeCommandOption({\n definition(builder) {\n builder.addOption({\n names: optNames,\n arity: opts.tolerateBoolean ? 0 : arity,\n hidden: opts.hidden,\n description: opts.description,\n required: opts.required,\n });\n },\n transformer(builder, key, state, context) {\n let usedName;\n let currentValue = initialValue;\n if (typeof opts.env !== `undefined` && context.env[opts.env]) {\n usedName = opts.env;\n currentValue = context.env[opts.env];\n }\n for (const { name, value } of state.options) {\n if (!nameSet.has(name))\n continue;\n usedName = name;\n currentValue = value;\n }\n if (typeof currentValue === `string`) {\n return applyValidator(usedName !== null && usedName !== void 0 ? usedName : key, currentValue, opts.validator);\n }\n else {\n return currentValue;\n }\n },\n });\n}\nfunction StringPositional(opts = {}) {\n const { required = true } = opts;\n return makeCommandOption({\n definition(builder, key) {\n var _a;\n builder.addPositional({\n name: (_a = opts.name) !== null && _a !== void 0 ? _a : key,\n required: opts.required,\n });\n },\n transformer(builder, key, state) {\n var _a;\n for (let i = 0; i < state.positionals.length; ++i) {\n // We skip NoLimits extras. We only care about\n // required and optional finite positionals.\n if (state.positionals[i].extra === NoLimits)\n continue;\n // We skip optional positionals when we only\n // care about required positionals.\n if (required && state.positionals[i].extra === true)\n continue;\n // We skip required positionals when we only\n // care about optional positionals.\n if (!required && state.positionals[i].extra === false)\n continue;\n // We remove the positional from the list\n const [positional] = state.positionals.splice(i, 1);\n return applyValidator((_a = opts.name) !== null && _a !== void 0 ? _a : key, positional.value, opts.validator);\n }\n return undefined;\n },\n });\n}\n// This function is badly typed, but it doesn't matter because the overloads provide the true public typings\nfunction String(descriptor, ...args) {\n if (typeof descriptor === `string`) {\n return StringOption(descriptor, ...args);\n }\n else {\n return StringPositional(descriptor);\n }\n}\n\nexport { String };\n","export const enum TadaErrorCode {\n VUE_SUPPORT,\n SVELTE_SUPPORT,\n UNKNOWN_EXTERNAL_FILE,\n}\n\nexport class TadaError extends Error {\n static isTadaError(error: unknown): error is TadaError {\n return !!(typeof error === 'object' && error && 'name' in error && error.name === 'TadaError');\n }\n\n readonly code: TadaErrorCode;\n constructor(code: TadaErrorCode, message: string) {\n super(message);\n this.code = code;\n this.name = 'TadaError';\n }\n}\n\nexport const exitCode = () => {\n const { exitCode } = process;\n return typeof exitCode === 'string' ? parseInt(exitCode, 10) || 0 : exitCode;\n};\n","let hasColor = false;\n\nexport function _setColor(color: boolean) {\n hasColor = color;\n}\n\n// See: http://xtermjs.org/docs/api/vtfeatures/#csi\nconst enum CSI {\n InsertChars = '@',\n ScrollLeft = 'SP@',\n Up = 'A',\n ScrollRight = 'SPA',\n Down = 'B',\n Forward = 'C',\n Backward = 'D',\n NextLine = 'E',\n PrevLine = 'F',\n ToColumn = 'G',\n ToPosition = 'H',\n Tab = 'I',\n Erase = 'J',\n EraseLine = 'K',\n InsertLines = 'L',\n DeleteLines = 'M',\n DeleteChars = 'P',\n ScrollUp = 'S',\n ScrollDown = 'T',\n EraseChars = 'X',\n TabBackwards = 'Z',\n RepeatChar = 'b',\n ToRow = 'd',\n DownLine = 'e',\n TabClear = 'g',\n SetMode = 'h',\n UnsetMode = 'l',\n SetPrivateMode = '?h',\n UnsetPrivateMode = '?l',\n ResetPrivateMode = '?r',\n Style = 'm',\n Reset = '!p',\n Protect = '\"q',\n Cursor = 'SPq',\n SetMargin = 'r',\n SaveCursor = 's',\n RestoreCursor = 'u',\n InsertColumns = \"'}\",\n DeleteColumns = \"'~\",\n}\n\nconst enum TabClear {\n Current = 0,\n All = 3,\n}\n\nconst enum Erase {\n Forward = 0,\n Backward = 1,\n All = 2,\n Scrollback = 3,\n}\n\nconst enum EraseLine {\n Forward = 0,\n Backward = 1,\n All = 2,\n}\n\nconst enum Protect {\n Insert = 4,\n AutomaticNewline = 20,\n}\n\nconst enum Mode {\n Insert = 4,\n AutomaticNewline = 20,\n}\n\nconst enum PrivateMode {\n AppCursorKeys = 1,\n USASCII = 2,\n Column132 = 3,\n OriginMode = 6,\n AutoWrap = 7,\n AutoRepeat = 8,\n X10Mouse = 9,\n BlinkCursor = 12,\n ShowCursor = 25,\n ReverseWrapAround = 45,\n AlternativeScreenBuffer = 47,\n AppKeypad = 66,\n X11Mouse = 1000,\n CellMotionMouseTracking = 1002,\n AllMotionMouseTracking = 1003,\n FocusEvents = 1004,\n Utf8Mouse = 1005,\n SGRMouse = 1006,\n UrxvtMouse = 1015,\n SGRPixelsMouse = 1016,\n SaveCursor = 1048,\n BracketedPaste = 2004,\n}\n\nconst enum Cursor {\n Empty = 0,\n Block = 1,\n BlinkBlock = 2,\n Underline = 3,\n BlinkUnderline = 4,\n Bar = 5,\n BlinkBar = 6,\n}\n\nconst enum Style {\n Reset = 0,\n Bold = 1,\n Faint = 2,\n Italic = 3,\n Underline = 4,\n Blink = 5,\n RapidBlink = 6,\n Invert = 7,\n Invisible = 8,\n Strikethrough = 9,\n DoubleUnderlined = 21,\n Normal = 22, // No Bold, No Faint\n NoItalic = 23,\n NoUnderline = 24,\n NoBlink = 25,\n NoInvert = 27,\n Visible = 28,\n NoStrikethrough = 29,\n\n Black = 30,\n Red = 31,\n Green = 32,\n Yellow = 33,\n Blue = 34,\n Magenta = 35,\n Cyan = 36,\n White = 37,\n Foreground = 39,\n\n OnBlack = 40,\n OnRed = 41,\n OnGreen = 42,\n OnYellow = 43,\n OnBlue = 44,\n OnMagenta = 45,\n OnCyan = 46,\n OnWhite = 47,\n OnBackground = 49,\n\n BrightBlack = 90,\n BrightRed = 91,\n BrightGreen = 92,\n BrightYellow = 93,\n BrightBlue = 94,\n BrightMagenta = 95,\n BrightCyan = 96,\n BrightWhite = 97,\n\n OnBrightBlack = 100,\n OnBrightRed = 101,\n OnBrightGreen = 102,\n OnBrightYellow = 103,\n OnBrightBlue = 104,\n OnBrightMagenta = 105,\n OnBrightCyan = 106,\n OnBrightWhite = 107,\n\n DoubleUnderline = '4:2',\n CurlyUnderline = '4:3',\n DottedUnderline = '4:4',\n DashedUnderline = '4:5',\n}\n\ntype escapeCSI = '\\x1B[';\nconst escapeCSI = '\\x1B[';\n\ntype CommandNoParam = CSI.Reset | CSI.SaveCursor | CSI.RestoreCursor | CSI.ResetPrivateMode;\n\ntype CommandSingleParam =\n | CSI.ScrollLeft\n | CSI.ScrollRight\n | CSI.ScrollUp\n | CSI.ScrollDown\n | CSI.Up\n | CSI.Down\n | CSI.Backward\n | CSI.Forward\n | CSI.PrevLine\n | CSI.NextLine\n | CSI.DownLine\n | CSI.ToColumn\n | CSI.ToRow\n | CSI.Tab\n | CSI.TabBackwards\n | CSI.InsertChars\n | CSI.InsertLines\n | CSI.InsertColumns\n | CSI.DeleteChars\n | CSI.DeleteLines\n | CSI.DeleteColumns\n | CSI.RepeatChar;\n\ntype CommandParam =\n | number\n | TabClear\n | Erase\n | EraseLine\n | Protect\n | Cursor\n | Mode\n | PrivateMode\n | Style\n | readonly Mode[]\n | readonly PrivateMode[]\n | readonly Style[];\n\nfunction cmd(code: CommandNoParam): `${escapeCSI}${CommandNoParam}`;\nfunction cmd(\n code: CommandSingleParam,\n count?: number\n): `${escapeCSI}${number}${CommandSingleParam}`;\nfunction cmd(code: CSI.TabClear, mode?: TabClear): `${escapeCSI}${TabClear}${CSI.TabClear}`;\nfunction cmd(code: CSI.Erase, mode?: Erase): `${escapeCSI}${Erase}${CSI.Erase}`;\nfunction cmd(code: CSI.EraseLine, mode?: EraseLine): `${escapeCSI}${EraseLine}${CSI.EraseLine}`;\nfunction cmd(code: CSI.Protect, mode?: Protect): `${escapeCSI}${Protect}${CSI.Protect}`;\nfunction cmd(code: CSI.Cursor, style: Cursor): `${escapeCSI}${Cursor}${CSI.Cursor}`;\n\nfunction cmd(\n code: CSI.ToPosition,\n row: number,\n column: number\n): `${escapeCSI}${number};${number}${CSI.ToPosition}`;\n\nfunction cmd(\n code: CSI.SetMargin,\n top: number,\n bottom: number\n): `${escapeCSI}${number};${number}${CSI.SetMargin}`;\n\nfunction cmd(code: CSI.SetMode, modes: Mode | readonly Mode[]): `${escapeCSI}${Mode}${CSI.SetMode}`;\n\nfunction cmd(\n code: CSI.SetPrivateMode,\n modes: PrivateMode | readonly PrivateMode[]\n): `${escapeCSI}?${PrivateMode}${CSI.SetMode}`;\n\nfunction cmd(\n code: CSI.UnsetMode,\n modes: Mode | readonly Mode[]\n): `${escapeCSI}${Mode}${CSI.UnsetMode}`;\n\nfunction cmd(\n code: CSI.UnsetPrivateMode,\n modes: PrivateMode | readonly PrivateMode[]\n): `${escapeCSI}?${PrivateMode}${CSI.UnsetMode}`;\n\nfunction cmd(code: CSI.Style, styles: Style | readonly Style[]): `${escapeCSI}${Style}${CSI.Style}`;\n\nfunction cmd(code: CSI, a?: CommandParam, b?: number): cmdCode {\n if (!hasColor && code === CSI.Style) return '';\n let out = escapeCSI;\n if (code === CSI.SetPrivateMode) {\n out += '?';\n code = CSI.SetMode;\n } else if (code === CSI.UnsetPrivateMode) {\n out += '?';\n code = CSI.UnsetMode;\n }\n if (Array.isArray(a)) {\n out += a.join(';');\n } else if (a != null) {\n out += `${a}`;\n if (b != null) out += `;${b}`;\n }\n out += code;\n return out as cmdCode;\n}\n\nexport type cmdCode = `${escapeCSI}${string}${CSI}` | '';\n\nexport { cmd, CSI, TabClear, Erase, EraseLine, Protect, Mode, PrivateMode, Cursor, Style };\n","import type { Source } from 'wonka';\n\nimport {\n pipe,\n fromAsyncIterable,\n fromValue,\n concatMap,\n never,\n merge,\n takeUntil,\n takeLast,\n filter,\n share,\n scan,\n make,\n onPush,\n onEnd,\n subscribe,\n} from 'wonka';\n\nimport { cmd, CSI, EraseLine, Style } from './csi';\n\nconst ansiRegex = /([\\x1B\\x9B][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><])/g;\n\nexport const stripAnsi = (input: string) => input.replace(ansiRegex, '');\n\nexport class CLIError extends Error {\n output: string;\n exit: number;\n constructor(message: string, exitCode?: number) {\n super(stripAnsi(message));\n this.output = message;\n this.exit = exitCode != null ? exitCode : 1;\n }\n\n toString() {\n return this.output;\n }\n}\n\nfunction text(input: readonly string[], ...args: readonly string[]): string;\nfunction text(...input: readonly string[]): string;\n\nfunction text(input: string | readonly string[], ...args: readonly string[]): string {\n let out = '';\n if (Array.isArray(input)) {\n let argIndex = 0;\n for (let index = 0; index < input.length; index++) {\n out += input[index];\n if (argIndex < args.length) out += args[argIndex++];\n }\n } else if (typeof input === 'string') {\n out += input;\n for (const arg of args) out += arg;\n }\n return out;\n}\n\nfunction error(input: readonly string[], ...args: readonly string[]): CLIError;\nfunction error(arg: string | number, ...input: readonly string[]): CLIError;\nfunction error(...input: readonly string[]): CLIError;\n\nfunction error(arg: readonly string[] | string | number, ...input: readonly string[]): CLIError {\n return typeof arg === 'number'\n ? new CLIError(text(...input), arg)\n : new CLIError(text(arg as string, ...input));\n}\n\nfunction clear(text: string) {\n let lines = 0;\n for (let index = 0; index < text.length; index++)\n if (text.charCodeAt(index) === 10 /*'\\n'*/) lines++;\n if (lines) {\n return cmd(CSI.PrevLine, lines) + cmd(CSI.DeleteLines, lines + 1);\n } else if (stripAnsi(text)) {\n return cmd(CSI.EraseLine, EraseLine.Backward) + cmd(CSI.ToColumn, 1);\n } else {\n return '';\n }\n}\n\ntype ComposeInput = undefined | string | CLIError | Source<string> | AsyncIterable<ComposeInput>;\n\nfunction commit(source: Source<string | CLIError>): Source<string | CLIError> {\n return make((observer) => {\n let last: string | CLIError | undefined;\n const subscription = pipe(\n source,\n onPush((value) => {\n last = value;\n observer.next(value);\n }),\n onEnd(() => {\n if (typeof last === 'string' && !last.endsWith('\\n')) observer.next('');\n observer.complete();\n }),\n subscribe(() => {})\n );\n return subscription.unsubscribe;\n });\n}\n\nasync function* convertError(outputs: AsyncIterable<ComposeInput>): AsyncIterable<ComposeInput> {\n try {\n yield* outputs;\n } catch (error) {\n if (error instanceof CLIError) {\n process.exitCode = error.exit;\n yield error;\n } else {\n yield ('' + error).trim();\n }\n }\n\n yield '\\n';\n}\n\nfunction compose(outputs: AsyncIterable<ComposeInput>): Source<string | CLIError> {\n const reset = cmd(CSI.Style, [Style.Reset, Style.NoInvert]);\n const outputs$ = pipe(\n fromAsyncIterable(convertError(outputs)),\n concatMap((output) => {\n return typeof output === 'object' && !(output instanceof CLIError)\n ? compose(output)\n : fromValue(output);\n }),\n filter(<T>(x: T): x is Exclude<T, undefined> => x != null),\n share\n );\n\n return pipe(\n outputs$,\n concatMap((output) => {\n const output$ = pipe(\n typeof output === 'string' || output instanceof CLIError\n ? fromValue(output)\n : merge([output, never]),\n takeUntil(outputs$),\n share\n );\n return pipe(\n commit(output$),\n scan((prev: CLIError | string, output) => {\n return typeof output === 'string'\n ? clear(typeof prev === 'string' ? prev : '') + output + reset\n : output;\n }, '')\n );\n }),\n takeUntil(pipe(outputs$, takeLast(1)))\n );\n}\n\nexport type { ComposeInput };\nexport { text, error, compose, clear };\n","export const enum Chars {\n Bell = '\\x07',\n Newline = '\\x0a',\n Tab = '\\x09',\n Space = ' ',\n Ellipsis = '…',\n}\n\nexport const enum Box {\n TopLeft = '┌',\n TopRight = '┐',\n BottomLeft = '└',\n BottomRight = '┘',\n Vertical = '│',\n VerticalRight = '├',\n VerticalLeft = '┤',\n Horizontal = '─',\n HorizontalDown = '┬',\n HorizontalUp = '┴',\n Cross = '┼',\n}\n\nexport const enum HeavyBox {\n TopLeft = '┏',\n TopRight = '┓',\n BottomLeft = '┗',\n BottomRight = '┛',\n Vertical = '┃',\n VerticalRight = '┣',\n VerticalLeft = '┫',\n Horizontal = '━',\n HorizontalDown = '┳',\n HorizontalUp = '┻',\n Cross = '╋',\n}\n\nexport const enum DoubleBox {\n TopLeft = '╔',\n TopRight = '╗',\n BottomLeft = '╚',\n BottomRight = '╝',\n Vertical = '║',\n VerticalRight = '╠',\n VerticalLeft = '╣',\n Horizontal = '═',\n HorizontalDown = '╦',\n HorizontalUp = '╩',\n Cross = '╬',\n}\n\nexport enum RoundedBox {\n TopLeft = '╭',\n TopRight = '╮',\n BottomLeft = '╰',\n BottomRight = '╯',\n Vertical = '│',\n VerticalRight = '├',\n VerticalLeft = '┤',\n Horizontal = '─',\n HorizontalDown = '┬',\n HorizontalUp = '┴',\n Cross = '┼',\n}\n\nexport const enum Arrow {\n Right = '→',\n Left = '←',\n Up = '↑',\n Down = '↓',\n LeftRight = '↔',\n UpDown = '↕',\n}\n\nexport const enum Triangle {\n Right = '▶',\n Left = '◀',\n Up = '▲',\n Down = '▼',\n}\n\nexport const enum SmallTriangle {\n Right = '▸',\n Left = '◂',\n Up = '▴',\n Down = '▾',\n}\n\nexport const enum Line {\n DiagonalCross = '╳',\n Diagonalbackwards = '╲',\n Diagonal = '╱',\n VerticalDashed = '┆',\n VerticalDashedHeavy = '┇',\n Vertical = '│',\n VerticalHeavy = '┃',\n HorizontalDashed = '┄',\n HorizontalDashedHeavy = '┅',\n Horizontal = '─',\n HorizontalHeavy = '━',\n}\n\nexport const enum Circle {\n Filled = '●',\n Outline = '◯',\n OutlineFilled = '◉',\n Dotted = '◌',\n Doubled = '◎',\n Small = '•',\n HalfLeft = '◐',\n HalfTop = '◓',\n HalfRight = '◑',\n HalfBottom = '◒',\n}\n\nexport const enum Chevron {\n Default = '',\n Small = '›',\n Heavy = '❯',\n}\n\nexport const enum Diamond {\n Default = '◆',\n Outline = '◇',\n}\n\nexport const enum Square {\n Default = '■',\n Outline = '☐',\n Crossed = '☒',\n}\n\nexport const enum Heart {\n Default = '❤︎',\n Outline = '♥',\n}\n\nexport const enum Icons {\n Tick = '✓',\n TickSwoosh = '✔',\n Cross = '✖',\n CrossSwoosh = '✘',\n Home = '⌂',\n Note = '♪',\n Warning = '⚠',\n Info = 'ℹ',\n Star = '★',\n}\n\nexport const enum Shade {\n Light = '░',\n Medium = '▒',\n Heavy = '▓',\n}\n\nexport const dotSpinner = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\nexport const circleSpinner = ['◐', '◓', '◑', '◒'];\n","export const isGithubCI = !!process.env.GITHUB_ACTIONS;\n\nexport interface AnnotationProperties {\n title?: string;\n file?: string;\n line?: number;\n endLine?: number;\n col?: number;\n endColumn?: number;\n}\n\nconst toCommandValue = (input: unknown): string =>\n typeof input == 'string' || input == null\n ? '' + (input ? '' + input : '')\n : JSON.stringify(input);\n\nconst escapeData = (input: unknown) =>\n toCommandValue(input).replace(/%/g, '%25').replace(/\\r/g, '%0D').replace(/\\n/g, '%0A');\n\nconst escapeProperty = (input: unknown): string =>\n toCommandValue(input)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A')\n .replace(/:/g, '%3A')\n .replace(/,/g, '%2C');\n\nexport function githubAnnotation(\n kind: 'error' | 'warning' | 'notice',\n message: string,\n properties?: AnnotationProperties\n) {\n if (isGithubCI) {\n let out = `::${kind}`;\n let propsOut = '';\n if (properties) {\n for (const key in properties) {\n if (properties) propsOut += ',';\n if (properties[key]) propsOut += `${key}=${escapeProperty(properties[key])}`;\n }\n }\n if (propsOut) out += ` ${propsOut}`;\n out += `::${escapeData(message)}\\n`;\n process.stdout.write(out);\n }\n}\n","import {\n fromValue,\n make,\n concat,\n pipe,\n filter,\n share,\n takeUntil,\n toPromise,\n onPush,\n onStart,\n onEnd,\n} from 'wonka';\n\nimport type { Source } from 'wonka';\nimport type { WriteStream, ReadStream } from 'node:tty';\nimport { emitKeypressEvents } from 'node:readline';\n\nimport type { ComposeInput, CLIError } from './write';\nimport { text, compose } from './write';\nimport { cmd, _setColor, CSI, Mode, PrivateMode } from './csi';\nimport { isGithubCI } from './github';\n\nexport interface TTYParams {\n disableTTY?: boolean;\n silent?: boolean;\n}\n\nexport interface KeypressEvent {\n data?: string;\n sequence: string;\n name: string;\n ctrl: boolean;\n meta: boolean;\n shift: boolean;\n}\n\nexport interface TTY {\n isInteractive: boolean;\n\n output: WriteStream;\n pipeTo: WriteStream | null;\n inputSource: Source<KeypressEvent>;\n cancelSource: Source<unknown>;\n\n write(input: readonly string[], ...args: readonly string[]): void;\n write(...input: readonly string[]): void;\n\n start(outputs: AsyncIterable<ComposeInput>, disableInput?: boolean): Promise<string | CLIError>;\n\n mode(...modes: readonly (Mode | PrivateMode)[]): void;\n modeOff(...modes: readonly (Mode | PrivateMode)[]): void;\n}\n\nfunction fromReadStream(stream: ReadStream, onTerminate: () => void): Source<KeypressEvent> {\n return make((observer) => {\n function onKeypress(data: string | undefined, event: KeypressEvent) {\n // PTY hosts may send Ctrl-D to signal EOF, so it must not terminate the command.\n switch (event.name) {\n case 'c':\n case 'x':\n if (event.ctrl) return onTerminate();\n break;\n case 'escape':\n return cleanup();\n }\n observer.next({ ...event, data });\n }\n\n function cleanup() {\n try {\n if (stream.isTTY) stream.setRawMode(false);\n stream.removeListener('keypress', onKeypress);\n if (typeof stream.unref === 'function') {\n stream.unref();\n }\n } catch {\n // noop\n } finally {\n observer.complete();\n }\n }\n\n if (stream.isTTY) stream.setRawMode(true);\n emitKeypressEvents(stream);\n stream.setEncoding('utf8');\n stream.resume();\n stream.addListener('keypress', onKeypress);\n return cleanup;\n });\n}\n\nexport function initTTY(params: TTYParams = {}): TTY {\n let isTTY = process.env.TERM !== 'dumb' && !process.env.CI && !params.disableTTY;\n let pipeTo: WriteStream | null = null;\n let output: WriteStream = process.stdout;\n if (isGithubCI) {\n output = process.stderr;\n } else if (!output.isTTY && process.stderr.isTTY) {\n output = process.stderr;\n pipeTo = process.stdout;\n } else {\n isTTY = isTTY && !!output.isTTY;\n }\n\n const hasColorArg = process.argv.includes('--color');\n const hasColorEnv = 'FORCE_COLOR' in process.env || (!process.env.NO_COLOR && !process.env.CI);\n _setColor((isTTY && hasColorEnv) || hasColorArg || isGithubCI);\n\n function _restore() {\n if (process.stdin.isTTY) process.stdin.setRawMode(false);\n output.write(\n cmd(CSI.Reset) + cmd(CSI.ResetPrivateMode) + cmd(CSI.SetPrivateMode, PrivateMode.ShowCursor)\n );\n }\n\n function _terminate(code: number) {\n _restore();\n process.exit(code);\n }\n\n function _signal(signal: NodeJS.Signals) {\n _terminate(signal === 'SIGINT' ? 130 : 143);\n }\n\n function _start() {\n _setColor((isTTY && hasColorEnv) || hasColorArg);\n if (isTTY) {\n output.write(cmd(CSI.UnsetPrivateMode, PrivateMode.ShowCursor));\n process.on('SIGINT', _signal);\n process.on('SIGTERM', _signal);\n }\n }\n\n function _end() {\n if (isTTY) {\n process.removeListener('SIGINT', _signal);\n process.removeListener('SIGTERM', _signal);\n output.write(\n cmd(CSI.Reset) + cmd(CSI.ResetPrivateMode) + cmd(CSI.SetPrivateMode, PrivateMode.ShowCursor)\n );\n }\n }\n\n const inputSource = pipe(\n fromReadStream(process.stdin, () => _terminate(130)),\n onStart(_start),\n onEnd(_end),\n share\n );\n\n const cancelSource = pipe(\n concat([\n pipe(\n inputSource,\n filter(() => false)\n ),\n fromValue(null),\n ]),\n share\n );\n\n function write(...input: any[]) {\n if (!params.silent) output.write(text(...input));\n }\n\n function start(outputs: AsyncIterable<ComposeInput>): Promise<string | CLIError> {\n const write = (input: string | CLIError) => {\n if (!params.silent) output.write('' + input);\n };\n if (params.disableTTY || !isTTY) {\n return pipe(compose(outputs), onPush(write), toPromise);\n } else {\n return pipe(compose(outputs), onPush(write), takeUntil(cancelSource), toPromise);\n }\n }\n\n function mode(...modes: readonly (Mode | PrivateMode)[]): void {\n if (isTTY) {\n const normalModes: Mode[] = [];\n const privateModes: PrivateMode[] = [];\n for (const mode of modes) {\n if (mode === Mode.Insert || mode === Mode.AutomaticNewline) {\n normalModes.push(mode);\n } else {\n privateModes.push(mode);\n }\n }\n if (normalModes.length) output.write(cmd(CSI.SetMode, normalModes));\n if (privateModes.length) output.write(cmd(CSI.SetPrivateMode, privateModes));\n }\n }\n\n function modeOff(...modes: readonly (Mode | PrivateMode)[]): void {\n if (isTTY) {\n const normalModes: Mode[] = [];\n const privateModes: PrivateMode[] = [];\n for (const mode of modes) {\n if (mode === Mode.Insert || mode === Mode.AutomaticNewline) {\n normalModes.push(mode);\n } else {\n privateModes.push(mode);\n }\n }\n if (normalModes.length) output.write(cmd(CSI.UnsetMode, normalModes));\n if (privateModes.length) output.write(cmd(CSI.UnsetPrivateMode, privateModes));\n }\n }\n\n return {\n isInteractive: isTTY,\n output,\n pipeTo,\n inputSource,\n cancelSource,\n write,\n start,\n mode,\n modeOff,\n };\n}\n","import * as t from '../../term';\n\nexport function indent(text: string, indent: string) {\n if (text.includes('\\n')) {\n const out = text\n .trim()\n .split('\\n')\n .join(t.text([t.Chars.Newline, indent]));\n return text.endsWith('\\n') ? out + '\\n' : out;\n } else {\n return text;\n }\n}\n\nexport function code(text: string) {\n return t.text`${t.cmd(t.CSI.Style, t.Style.Underline)}${text}${t.cmd(\n t.CSI.Style,\n t.Style.NoUnderline\n )}`;\n}\n\nexport function bold(text: string) {\n return t.text`${t.cmd(t.CSI.Style, t.Style.Bold)}${text}${t.cmd(t.CSI.Style, t.Style.Normal)}`;\n}\n\nexport function hint(text: string) {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${t.Icons.Info} `,\n t.cmd(t.CSI.Style, t.Style.Blue),\n indent(text, ' '),\n ]);\n}\n\nexport function projectHeader(label: string) {\n return t.text([\n '\\n',\n t.cmd(t.CSI.Style, t.Style.Magenta),\n `${t.SmallTriangle.Right} `,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n bold(label),\n '\\n',\n ]);\n}\n\nexport function errorMessage(message: string) {\n return t.error([\n '\\n',\n t.cmd(t.CSI.Style, [t.Style.Red, t.Style.Invert]),\n ` ${t.Icons.Warning} Error `,\n t.cmd(t.CSI.Style, t.Style.NoInvert),\n `\\n${message.trim()}\\n`,\n ]);\n}\n\nexport function externalError(message: string, error: unknown) {\n let title: string;\n let text: string;\n if (error && typeof error === 'object') {\n if (\n 'name' in error &&\n (error.name === 'TSError' || error.name === 'TadaError' || 'code' in error)\n ) {\n title = 'code' in error ? 'System Error' : 'Error';\n text =\n error.name === 'TadaError'\n ? t.text([t.cmd(t.CSI.Style, t.Style.Blue), (error as Error).message])\n : (error as Error).message.trim();\n } else if ('stack' in error && typeof error.stack === 'string') {\n title = 'Unexpected Error';\n text = `${error.stack}`;\n } else if ('message' in error && typeof error.message === 'string') {\n title = 'Unexpected Error';\n text = `${error.message}`;\n } else {\n title = 'Unexpected Error';\n text = `${error}`;\n }\n } else {\n title = 'Unexpected Error';\n text = `${error}`;\n }\n\n return t.error([\n '\\n',\n t.cmd(t.CSI.Style, [t.Style.Red, t.Style.Invert]),\n ` ${t.Icons.Warning} ${title} `,\n t.cmd(t.CSI.Style, t.Style.NoInvert),\n `\\n${message.trim()}\\n`,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n indent(!text.endsWith('\\n') ? text + '\\n' : text, ' '),\n ]);\n}\n\nexport function experimentMessage(message: string) {\n return t.error([\n t.cmd(t.CSI.Style, [t.Style.Yellow, t.Style.Bold]),\n `${t.Icons.Warning} Note: `,\n t.cmd(t.CSI.Style, t.Style.Reset),\n `${message.trim()}\\n\\n`,\n ]);\n}\n","import * as path from 'node:path';\nimport type { GraphQLSPConfig, LoadConfigResult } from '@gql.tada/internal';\nimport { loadConfigs, parseConfig, validateUniqueOutputLocations } from '@gql.tada/internal';\n\nexport interface ProjectContext {\n configResult: LoadConfigResult;\n pluginConfig: GraphQLSPConfig;\n /** Directory of the project's own tsconfig.json file. */\n projectPath: string;\n /** Display name for per-project output. */\n label: string;\n}\n\n/** Loads all projects with a plugin config, including referenced projects. */\nexport const loadProjects = async (tsconfig: string | undefined): Promise<ProjectContext[]> => {\n const configResults = await loadConfigs(tsconfig);\n const projects = configResults.map((configResult): ProjectContext => {\n const projectPath = path.dirname(configResult.tsconfigPath);\n return {\n configResult,\n pluginConfig: parseConfig(configResult.pluginConfig, configResult.rootPath),\n projectPath,\n label: path.relative(process.cwd(), configResult.tsconfigPath) || configResult.tsconfigPath,\n };\n });\n validateUniqueOutputLocations(\n projects.map((project) => ({\n projectPath: project.projectPath,\n config: project.pluginConfig,\n label: project.label,\n }))\n );\n return projects;\n};\n","import type { WriteStream } from 'node:tty';\nimport type { PathLike } from 'node:fs';\nimport { dirname } from 'node:path';\nimport * as fs from 'node:fs/promises';\n\n/** Checks whether a directory exists on disk */\nconst directoryExists = async (file: PathLike): Promise<boolean> => {\n try {\n const stat = await fs.stat(file);\n if (stat.isDirectory()) {\n return true;\n } else if (stat.isSymbolicLink()) {\n return directoryExists(await fs.realpath(file));\n } else {\n return false;\n }\n } catch {\n return false;\n }\n};\n\n/** Checks whether a file exists on disk */\nconst fileExists = (file: PathLike): Promise<boolean> =>\n fs\n .stat(file)\n .then((stat) => stat.isFile())\n .catch(() => false);\n\nconst touchFile = async (file: PathLike): Promise<void> => {\n try {\n const now = new Date();\n await fs.utimes(file, now, now);\n } catch (_error) {}\n};\n\nexport type WriteTarget = PathLike | WriteStream;\n\n/** Reads the current contents of a file target, or `undefined` for streams or missing files. */\nexport const readOutput = async (target: WriteTarget): Promise<string | undefined> => {\n if (target && typeof target === 'object' && 'writable' in target) return undefined;\n try {\n return await fs.readFile(target, 'utf8');\n } catch {\n return undefined;\n }\n};\n\n/** Writes a file to a swapfile then moves it into place to prevent excess change events. */\nexport const writeOutput = async (target: WriteTarget, contents: string): Promise<void> => {\n if (target && typeof target === 'object' && 'writable' in target) {\n // If we get a WritableStream (e.g. stdout), we write to that\n // but we listen for errors and wait for it to flush fully\n return await new Promise((resolve, reject) => {\n target.write(contents, (error) => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n }\n\n const targetDirectory = dirname(typeof target !== 'string' ? await fs.realpath(target) : target);\n if (!(await directoryExists(targetDirectory))) {\n await fs.mkdir(targetDirectory, { recursive: true });\n }\n\n if (!(await fileExists(target))) {\n // If the file doesn't exist, we can write directly, and not\n // try-catch so the error falls through\n await fs.writeFile(target, contents);\n } else {\n // If the file exists, we write to a swap-file, then rename (i.e. move)\n // the file into place. No try-catch around `writeFile` for proper\n // directory/permission errors\n const tempTarget = target + '.tmp';\n await fs.writeFile(tempTarget, contents);\n try {\n await fs.rename(tempTarget, target);\n } catch (error) {\n await fs.unlink(tempTarget);\n throw error;\n } finally {\n // When we move the file into place, we also update its access and\n // modification time manually, in case the rename doesn't trigger\n // a change event\n await touchFile(target);\n }\n }\n};\n","import * as t from '../../term';\n\nimport { hint, code } from '../shared/logger';\nexport * from '../shared/logger';\n\nexport function summary(showHint?: boolean) {\n let out = t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Introspection output was generated successfully\\n`,\n ]);\n if (showHint) {\n out += hint(\n `The pipe output was generated in the ${code('.d.ts')} format.\\n` +\n `For the ${code('.ts')} format, pass the ${code('--force-ts-format')} argument.\\n`\n );\n }\n return out;\n}\n","import * as path from 'node:path';\n\nimport {\n loadRef,\n minifyIntrospection,\n outputIntrospectionFile,\n extractIntrospectionHeader,\n} from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, writeOutput, readOutput } from '../shared';\nimport * as logger from './logger';\n\nexport interface OutputOptions {\n /** Whether to output the `.ts` format when the CLI's standard output is piped to an output file.\n * @defaultValue `false` */\n forceTSFormat?: boolean;\n /** Whether to disable the optimized output format for `.d.ts` files.\n * @defaultValue `false` */\n disablePreprocessing?: boolean;\n /** The filename to write the cache file to.\n * @defaultValue The `tadaTurboLocation` configuration option */\n output: string | undefined;\n /** The `tsconfig.json` to use for configurations and the TypeScript program.\n * @defaultValue A `tsconfig.json` in the current or any parent directory. */\n tsconfig: string | undefined;\n /** Whether to disable terminal output when using the programmatic API.\n * @defaultValue `false` */\n silent?: boolean;\n}\n\nexport async function* run(tty: TTY, opts: OutputOptions): AsyncIterable<ComposeInput> {\n let projects: ProjectContext[];\n try {\n projects = await loadProjects(opts.tsconfig);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n if (projects.length > 1 && (opts.output || tty.pipeTo)) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple projects are configured.\\n' +\n logger.hint(\n `You can only output all projects to their ${logger.code(\n '\"tadaOutputLocation\"'\n )} options\\n` +\n `when multiple projects are set up through ${logger.code('\"references\"')}.`\n )\n );\n }\n\n // Projects may share an output file; its contents come only from the schema,\n // so generate each distinct file once rather than once per referencing project.\n const generated = new Set<string>();\n for (const project of projects) {\n const destinations = outputDestinations(project);\n if (destinations.length && destinations.every((destination) => generated.has(destination))) {\n continue;\n }\n for (const destination of destinations) generated.add(destination);\n if (projects.length > 1) yield logger.projectHeader(project.label);\n yield* runProject(tty, opts, project);\n }\n}\n\nfunction outputDestinations(project: ProjectContext): string[] {\n const { pluginConfig, projectPath } = project;\n const locations =\n 'schemas' in pluginConfig\n ? pluginConfig.schemas.map((schema) => schema.tadaOutputLocation)\n : [pluginConfig.tadaOutputLocation];\n return locations\n .filter((location): location is string => !!location)\n .map((location) => path.resolve(projectPath, location));\n}\n\n/** Generates the introspection output for a single project. */\nasync function* runProject(\n tty: TTY,\n opts: OutputOptions,\n project: ProjectContext\n): AsyncIterable<ComposeInput> {\n const { pluginConfig, projectPath } = project;\n\n let schemaRef = loadRef(pluginConfig);\n try {\n schemaRef = await schemaRef.load({ rootPath: projectPath });\n } catch (error) {\n throw logger.externalError('Failed to load schema(s).', error);\n }\n\n if ('schema' in pluginConfig) {\n const schema = schemaRef.current!;\n\n let destination: WriteTarget;\n if (!opts.output && tty.pipeTo) {\n destination = tty.pipeTo;\n } else if (opts.output) {\n destination = path.resolve(process.cwd(), opts.output);\n } else if (pluginConfig.tadaOutputLocation) {\n destination = path.resolve(projectPath, pluginConfig.tadaOutputLocation);\n } else {\n throw logger.errorMessage(\n 'No output path was specified to write the output file to.\\n' +\n logger.hint(\n `You have to either set ${logger.code(\n '\"tadaOutputLocation\"'\n )} in your configuration,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n }\n\n const existing = await readOutput(destination);\n let contents: string;\n try {\n contents = outputIntrospectionFile(minifyIntrospection(schema.introspection), {\n fileType:\n destination && typeof destination === 'string'\n ? destination\n : opts.forceTSFormat\n ? '.ts'\n : '.d.ts',\n shouldPreprocess: !opts.disablePreprocessing,\n preamble: existing ? extractIntrospectionHeader(existing) || undefined : undefined,\n });\n } catch (error) {\n throw logger.externalError('Could not generate introspection output', error);\n }\n\n try {\n await writeOutput(destination, contents);\n } catch (error) {\n throw logger.externalError(\n 'Something went wrong while writing the introspection file',\n error\n );\n }\n\n yield logger.summary(!opts.forceTSFormat && typeof destination !== 'string');\n } else {\n if (opts.output) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple schemas are configured.\\n' +\n logger.hint(\n `You can only output all schemas to their ${logger.code(\n '\"tadaOutputLocation\"'\n )} options\\n` + `when multiple ${logger.code('schemas')} are set up.`\n )\n );\n }\n\n for (const schemaName in schemaRef.multi) {\n const schema = schemaRef.multi[schemaName];\n if (!schema) {\n continue;\n } else if (!schema.tadaOutputLocation) {\n throw logger.errorMessage(\n `No output path was specified to write the '${schemaName}' schema to.\\n` +\n logger.hint(\n `You have to set ${logger.code('\"tadaOutputLocation\"')} in each schema configuration.`\n )\n );\n }\n\n const destination = path.resolve(projectPath, schema.tadaOutputLocation);\n const existing = await readOutput(destination);\n let contents: string;\n try {\n contents = outputIntrospectionFile(minifyIntrospection(schema.introspection), {\n fileType: schema.tadaOutputLocation,\n shouldPreprocess: !opts.disablePreprocessing,\n preamble: existing ? extractIntrospectionHeader(existing) || undefined : undefined,\n });\n } catch (error) {\n throw logger.externalError(\n `Could not generate any output for the '${schemaName}' schema`,\n error\n );\n }\n\n try {\n await writeOutput(destination, contents);\n } catch (error) {\n throw logger.externalError(\n `Something went wrong while writing the '${schemaName}' schema's output`,\n error\n );\n }\n }\n\n yield logger.summary();\n }\n}\n","import { Command, Option } from 'clipanion';\n\nimport type { OutputOptions } from './runner';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class GenerateOutputCommand extends Command {\n static paths = [['generate-output'], ['generate', 'output']];\n\n forceTSFormat = Option.Boolean('--force-ts-format', false, {\n description: 'Forces the `.ts` output format when the output is piped',\n hidden: true,\n });\n\n disablePreprocessing = Option.Boolean('--disable-preprocessing', false, {\n description:\n 'Disables pre-processing, which is an internal introspection format generated ahead of time',\n });\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` used to read, unless `--output` is passed.',\n });\n\n output = Option.String('--output,-o', {\n description:\n 'Specifies where to output the file to.\\tDefault: The `tadaOutputLocation` configuration option',\n });\n\n async execute() {\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n forceTSFormat: this.forceTSFormat,\n disablePreprocessing: this.disablePreprocessing,\n output: this.output,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Outputs the `gql.tada` output file manually.\n *\n * @remarks\n * Loads the schema from the specified `schema` configuration option and writes the output file\n * to the specified output location.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#generateoutput}\n */\nexport async function generateOutput(opts: OutputOptions): Promise<void> {\n const tty = initTTY({ disableTTY: true, silent: opts.silent });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","import { pipe, interval, map, concat, fromValue } from 'wonka';\n\nimport * as path from 'node:path';\nimport * as t from '../../term';\n\nimport type { PersistedWarning } from './types';\nimport { indent } from '../shared/logger';\n\nexport * from '../shared/logger';\n\nconst CWD = process.cwd();\nconst INDENT = ' ';\n\nexport function warningFile(filePath: string) {\n const relativePath = path.relative(CWD, filePath);\n if (!relativePath.startsWith('..')) filePath = relativePath;\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Underline),\n filePath,\n t.cmd(t.CSI.Style, t.Style.NoUnderline),\n '\\n',\n ]);\n}\n\nexport function warningMessage(message: PersistedWarning) {\n return t.text([\n INDENT,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${message.line}:${message.col}`,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n indent(message.message.trim(), t.text([INDENT, t.Chars.Tab])),\n t.Chars.Newline,\n ]);\n}\n\nconst documentSummary = (documentCount: number | Record<string, number>) => {\n let out = '';\n if (\n typeof documentCount !== 'number'\n ? Object.values(documentCount).every((value) => !value)\n : !documentCount\n ) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.Blue),\n `${t.Icons.Info} No persisted documents were found `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `(Persisted manifests were not generated)\\n`,\n ]);\n } else if (typeof documentCount === 'number') {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Persisted manifest was generated successfully `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `(${documentCount} documents extracted)\\n`,\n ]);\n } else {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Persisted manifests were generated successfully.\\n`,\n ]);\n for (const schemaName in documentCount) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${documentCount[schemaName]} documents extracted for the '${schemaName}' schema\\n`,\n ]);\n }\n }\n return out;\n};\n\nexport function warningSummary(warningCount: number) {\n return t.error([t.cmd(t.CSI.Style, t.Style.Red), `${t.Icons.Cross} ${warningCount} warnings\\n`]);\n}\n\nexport function infoSummary(warningCount: number, documentCount: number | Record<string, number>) {\n let out = '';\n if (warningCount) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ` ${warningCount} warnings\\n`,\n ]);\n }\n out += documentSummary(documentCount);\n return out;\n}\n\nexport function warningGithub(message: PersistedWarning): void {\n t.githubAnnotation('warning', message.message, {\n file: message.file,\n line: message.line,\n col: message.col,\n });\n}\n\nexport function runningPersisted(file?: number, ofFiles?: number) {\n const progress = file ? (ofFiles ? `(${file}/${ofFiles})` : `(${file})`) : '';\n const frame = (state: number) =>\n t.text([\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.dotSpinner[state % t.dotSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n `Scanning files${t.Chars.Ellipsis} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n progress,\n ]);\n return concat([\n fromValue(frame(0)),\n pipe(\n interval(150),\n map((state) => frame(state + 1))\n ),\n ]);\n}\n","import * as path from 'node:path';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, writeOutput } from '../shared';\nimport type { PersistedDocument } from './types';\nimport * as logger from './logger';\n\nexport interface PersistedOptions {\n /** Whether to disable normalization of GraphQL documents in the output.\n * @defaultValue `false`\n * @remarks\n * Normalizing a GraphQL document means to parse then print them, which\n * removes comments and normalizes formatting.\n */\n disableNormalization?: boolean;\n /** The `tsconfig.json` to use for configurations and the TypeScript program.\n * @defaultValue A `tsconfig.json` in the current or any parent directory. */\n tsconfig: string | undefined;\n /** The filename to write the persisted JSON manifest to.\n * @defaultValue The `schema` configuration option */\n output: string | undefined;\n /** Whether to fail instead of just logging a warning. */\n failOnWarn: boolean;\n}\n\nexport async function* run(tty: TTY, opts: PersistedOptions): AsyncIterable<ComposeInput> {\n let projects: ProjectContext[];\n try {\n projects = await loadProjects(opts.tsconfig);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n if (projects.length > 1 && (opts.output || tty.pipeTo)) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple projects are configured.\\n' +\n logger.hint(\n `You can only output all projects to their ${logger.code(\n '\"tadaPersistedLocation\"'\n )} options\\n` +\n `when multiple projects are set up through ${logger.code('\"references\"')}.`\n )\n );\n }\n\n let totalWarnings = 0;\n let failedProjects = false;\n for (const project of projects) {\n if (projects.length > 1) yield logger.projectHeader(project.label);\n const result = yield* runProject(tty, opts, project, projects.length > 1);\n totalWarnings += result.warnings;\n failedProjects = failedProjects || result.failed;\n }\n\n if (failedProjects) {\n throw logger.warningSummary(totalWarnings);\n }\n}\n\ninterface ProjectResult {\n warnings: number;\n failed: boolean;\n}\n\n/** Generates the persisted manifest for a single project. */\nasync function* runProject(\n tty: TTY,\n opts: PersistedOptions,\n project: ProjectContext,\n deferWarnings: boolean\n): AsyncGenerator<ComposeInput, ProjectResult> {\n const { runPersisted } = await import('./thread');\n\n const { pluginConfig, projectPath } = project;\n\n if (tty.isInteractive) yield logger.runningPersisted();\n\n const generator = runPersisted({\n disableNormalization: !!opts.disableNormalization,\n rootPath: project.configResult.rootPath,\n tsconfigPath: project.configResult.tsconfigPath,\n configPath: project.configResult.configPath,\n pluginConfig,\n });\n\n const documents: PersistedDocument[] = [];\n let warnings = 0;\n let totalFileCount = 0;\n let fileCount = 0;\n\n try {\n if (tty.isInteractive) yield logger.runningPersisted();\n\n for await (const signal of generator) {\n if (signal.kind === 'EXTERNAL_WARNING') {\n yield logger.experimentMessage(\n `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n );\n } else if (signal.kind === 'FILE_COUNT') {\n totalFileCount = signal.fileCount;\n } else {\n fileCount++;\n documents.push(...signal.documents);\n warnings += signal.warnings.length;\n if (signal.warnings.length) {\n let buffer = logger.warningFile(signal.filePath);\n for (const warning of signal.warnings) {\n buffer += logger.warningMessage(warning);\n logger.warningGithub(warning);\n }\n yield buffer + '\\n';\n }\n }\n\n if (tty.isInteractive) yield logger.runningPersisted(fileCount, totalFileCount);\n }\n } catch (error) {\n throw logger.externalError('Could not generate persisted manifest file', error);\n }\n\n if ('schema' in pluginConfig) {\n let destination: WriteTarget;\n if (!opts.output && tty.pipeTo) {\n destination = tty.pipeTo;\n } else if (opts.output) {\n destination = path.resolve(process.cwd(), opts.output);\n } else if (pluginConfig.tadaPersistedLocation) {\n destination = path.resolve(projectPath, pluginConfig.tadaPersistedLocation);\n } else {\n throw logger.errorMessage(\n 'No output path was specified to write the persisted manifest file to.\\n' +\n logger.hint(\n `You have to either set ${logger.code(\n '\"tadaPersistedLocation\"'\n )} in your configuration,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n }\n\n if (warnings && opts.failOnWarn) {\n if (!deferWarnings) throw logger.warningSummary(warnings);\n return { warnings, failed: true };\n } else if (documents.length) {\n try {\n const json: Record<string, string> = {};\n for (const item of documents) json[item.hashKey] = item.document;\n const contents = JSON.stringify(json, null, 2);\n await writeOutput(destination, contents);\n } catch (error) {\n throw logger.externalError(\n 'Something went wrong while writing the persisted manifest file.',\n error\n );\n }\n }\n\n yield logger.infoSummary(warnings, documents.length);\n } else {\n if (opts.output) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple schemas are configured.\\n' +\n logger.hint(\n `You can only output all schemas to their ${logger.code(\n '\"tadaPersistedLocation\"'\n )} options\\n` + `when multiple ${logger.code('schemas')} are set up.`\n )\n );\n }\n\n const documentCount: Record<string, number> = {};\n for (const schemaConfig of pluginConfig.schemas) {\n const { name, tadaPersistedLocation } = schemaConfig;\n if (!tadaPersistedLocation) {\n throw logger.errorMessage(\n `No output path was specified to write the '${name}' schema to.\\n` +\n logger.hint(\n `You have to set ${logger.code(\n '\"tadaPersistedLocation\"'\n )} in each schema configuration.`\n )\n );\n }\n\n try {\n documentCount[name] = 0;\n const json: Record<string, string> = {};\n for (const item of documents) {\n if (item.schemaName === name) {\n json[item.hashKey] = item.document;\n documentCount[name]++;\n }\n }\n if (documentCount[name]) {\n const contents = JSON.stringify(json, null, 2);\n await writeOutput(path.resolve(projectPath, tadaPersistedLocation), contents);\n }\n } catch (error) {\n throw logger.externalError(\n `Something went wrong while writing the '${name}' schema's persisted manifest file.`,\n error\n );\n }\n }\n\n if (warnings && opts.failOnWarn) {\n if (!deferWarnings) throw logger.warningSummary(warnings);\n return { warnings, failed: true };\n } else {\n yield logger.infoSummary(warnings, documentCount);\n }\n }\n\n return { warnings, failed: false };\n}\n","import { Command, Option } from 'clipanion';\n\nimport type { PersistedOptions } from './runner';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class GeneratePersisted extends Command {\n static paths = [['generate-persisted'], ['generate', 'persisted']];\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` used to read, unless `--output` is passed.',\n });\n\n disableNormalization = Option.Boolean('--disable-normalization', false, {\n description: 'Disables normalizing of GraphQL documents (parsing then printing documents)',\n });\n\n failOnWarn = Option.Boolean('--fail-on-warn', false, {\n description: 'Triggers an error and a non-zero exit code if any warnings have been reported',\n });\n\n output = Option.String('--output,-o', {\n description:\n 'Specifies where to output the file to.\\tDefault: The `tadaPersistedLocation` configuration option',\n });\n\n async execute() {\n // TODO: Add verbose/log/list/debug/trace option that outputs discovered documents (by name) per file\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n disableNormalization: this.disableNormalization,\n failOnWarn: this.failOnWarn,\n output: this.output,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Generates a JSON manifest file of all `graphql.persisted()` documents.\n *\n * @remarks\n * Scans your code for `graphql.persisted()` calls and generates a JSON\n * manifest file containing a mapping of document IDs to the GraphQL document strings.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#generatepersisted}\n */\nexport async function generatePersisted(opts: PersistedOptions) {\n const tty = initTTY({ disableTTY: true });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","const simpleKeyRegExp = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\nfunction getPrintable(value) {\n if (value === null)\n return `null`;\n if (value === undefined)\n return `undefined`;\n if (value === ``)\n return `an empty string`;\n if (typeof value === 'symbol')\n return `<${value.toString()}>`;\n if (Array.isArray(value))\n return `an array`;\n return JSON.stringify(value);\n}\nfunction getPrintableArray(value, conjunction) {\n if (value.length === 0)\n return `nothing`;\n if (value.length === 1)\n return getPrintable(value[0]);\n const rest = value.slice(0, -1);\n const trailing = value[value.length - 1];\n const separator = value.length > 2\n ? `, ${conjunction} `\n : ` ${conjunction} `;\n return `${rest.map(value => getPrintable(value)).join(`, `)}${separator}${getPrintable(trailing)}`;\n}\nfunction computeKey(state, key) {\n var _a, _b, _c;\n if (typeof key === `number`) {\n return `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}[${key}]`;\n }\n else if (simpleKeyRegExp.test(key)) {\n return `${(_b = state === null || state === void 0 ? void 0 : state.p) !== null && _b !== void 0 ? _b : ``}.${key}`;\n }\n else {\n return `${(_c = state === null || state === void 0 ? void 0 : state.p) !== null && _c !== void 0 ? _c : `.`}[${JSON.stringify(key)}]`;\n }\n}\nfunction plural(n, singular, plural) {\n return n === 1 ? singular : plural;\n}\n\nconst colorStringRegExp = /^#[0-9a-f]{6}$/i;\nconst colorStringAlphaRegExp = /^#[0-9a-f]{6}([0-9a-f]{2})?$/i;\n// https://stackoverflow.com/a/475217/880703\nconst base64RegExp = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n// https://stackoverflow.com/a/14166194/880703\nconst uuid4RegExp = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$/i;\n// https://stackoverflow.com/a/28022901/880703 + https://www.debuggex.com/r/bl8J35wMKk48a7u_\nconst iso8601RegExp = /^(?:[1-9]\\d{3}(-?)(?:(?:0[1-9]|1[0-2])\\1(?:0[1-9]|1\\d|2[0-8])|(?:0[13-9]|1[0-2])\\1(?:29|30)|(?:0[13578]|1[02])(?:\\1)31|00[1-9]|0[1-9]\\d|[12]\\d{2}|3(?:[0-5]\\d|6[0-5]))|(?:[1-9]\\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)(?:(-?)02(?:\\2)29|-?366))T(?:[01]\\d|2[0-3])(:?)[0-5]\\d(?:\\3[0-5]\\d)?(?:Z|[+-][01]\\d(?:\\3[0-5]\\d)?)$/;\n\nfunction pushError({ errors, p } = {}, message) {\n errors === null || errors === void 0 ? void 0 : errors.push(`${p !== null && p !== void 0 ? p : `.`}: ${message}`);\n return false;\n}\nfunction makeSetter(target, key) {\n return (v) => {\n target[key] = v;\n };\n}\nfunction makeCoercionFn(target, key) {\n return (v) => {\n const previous = target[key];\n target[key] = v;\n return makeCoercionFn(target, key).bind(null, previous);\n };\n}\nfunction makeLazyCoercionFn(fn, orig, generator) {\n const commit = () => {\n fn(generator());\n return revert;\n };\n const revert = () => {\n fn(orig);\n return commit;\n };\n return commit;\n}\n\n/**\n * Create a validator that always returns true and never refines the type.\n */\nfunction isUnknown() {\n return makeValidator({\n test: (value, state) => {\n return true;\n },\n });\n}\nfunction isLiteral(expected) {\n return makeValidator({\n test: (value, state) => {\n if (value !== expected)\n return pushError(state, `Expected ${getPrintable(expected)} (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a string.\n * Refines the type to `string`.\n */\nfunction isString() {\n return makeValidator({\n test: (value, state) => {\n if (typeof value !== `string`)\n return pushError(state, `Expected a string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\nfunction isEnum(enumSpec) {\n const valuesArray = Array.isArray(enumSpec) ? enumSpec : Object.values(enumSpec);\n const isAlphaNum = valuesArray.every(item => typeof item === 'string' || typeof item === 'number');\n const values = new Set(valuesArray);\n if (values.size === 1)\n return isLiteral([...values][0]);\n return makeValidator({\n test: (value, state) => {\n if (!values.has(value)) {\n if (isAlphaNum) {\n return pushError(state, `Expected one of ${getPrintableArray(valuesArray, `or`)} (got ${getPrintable(value)})`);\n }\n else {\n return pushError(state, `Expected a valid enumeration value (got ${getPrintable(value)})`);\n }\n }\n return true;\n },\n });\n}\nconst BOOLEAN_COERCIONS = new Map([\n [`true`, true],\n [`True`, true],\n [`1`, true],\n [1, true],\n [`false`, false],\n [`False`, false],\n [`0`, false],\n [0, false],\n]);\n/**\n * Create a validator that only returns true when the tested value is a\n * boolean. Refines the type to `boolean`.\n *\n * Supports coercion:\n * - 'true' / 'True' / '1' / 1 will turn to `true`\n * - 'false' / 'False' / '0' / 0 will turn to `false`\n */\nfunction isBoolean() {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof value !== `boolean`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const coercion = BOOLEAN_COERCIONS.get(value);\n if (typeof coercion !== `undefined`) {\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);\n return true;\n }\n }\n return pushError(state, `Expected a boolean (got ${getPrintable(value)})`);\n }\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a\n * number (including floating numbers; use `cascade` and `isInteger` to\n * restrict the range further). Refines the type to `number`.\n *\n * Supports coercion.\n */\nfunction isNumber() {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof value !== `number`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n let coercion;\n if (typeof value === `string`) {\n let val;\n try {\n val = JSON.parse(value);\n }\n catch (_b) { }\n // We check against JSON.stringify that the output is the same to ensure that the number can be safely represented in JS\n if (typeof val === `number`) {\n if (JSON.stringify(val) === value) {\n coercion = val;\n }\n else {\n return pushError(state, `Received a number that can't be safely represented by the runtime (${value})`);\n }\n }\n }\n if (typeof coercion !== `undefined`) {\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);\n return true;\n }\n }\n return pushError(state, `Expected a number (got ${getPrintable(value)})`);\n }\n return true;\n },\n });\n}\n/**\n * Important: This validator only makes sense when used in conjunction with\n * coercion! It will always error when used without.\n *\n * Create a validator that only returns true when the tested value is a\n * JSON representation of the expected type. Refines the type to the\n * expected type, and casts the value into its inner value.\n */\nfunction isPayload(spec) {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) === `undefined`)\n return pushError(state, `The isPayload predicate can only be used with coercion enabled`);\n if (typeof state.coercion === `undefined`)\n return pushError(state, `Unbound coercion result`);\n if (typeof value !== `string`)\n return pushError(state, `Expected a string (got ${getPrintable(value)})`);\n let inner;\n try {\n inner = JSON.parse(value);\n }\n catch (_b) {\n return pushError(state, `Expected a JSON string (got ${getPrintable(value)})`);\n }\n const wrapper = { value: inner };\n if (!spec(inner, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(wrapper, `value`) })))\n return false;\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, wrapper.value)]);\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a\n * valid date. Refines the type to `Date`.\n *\n * Supports coercion via one of the following formats:\n * - ISO86001 strings\n * - Unix timestamps\n */\nfunction isDate() {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (!(value instanceof Date)) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n let coercion;\n if (typeof value === `string` && iso8601RegExp.test(value)) {\n coercion = new Date(value);\n }\n else {\n let timestamp;\n if (typeof value === `string`) {\n let val;\n try {\n val = JSON.parse(value);\n }\n catch (_b) { }\n if (typeof val === `number`) {\n timestamp = val;\n }\n }\n else if (typeof value === `number`) {\n timestamp = value;\n }\n if (typeof timestamp !== `undefined`) {\n if (Number.isSafeInteger(timestamp) || !Number.isSafeInteger(timestamp * 1000)) {\n coercion = new Date(timestamp * 1000);\n }\n else {\n return pushError(state, `Received a timestamp that can't be safely represented by the runtime (${value})`);\n }\n }\n }\n if (typeof coercion !== `undefined`) {\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);\n return true;\n }\n }\n return pushError(state, `Expected a date (got ${getPrintable(value)})`);\n }\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * array whose all values match the provided subspec. Refines the type to\n * `Array<T>`, with `T` being the subspec inferred type.\n *\n * Supports coercion if the `delimiter` option is set, in which case strings\n * will be split accordingly.\n */\nfunction isArray(spec, { delimiter } = {}) {\n return makeValidator({\n test: (value, state) => {\n var _a;\n const originalValue = value;\n if (typeof value === `string` && typeof delimiter !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n value = value.split(delimiter);\n }\n }\n if (!Array.isArray(value))\n return pushError(state, `Expected an array (got ${getPrintable(value)})`);\n let valid = true;\n for (let t = 0, T = value.length; t < T; ++t) {\n valid = spec(value[t], Object.assign(Object.assign({}, state), { p: computeKey(state, t), coercion: makeCoercionFn(value, t) })) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n if (value !== originalValue)\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);\n return valid;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * set whose all values match the provided subspec. Refines the type to\n * `Set<T>`, with `T` being the subspec inferred type.\n *\n * Supports coercion from arrays (or anything that can be coerced into an\n * array).\n */\nfunction isSet(spec, { delimiter } = {}) {\n const isArrayValidator = isArray(spec, { delimiter });\n return makeValidator({\n test: (value, state) => {\n var _a, _b;\n if (Object.getPrototypeOf(value).toString() === `[object Set]`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const originalValues = [...value];\n const coercedValues = [...value];\n if (!isArrayValidator(coercedValues, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n const updateValue = () => coercedValues.some((val, t) => val !== originalValues[t])\n ? new Set(coercedValues)\n : value;\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, makeLazyCoercionFn(state.coercion, value, updateValue)]);\n return true;\n }\n else {\n let valid = true;\n for (const subValue of value) {\n valid = spec(subValue, Object.assign({}, state)) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n return valid;\n }\n }\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const store = { value };\n if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(store, `value`) })))\n return false;\n state.coercions.push([(_b = state.p) !== null && _b !== void 0 ? _b : `.`, makeLazyCoercionFn(state.coercion, value, () => new Set(store.value))]);\n return true;\n }\n return pushError(state, `Expected a set (got ${getPrintable(value)})`);\n }\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * map whose all values match the provided subspecs. Refines the type to\n * `Map<U, V>`, with `U` being the key subspec inferred type and `V` being\n * the value subspec inferred type.\n *\n * Supports coercion from array of tuples (or anything that can be coerced into\n * an array of tuples).\n */\nfunction isMap(keySpec, valueSpec) {\n const isArrayValidator = isArray(isTuple([keySpec, valueSpec]));\n const isRecordValidator = isRecord(valueSpec, { keys: keySpec });\n return makeValidator({\n test: (value, state) => {\n var _a, _b, _c;\n if (Object.getPrototypeOf(value).toString() === `[object Map]`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const originalValues = [...value];\n const coercedValues = [...value];\n if (!isArrayValidator(coercedValues, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n const updateValue = () => coercedValues.some((val, t) => val[0] !== originalValues[t][0] || val[1] !== originalValues[t][1])\n ? new Map(coercedValues)\n : value;\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, makeLazyCoercionFn(state.coercion, value, updateValue)]);\n return true;\n }\n else {\n let valid = true;\n for (const [key, subValue] of value) {\n valid = keySpec(key, Object.assign({}, state)) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n valid = valueSpec(subValue, Object.assign(Object.assign({}, state), { p: computeKey(state, key) })) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n return valid;\n }\n }\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const store = { value };\n if (Array.isArray(value)) {\n if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n state.coercions.push([(_b = state.p) !== null && _b !== void 0 ? _b : `.`, makeLazyCoercionFn(state.coercion, value, () => new Map(store.value))]);\n return true;\n }\n else {\n if (!isRecordValidator(value, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(store, `value`) })))\n return false;\n state.coercions.push([(_c = state.p) !== null && _c !== void 0 ? _c : `.`, makeLazyCoercionFn(state.coercion, value, () => new Map(Object.entries(store.value)))]);\n return true;\n }\n }\n return pushError(state, `Expected a map (got ${getPrintable(value)})`);\n }\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a\n * tuple whose each value matches the corresponding subspec. Refines the type\n * into a tuple whose each item has the type inferred by the corresponding\n * tuple.\n *\n * Supports coercion if the `delimiter` option is set, in which case strings\n * will be split accordingly.\n */\nfunction isTuple(spec, { delimiter } = {}) {\n const lengthValidator = hasExactLength(spec.length);\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof value === `string` && typeof delimiter !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n value = value.split(delimiter);\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);\n }\n }\n if (!Array.isArray(value))\n return pushError(state, `Expected a tuple (got ${getPrintable(value)})`);\n let valid = lengthValidator(value, Object.assign({}, state));\n for (let t = 0, T = value.length; t < T && t < spec.length; ++t) {\n valid = spec[t](value[t], Object.assign(Object.assign({}, state), { p: computeKey(state, t), coercion: makeCoercionFn(value, t) })) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n return valid;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object with any amount of properties that must all match the provided\n * subspec. Refines the type to `Record<string, T>`, with `T` being the\n * subspec inferred type.\n *\n * Keys can be optionally validated as well by using the `keys` optional\n * subspec parameter.\n */\nfunction isRecord(spec, { keys: keySpec = null, } = {}) {\n const isArrayValidator = isArray(isTuple([keySpec !== null && keySpec !== void 0 ? keySpec : isString(), spec]));\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (Array.isArray(value)) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n value = Object.fromEntries(value);\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);\n return true;\n }\n }\n if (typeof value !== `object` || value === null)\n return pushError(state, `Expected an object (got ${getPrintable(value)})`);\n const keys = Object.keys(value);\n let valid = true;\n for (let t = 0, T = keys.length; t < T && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null); ++t) {\n const key = keys[t];\n const sub = value[key];\n if (key === `__proto__` || key === `constructor`) {\n valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`);\n continue;\n }\n if (keySpec !== null && !keySpec(key, state)) {\n valid = false;\n continue;\n }\n if (!spec(sub, Object.assign(Object.assign({}, state), { p: computeKey(state, key), coercion: makeCoercionFn(value, key) }))) {\n valid = false;\n continue;\n }\n }\n return valid;\n },\n });\n}\n/**\n * @deprecated Replace `isDict` by `isRecord`\n */\nfunction isDict(spec, opts = {}) {\n return isRecord(spec, opts);\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object whose all properties match their corresponding subspec. Refines\n * the type into an object whose each property has the type inferred by the\n * corresponding subspec.\n *\n * Unlike `t.isPartial`, `t.isObject` doesn't allow extraneous properties by\n * default. This behaviour can be altered by using the `extra` optional\n * subspec parameter, which will be called to validate an object only\n * containing the extraneous properties.\n *\n * Calling `t.isObject(..., {extra: t.isRecord(t.isUnknown())})` is\n * essentially the same as calling `t.isPartial(...)`.\n */\nfunction isObject(props, { extra: extraSpec = null, } = {}) {\n const specKeys = Object.keys(props);\n const validator = makeValidator({\n test: (value, state) => {\n if (typeof value !== `object` || value === null)\n return pushError(state, `Expected an object (got ${getPrintable(value)})`);\n const keys = new Set([...specKeys, ...Object.keys(value)]);\n const extra = {};\n let valid = true;\n for (const key of keys) {\n if (key === `constructor` || key === `__proto__`) {\n valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`);\n }\n else {\n const spec = Object.prototype.hasOwnProperty.call(props, key)\n ? props[key]\n : undefined;\n const sub = Object.prototype.hasOwnProperty.call(value, key)\n ? value[key]\n : undefined;\n if (typeof spec !== `undefined`) {\n valid = spec(sub, Object.assign(Object.assign({}, state), { p: computeKey(state, key), coercion: makeCoercionFn(value, key) })) && valid;\n }\n else if (extraSpec === null) {\n valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Extraneous property (got ${getPrintable(sub)})`);\n }\n else {\n Object.defineProperty(extra, key, {\n enumerable: true,\n get: () => sub,\n set: makeSetter(value, key)\n });\n }\n }\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n if (extraSpec !== null && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null))\n valid = extraSpec(extra, state) && valid;\n return valid;\n },\n });\n return Object.assign(validator, {\n properties: props,\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object whose all properties match their corresponding subspec. Refines\n * the type into an object whose each property has the type inferred by the\n * corresponding subspec.\n *\n * Unlike `t.isObject`, `t.isPartial` allows extraneous properties. The\n * resulting type will reflect this behaviour by including an index\n * signature (each extraneous property being typed `unknown`).\n *\n * Calling `t.isPartial(...)` is essentially the same as calling\n * `t.isObject(..., {extra: t.isRecord(t.isUnknown())})`.\n */\nfunction isPartial(props) {\n return isObject(props, { extra: isRecord(isUnknown()) });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object whose prototype is derived from the given class. Refines the type\n * into a class instance.\n */\nconst isInstanceOf = (constructor) => makeValidator({\n test: (value, state) => {\n if (!(value instanceof constructor))\n return pushError(state, `Expected an instance of ${constructor.name} (got ${getPrintable(value)})`);\n return true;\n },\n});\n/**\n * Create a validator that only returns true when the tested value is an\n * object matching any of the provided subspecs. If the optional `exclusive`\n * parameter is set to `true`, the behaviour changes so that the validator\n * only returns true when exactly one subspec matches.\n */\nconst isOneOf = (specs, { exclusive = false, } = {}) => makeValidator({\n test: (value, state) => {\n var _a, _b, _c;\n const matches = [];\n const errorBuffer = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined`\n ? [] : undefined;\n for (let t = 0, T = specs.length; t < T; ++t) {\n const subErrors = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined`\n ? [] : undefined;\n const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`\n ? [] : undefined;\n if (specs[t](value, Object.assign(Object.assign({}, state), { errors: subErrors, coercions: subCoercions, p: `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}#${t + 1}` }))) {\n matches.push([`#${t + 1}`, subCoercions]);\n if (!exclusive) {\n break;\n }\n }\n else {\n errorBuffer === null || errorBuffer === void 0 ? void 0 : errorBuffer.push(subErrors[0]);\n }\n }\n if (matches.length === 1) {\n const [, subCoercions] = matches[0];\n if (typeof subCoercions !== `undefined`)\n (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 ? void 0 : _b.push(...subCoercions);\n return true;\n }\n if (matches.length > 1)\n pushError(state, `Expected to match exactly a single predicate (matched ${matches.join(`, `)})`);\n else\n (_c = state === null || state === void 0 ? void 0 : state.errors) === null || _c === void 0 ? void 0 : _c.push(...errorBuffer);\n return false;\n },\n});\n\nfunction makeTrait(value) {\n return () => {\n return value;\n };\n}\nfunction makeValidator({ test }) {\n return makeTrait(test)();\n}\nclass TypeAssertionError extends Error {\n constructor({ errors } = {}) {\n let errorMessage = `Type mismatch`;\n if (errors && errors.length > 0) {\n errorMessage += `\\n`;\n for (const error of errors) {\n errorMessage += `\\n- ${error}`;\n }\n }\n super(errorMessage);\n }\n}\n/**\n * Check that the specified value matches the given validator, and throws an\n * exception if it doesn't. Refine the type if it passes.\n */\nfunction assert(val, validator) {\n if (!validator(val)) {\n throw new TypeAssertionError();\n }\n}\n/**\n * Check that the specified value matches the given validator, and throws an\n * exception if it doesn't. Refine the type if it passes.\n *\n * Thrown exceptions include details about what exactly looks invalid in the\n * tested value.\n */\nfunction assertWithErrors(val, validator) {\n const errors = [];\n if (!validator(val, { errors })) {\n throw new TypeAssertionError({ errors });\n }\n}\n/**\n * Compile-time only. Refine the type as if the validator was matching the\n * tested value, but doesn't actually run it. Similar to the classic `as`\n * operator in TypeScript.\n */\nfunction softAssert(val, validator) {\n // It's a soft assert; we tell TypeScript about the type, but we don't need to check it\n}\nfunction as(value, validator, { coerce = false, errors: storeErrors, throw: throws } = {}) {\n const errors = storeErrors ? [] : undefined;\n if (!coerce) {\n if (validator(value, { errors })) {\n return throws ? value : { value, errors: undefined };\n }\n else if (!throws) {\n return { value: undefined, errors: errors !== null && errors !== void 0 ? errors : true };\n }\n else {\n throw new TypeAssertionError({ errors });\n }\n }\n const state = { value };\n const coercion = makeCoercionFn(state, `value`);\n const coercions = [];\n if (!validator(value, { errors, coercion, coercions })) {\n if (!throws) {\n return { value: undefined, errors: errors !== null && errors !== void 0 ? errors : true };\n }\n else {\n throw new TypeAssertionError({ errors });\n }\n }\n for (const [, apply] of coercions)\n apply();\n if (throws) {\n return state.value;\n }\n else {\n return { value: state.value, errors: undefined };\n }\n}\n/**\n * Create and return a new function that apply the given validators to each\n * corresponding argument passed to the function and throws an exception in\n * case of a mismatch.\n */\nfunction fn(validators, fn) {\n const isValidArgList = isTuple(validators);\n return ((...args) => {\n const check = isValidArgList(args);\n if (!check)\n throw new TypeAssertionError();\n return fn(...args);\n });\n}\n\n/**\n * Create a validator that checks that the tested array or string has at least\n * the specified length.\n */\nfunction hasMinLength(length) {\n return makeValidator({\n test: (value, state) => {\n if (!(value.length >= length))\n return pushError(state, `Expected to have a length of at least ${length} elements (got ${value.length})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested array or string has at most\n * the specified length.\n */\nfunction hasMaxLength(length) {\n return makeValidator({\n test: (value, state) => {\n if (!(value.length <= length))\n return pushError(state, `Expected to have a length of at most ${length} elements (got ${value.length})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested array or string has exactly\n * the specified length.\n */\nfunction hasExactLength(length) {\n return makeValidator({\n test: (value, state) => {\n if (!(value.length === length))\n return pushError(state, `Expected to have a length of exactly ${length} elements (got ${value.length})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested array only contains unique\n * elements. The optional `map` parameter lets you define a transform to\n * apply before making the check (the result of this transform will be\n * discarded afterwards).\n */\nfunction hasUniqueItems({ map, } = {}) {\n return makeValidator({\n test: (value, state) => {\n const set = new Set();\n const dup = new Set();\n for (let t = 0, T = value.length; t < T; ++t) {\n const sub = value[t];\n const key = typeof map !== `undefined`\n ? map(sub)\n : sub;\n if (set.has(key)) {\n if (dup.has(key))\n continue;\n pushError(state, `Expected to contain unique elements; got a duplicate with ${getPrintable(value)}`);\n dup.add(key);\n }\n else {\n set.add(key);\n }\n }\n return dup.size === 0;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is strictly less than 0.\n */\nfunction isNegative() {\n return makeValidator({\n test: (value, state) => {\n if (!(value <= 0))\n return pushError(state, `Expected to be negative (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is equal or greater\n * than 0.\n */\nfunction isPositive() {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= 0))\n return pushError(state, `Expected to be positive (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is equal or greater\n * than the specified reference.\n */\nfunction isAtLeast(n) {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= n))\n return pushError(state, `Expected to be at least ${n} (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is equal or smaller\n * than the specified reference.\n */\nfunction isAtMost(n) {\n return makeValidator({\n test: (value, state) => {\n if (!(value <= n))\n return pushError(state, `Expected to be at most ${n} (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is between the\n * specified references (including the upper boundary).\n */\nfunction isInInclusiveRange(a, b) {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= a && value <= b))\n return pushError(state, `Expected to be in the [${a}; ${b}] range (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is between the\n * specified references (excluding the upper boundary).\n */\nfunction isInExclusiveRange(a, b) {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= a && value < b))\n return pushError(state, `Expected to be in the [${a}; ${b}[ range (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is an integer.\n *\n * By default Typanion will also check that it's a *safe* integer. For example,\n * 2^53 wouldn't be a safe integer because 2^53+1 would be rounded to 2^53,\n * which could put your applications at risk when used in loops.\n */\nfunction isInteger({ unsafe = false, } = {}) {\n return makeValidator({\n test: (value, state) => {\n if (value !== Math.round(value))\n return pushError(state, `Expected to be an integer (got ${value})`);\n if (!unsafe && !Number.isSafeInteger(value))\n return pushError(state, `Expected to be a safe integer (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string matches the given\n * regular expression.\n */\nfunction matchesRegExp(regExp) {\n return makeValidator({\n test: (value, state) => {\n if (!regExp.test(value))\n return pushError(state, `Expected to match the pattern ${regExp.toString()} (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string only contain lowercase\n * characters.\n */\nfunction isLowerCase() {\n return makeValidator({\n test: (value, state) => {\n if (value !== value.toLowerCase())\n return pushError(state, `Expected to be all-lowercase (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string only contain uppercase\n * characters.\n */\nfunction isUpperCase() {\n return makeValidator({\n test: (value, state) => {\n if (value !== value.toUpperCase())\n return pushError(state, `Expected to be all-uppercase (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is a valid UUID v4.\n */\nfunction isUUID4() {\n return makeValidator({\n test: (value, state) => {\n if (!uuid4RegExp.test(value))\n return pushError(state, `Expected to be a valid UUID v4 (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is a valid ISO8601\n * date.\n */\nfunction isISO8601() {\n return makeValidator({\n test: (value, state) => {\n if (!iso8601RegExp.test(value))\n return pushError(state, `Expected to be a valid ISO 8601 date string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is a valid hexadecimal\n * color. Setting the optional `alpha` parameter to `true` allows an additional\n * transparency channel to be included.\n */\nfunction isHexColor({ alpha = false, }) {\n return makeValidator({\n test: (value, state) => {\n const res = alpha\n ? colorStringRegExp.test(value)\n : colorStringAlphaRegExp.test(value);\n if (!res)\n return pushError(state, `Expected to be a valid hexadecimal color string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is valid base64.\n */\nfunction isBase64() {\n return makeValidator({\n test: (value, state) => {\n if (!base64RegExp.test(value))\n return pushError(state, `Expected to be a valid base 64 string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is valid JSON. A\n * optional spec can be passed as parameter, in which case the data will be\n * deserialized and validated against the spec (coercion will be disabled\n * for this check, and even if successful the returned value will still be\n * the original string).\n */\nfunction isJSON(spec = isUnknown()) {\n return makeValidator({\n test: (value, state) => {\n let data;\n try {\n data = JSON.parse(value);\n }\n catch (_a) {\n return pushError(state, `Expected to be a valid JSON string (got ${getPrintable(value)})`);\n }\n return spec(data, state);\n },\n });\n}\n\nfunction cascade(spec, ...followups) {\n const resolvedFollowups = Array.isArray(followups[0])\n ? followups[0]\n : followups;\n return makeValidator({\n test: (value, state) => {\n var _a, _b;\n const context = { value: value };\n const subCoercion = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`\n ? makeCoercionFn(context, `value`) : undefined;\n const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`\n ? [] : undefined;\n if (!spec(value, Object.assign(Object.assign({}, state), { coercion: subCoercion, coercions: subCoercions })))\n return false;\n const reverts = [];\n if (typeof subCoercions !== `undefined`)\n for (const [, coercion] of subCoercions)\n reverts.push(coercion());\n try {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (context.value !== value) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, context.value)]);\n }\n (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 ? void 0 : _b.push(...subCoercions);\n }\n return resolvedFollowups.every(spec => {\n return spec(context.value, state);\n });\n }\n finally {\n for (const revert of reverts) {\n revert();\n }\n }\n },\n });\n}\nfunction applyCascade(spec, ...followups) {\n const resolvedFollowups = Array.isArray(followups[0])\n ? followups[0]\n : followups;\n return cascade(spec, resolvedFollowups);\n}\n/**\n * Wraps the given spec to also allow `undefined`.\n */\nfunction isOptional(spec) {\n return makeValidator({\n test: (value, state) => {\n if (typeof value === `undefined`)\n return true;\n return spec(value, state);\n },\n });\n}\n/**\n * Wraps the given spec to also allow `null`.\n */\nfunction isNullable(spec) {\n return makeValidator({\n test: (value, state) => {\n if (value === null)\n return true;\n return spec(value, state);\n },\n });\n}\nconst checks = {\n missing: (keys, key) => keys.has(key),\n undefined: (keys, key, value) => keys.has(key) && typeof value[key] !== `undefined`,\n nil: (keys, key, value) => keys.has(key) && value[key] != null,\n falsy: (keys, key, value) => keys.has(key) && !!value[key],\n};\n/**\n * Create a validator that checks that the tested object contains the specified\n * keys.\n*/\nfunction hasRequiredKeys(requiredKeys, options) {\n var _a;\n const requiredSet = new Set(requiredKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n const problems = [];\n for (const key of requiredSet)\n if (!check(keys, key, value))\n problems.push(key);\n if (problems.length > 0)\n return pushError(state, `Missing required ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, `and`)}`);\n return true;\n },\n });\n}\n/**\n* Create a validator that checks that the tested object contains at least one\n* of the specified keys.\n*/\nfunction hasAtLeastOneKey(requiredKeys, options) {\n var _a;\n const requiredSet = new Set(requiredKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = Object.keys(value);\n const valid = keys.some(key => check(requiredSet, key, value));\n if (!valid)\n return pushError(state, `Missing at least one property from ${getPrintableArray(Array.from(requiredSet), `or`)}`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested object contains none of the\n * specified keys.\n*/\nfunction hasForbiddenKeys(forbiddenKeys, options) {\n var _a;\n const forbiddenSet = new Set(forbiddenKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n const problems = [];\n for (const key of forbiddenSet)\n if (check(keys, key, value))\n problems.push(key);\n if (problems.length > 0)\n return pushError(state, `Forbidden ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, `and`)}`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested object contains at most one\n * of the specified keys.\n */\nfunction hasMutuallyExclusiveKeys(exclusiveKeys, options) {\n var _a;\n const exclusiveSet = new Set(exclusiveKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n const used = [];\n for (const key of exclusiveSet)\n if (check(keys, key, value))\n used.push(key);\n if (used.length > 1)\n return pushError(state, `Mutually exclusive properties ${getPrintableArray(used, `and`)}`);\n return true;\n },\n });\n}\nvar KeyRelationship;\n(function (KeyRelationship) {\n KeyRelationship[\"Forbids\"] = \"Forbids\";\n KeyRelationship[\"Requires\"] = \"Requires\";\n})(KeyRelationship || (KeyRelationship = {}));\nconst keyRelationships = {\n [KeyRelationship.Forbids]: {\n expect: false,\n message: `forbids using`,\n },\n [KeyRelationship.Requires]: {\n expect: true,\n message: `requires using`,\n },\n};\n/**\n * Create a validator that checks that, when the specified subject property is\n * set, the relationship is satisfied.\n */\nfunction hasKeyRelationship(subject, relationship, others, options) {\n var _a, _b;\n const skipped = new Set((_a = options === null || options === void 0 ? void 0 : options.ignore) !== null && _a !== void 0 ? _a : []);\n const check = checks[(_b = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _b !== void 0 ? _b : 'missing'];\n const otherSet = new Set(others);\n const spec = keyRelationships[relationship];\n const conjunction = relationship === KeyRelationship.Forbids\n ? `or`\n : `and`;\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n if (!check(keys, subject, value) || skipped.has(value[subject]))\n return true;\n const problems = [];\n for (const key of otherSet)\n if ((check(keys, key, value) && !skipped.has(value[key])) !== spec.expect)\n problems.push(key);\n if (problems.length >= 1)\n return pushError(state, `Property \"${subject}\" ${spec.message} ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, conjunction)}`);\n return true;\n },\n });\n}\n\nexport { KeyRelationship, TypeAssertionError, applyCascade, as, assert, assertWithErrors, cascade, fn, hasAtLeastOneKey, hasExactLength, hasForbiddenKeys, hasKeyRelationship, hasMaxLength, hasMinLength, hasMutuallyExclusiveKeys, hasRequiredKeys, hasUniqueItems, isArray, isAtLeast, isAtMost, isBase64, isBoolean, isDate, isDict, isEnum, isHexColor, isISO8601, isInExclusiveRange, isInInclusiveRange, isInstanceOf, isInteger, isJSON, isLiteral, isLowerCase, isMap, isNegative, isNullable, isNumber, isObject, isOneOf, isOptional, isPartial, isPayload, isPositive, isRecord, isSet, isString, isTuple, isUUID4, isUnknown, isUpperCase, makeTrait, makeValidator, matchesRegExp, softAssert };\n","import path from 'node:path';\nimport { printSchema } from 'graphql';\nimport type { GraphQLSchema } from 'graphql';\nimport { load } from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, writeOutput } from '../shared';\nimport * as logger from './logger';\n\nexport interface SchemaOptions {\n /** The filename to a `.graphql` SDL file, introspection JSON, or URL to a GraphQL API to introspect. */\n input: string;\n /** Object of headers to send when introspection a GraphQL API. */\n headers: Record<string, string> | undefined;\n /** The filename to write the GraphQL SDL file to.\n * @defaultValue The `schema` configuration option */\n output: string | undefined;\n /** The `tsconfig.json` to use for configurations and the TypeScript program.\n * @defaultValue A `tsconfig.json` in the current or any parent directory. */\n tsconfig: string | undefined;\n /** Whether to disable terminal output when using the programmatic API.\n * @defaultValue `false` */\n silent?: boolean;\n}\n\nexport async function* run(tty: TTY, opts: SchemaOptions): AsyncIterable<ComposeInput> {\n const origin = opts.headers ? { url: opts.input, headers: opts.headers } : opts.input;\n const loader = load({ rootPath: process.cwd(), origin });\n\n let schema: GraphQLSchema;\n try {\n const loadResult = await loader.load();\n schema = loadResult.schema;\n } catch (error) {\n throw logger.externalError('Failed to load schema.', error);\n }\n\n let destination: WriteTarget;\n if (!opts.output && tty.pipeTo) {\n destination = tty.pipeTo;\n } else if (opts.output) {\n destination = path.resolve(process.cwd(), opts.output);\n } else {\n let projects: ProjectContext[];\n try {\n projects = await loadProjects(opts.tsconfig);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n if (projects.length > 1) {\n throw logger.errorMessage(\n `Output path cannot be automatically determined when multiple projects are configured,\\n` +\n `because multiple projects are set up through ${logger.code('\"references\"')}.` +\n logger.hint(\n `You have to explicitly pass an ${logger.code(\n '--output'\n )} argument to this command,\\n` + 'or pipe this command to an output file.'\n )\n );\n }\n\n const { pluginConfig, projectPath } = projects[0];\n if (\n 'schema' in pluginConfig &&\n typeof pluginConfig.schema === 'string' &&\n path.extname(pluginConfig.schema) === '.graphql'\n ) {\n destination = path.resolve(projectPath, pluginConfig.schema);\n } else if (!('schema' in pluginConfig)) {\n throw logger.errorMessage(\n `Output path cannot be automatically determined when multiple schemas are configured,\\n` +\n `because multiple ${logger.code('schemas')} are set up.` +\n logger.hint(\n `You have to explicitly pass an ${logger.code(\n '--output'\n )} argument to this command,\\n` + 'or pipe this command to an output file.'\n )\n );\n } else {\n throw logger.errorMessage(\n `Output path cannot be automatically determined,\\n` +\n `because ${logger.code('schema')} is not a file path.\\n` +\n logger.hint(\n `You have to either set ${logger.code(\n '\"schema\"'\n )} in your configuration to a ${logger.code('.graphql')} file,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n }\n }\n\n try {\n await writeOutput(destination, printSchema(schema));\n } catch (error) {\n throw logger.externalError('Something went wrong while writing the introspection file', error);\n }\n\n yield logger.summary();\n}\n","import * as t from '../../term';\n\nexport * from '../shared/logger';\n\nexport function summary() {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Schema was generated successfully\\n`,\n ]);\n}\n","import * as t from 'typanion';\nimport { Command, Option } from 'clipanion';\n\nimport { exitCode } from '../../utils/error';\nimport type { SchemaOptions } from './runner';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nconst isHeaderEntries = t.isArray(t.cascade(t.isString(), t.matchesRegExp(/^[\\w-]+[ ]*:[ ]*.+/i)));\n\nconst parseHeaders = (\n headers: readonly string[] | undefined\n): Record<string, string> | undefined => {\n if (headers && headers.length) {\n return (headers || []).reduce((headers, entry) => {\n const index = entry.indexOf(':');\n const key = entry.slice(0, index);\n const value = entry.slice(index + 1);\n headers[key.trimEnd()] = value.trimStart();\n return headers;\n }, {});\n }\n};\n\nexport class GenerateSchema extends Command {\n static paths = [['generate-schema'], ['generate', 'schema']];\n\n input = Option.String({\n name: 'schema',\n required: true,\n });\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` used to read, unless `--output` is passed.',\n });\n\n output = Option.String('--output,-o', {\n description:\n \"Specify where to output the file to.\\tDefault: The `schema` configuration option, if it's a file path\",\n });\n\n headers = Option.Array('--header', {\n description: 'Headers to be used when introspection a schema from a remote URL',\n validator: isHeaderEntries,\n });\n\n async execute() {\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n input: this.input,\n headers: parseHeaders(this.headers),\n output: this.output,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Generates a GraphQL SDL file from a given GraphQL API URL or schema file.\n *\n * @remarks\n * Introspects a targeted GraphQL API by URL, a `.graphql` SDL or introspection\n * JSON file, and outputs a `.graphql` SDL file.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#generateschema}\n */\nexport async function generateSchema(opts: SchemaOptions) {\n const tty = initTTY({ disableTTY: true, silent: opts.silent });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","import { makeCommandOption, applyValidator, rerouteArguments } from './utils.mjs';\n\nfunction Array(descriptor, initialValueBase, optsBase) {\n const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});\n const { arity = 1 } = opts;\n const optNames = descriptor.split(`,`);\n const nameSet = new Set(optNames);\n return makeCommandOption({\n definition(builder) {\n builder.addOption({\n names: optNames,\n arity,\n hidden: opts === null || opts === void 0 ? void 0 : opts.hidden,\n description: opts === null || opts === void 0 ? void 0 : opts.description,\n required: opts.required,\n });\n },\n transformer(builder, key, state) {\n let usedName;\n let currentValue = typeof initialValue !== `undefined`\n ? [...initialValue]\n : undefined;\n for (const { name, value } of state.options) {\n if (!nameSet.has(name))\n continue;\n usedName = name;\n currentValue = currentValue !== null && currentValue !== void 0 ? currentValue : [];\n currentValue.push(value);\n }\n if (typeof currentValue !== `undefined`) {\n return applyValidator(usedName !== null && usedName !== void 0 ? usedName : key, currentValue, opts.validator);\n }\n else {\n return currentValue;\n }\n },\n });\n}\n\nexport { Array };\n","import { pipe, interval, map, concat, fromValue } from 'wonka';\n\nimport * as path from 'node:path';\nimport * as t from '../../term';\n\nimport type { TurboWarning } from './types';\nimport { indent } from '../shared/logger';\n\nexport * from '../shared/logger';\n\nconst CWD = process.cwd();\nconst INDENT = ' ';\n\nexport function warningFile(filePath: string) {\n const relativePath = path.relative(CWD, filePath);\n if (!relativePath.startsWith('..')) filePath = relativePath;\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Underline),\n filePath,\n t.cmd(t.CSI.Style, t.Style.NoUnderline),\n '\\n',\n ]);\n}\n\nexport function warningMessage(message: TurboWarning) {\n return t.text([\n INDENT,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${message.line}:${message.col}`,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n indent(message.message.trim(), t.text([INDENT, t.Chars.Tab])),\n t.Chars.Newline,\n ]);\n}\n\nconst reusedLabel = (count: number | undefined) => (count ? `, ${count} reused` : '');\n\nconst documentSummary = (\n documentCount: number | Record<string, number>,\n cachedCount?: number | Record<string, number>\n) => {\n let out = '';\n if (typeof documentCount === 'number') {\n const cachedLabel = reusedLabel(typeof cachedCount === 'number' ? cachedCount : undefined);\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Type cache was generated successfully `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `(${documentCount} document types cached${cachedLabel})\\n`,\n ]);\n } else {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Type caches were generated successfully.\\n`,\n ]);\n for (const schemaName in documentCount) {\n const cachedLabel = reusedLabel(\n cachedCount && typeof cachedCount !== 'number' ? cachedCount[schemaName] : undefined\n );\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${documentCount[schemaName]} document types cached for the '${schemaName}' schema${cachedLabel}\\n`,\n ]);\n }\n }\n return out;\n};\n\nexport function warningSummary(warningCount: number) {\n return t.error([t.cmd(t.CSI.Style, t.Style.Red), `${t.Icons.Cross} ${warningCount} warnings\\n`]);\n}\n\nexport function infoSummary(\n warningCount: number,\n documentCount: number | Record<string, number>,\n cachedCount?: number | Record<string, number>\n) {\n let out = '';\n if (warningCount) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ` ${warningCount} warnings\\n`,\n ]);\n }\n out += documentSummary(documentCount, cachedCount);\n return out;\n}\n\nexport function warningGithub(message: TurboWarning): void {\n t.githubAnnotation('warning', message.message, {\n file: message.file,\n line: message.line,\n col: message.col,\n });\n}\n\nexport function runningTurbo(file?: number, ofFiles?: number) {\n const progress = file ? (ofFiles ? `(${file}/${ofFiles})` : `(${file})`) : '';\n const frame = (state: number) =>\n t.text([\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.dotSpinner[state % t.dotSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n `Scanning files${t.Chars.Ellipsis} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n progress,\n ]);\n return concat([\n fromValue(frame(0)),\n pipe(\n interval(150),\n map((state) => frame(state + 1))\n ),\n ]);\n}\n\nexport function hintMessage(message: string) {\n return t.error([\n t.cmd(t.CSI.Style, [t.Style.Yellow, t.Style.Bold]),\n `${t.Icons.Warning} Note: `,\n t.cmd(t.CSI.Style, t.Style.Reset),\n `${message.trim()}\\n\\n`,\n ]);\n}\n","import * as path from 'node:path';\n\nimport { extractIntrospectionHeader } from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, writeOutput, readOutput } from '../shared';\nimport type { TurboDocument, GraphQLSourceFile, TurboPath } from './types';\nimport * as logger from './logger';\n\nconst PREAMBLE_IGNORE = ['/* eslint-disable */', '/* prettier-ignore */'].join('\\n') + '\\n';\n\nexport interface TurboOptions {\n /** Whether to fail instead of just logging a warning. */\n failOnWarn: boolean;\n /** The `tsconfig.json` to use for configurations and the TypeScript program.\n * @defaultValue A `tsconfig.json` in the current or any parent directory. */\n tsconfig: string | undefined;\n /** The filename to write the cache file to.\n * @defaultValue The `tadaTurboLocation` configuration option */\n output: string | undefined;\n}\n\nexport async function* run(tty: TTY, opts: TurboOptions): AsyncIterable<ComposeInput> {\n let projects: ProjectContext[];\n try {\n projects = await loadProjects(opts.tsconfig);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n if (projects.length > 1 && (opts.output || tty.pipeTo)) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple projects are configured.\\n' +\n logger.hint(\n `You can only output all projects to their ${logger.code(\n '\"tadaTurboLocation\"'\n )} options\\n` +\n `when multiple projects are set up through ${logger.code('\"references\"')}.`\n )\n );\n }\n\n let totalWarnings = 0;\n let failedProjects = false;\n for (const project of projects) {\n if (projects.length > 1) yield logger.projectHeader(project.label);\n const result = yield* runProject(tty, opts, project, projects.length > 1);\n totalWarnings += result.warnings;\n failedProjects = failedProjects || result.failed;\n }\n\n if (failedProjects) {\n throw logger.warningSummary(totalWarnings);\n }\n}\n\ninterface ProjectResult {\n warnings: number;\n failed: boolean;\n}\n\n/** Runs the turbo cache generation for a single project. */\nasync function* runProject(\n tty: TTY,\n opts: TurboOptions,\n project: ProjectContext,\n deferWarnings: boolean\n): AsyncGenerator<ComposeInput, ProjectResult> {\n const { runTurbo } = await import('./thread');\n\n const { pluginConfig, projectPath } = project;\n\n let destination: WriteTarget;\n const destinations: TurboPath[] = [];\n if ('schema' in pluginConfig) {\n if (!opts.output && tty.pipeTo) {\n destination = tty.pipeTo;\n } else if (opts.output) {\n destination = path.resolve(process.cwd(), opts.output);\n } else if (pluginConfig.tadaTurboLocation) {\n destination = path.resolve(projectPath, pluginConfig.tadaTurboLocation);\n } else if (pluginConfig.tadaOutputLocation) {\n destination = path.resolve(\n projectPath,\n pluginConfig.tadaOutputLocation,\n '..',\n 'graphql-cache.d.ts'\n );\n yield logger.hintMessage(\n 'No output location was specified.\\n' +\n `The turbo cache will by default be saved as ${logger.code('\"graphql-cache.d.ts\"')}.\\n` +\n logger.hint(\n `To change this, add a ${logger.code('\"tadaTurboLocation\"')} in your configuration,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n } else {\n throw logger.errorMessage(\n 'No output path was specified to write the output file to.\\n' +\n logger.hint(\n `You have to either set ${logger.code('\"tadaTurboLocation\"')} in your configuration,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n }\n } else if ('schemas' in pluginConfig) {\n for (const schemaConfig of pluginConfig.schemas) {\n if (schemaConfig.tadaTurboLocation)\n destinations.push({\n path: path.resolve(projectPath, schemaConfig.tadaTurboLocation),\n schemaName: schemaConfig.name,\n });\n }\n }\n\n const generator = runTurbo({\n rootPath: project.configResult.rootPath,\n tsconfigPath: project.configResult.tsconfigPath,\n configPath: project.configResult.configPath,\n pluginConfig,\n turboOutputPath: typeof destination! === 'string' ? destination : destinations,\n });\n\n const documents: TurboDocument[] = [];\n let graphqlSources: GraphQLSourceFile[] = [];\n let warnings = 0;\n let totalFileCount = 0;\n let fileCount = 0;\n let cachedDocumentCount = 0;\n\n try {\n if (tty.isInteractive) yield logger.runningTurbo();\n\n for await (const signal of generator) {\n if (signal.kind === 'EXTERNAL_WARNING') {\n yield logger.experimentMessage(\n `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n );\n } else if (signal.kind === 'FILE_COUNT') {\n totalFileCount = signal.fileCount;\n } else if (signal.kind === 'GRAPHQL_SOURCES') {\n graphqlSources = signal.sources;\n } else {\n fileCount++;\n documents.push(...signal.documents);\n cachedDocumentCount += signal.documents.filter((document) => document.isCached).length;\n warnings += signal.warnings.length;\n if (signal.warnings.length) {\n let buffer = logger.warningFile(signal.filePath);\n for (const warning of signal.warnings) {\n buffer += logger.warningMessage(warning);\n logger.warningGithub(warning);\n }\n yield buffer + '\\n';\n }\n }\n\n if (tty.isInteractive) yield logger.runningTurbo(fileCount, totalFileCount);\n }\n } catch (error) {\n throw logger.externalError('Could not build cache', error);\n }\n\n if ('schema' in pluginConfig) {\n if (warnings && opts.failOnWarn) {\n if (!deferWarnings) throw logger.warningSummary(warnings);\n return { warnings, failed: true };\n }\n\n try {\n const existing = await readOutput(destination!);\n const contents = createCacheContents(documents, graphqlSources, destination!, existing);\n await writeOutput(destination!, contents);\n } catch (error) {\n throw logger.externalError('Something went wrong while writing the type cache file', error);\n }\n\n yield logger.infoSummary(warnings, documents.length, cachedDocumentCount);\n } else {\n if (opts.output) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple schemas are configured.\\n' +\n logger.hint(\n `You can only output all schemas to their ${logger.code(\n '\"tadaTurboLocation\"'\n )} options\\n` + `when multiple ${logger.code('schemas')} are set up.`\n )\n );\n }\n\n const documentCount: Record<string, number> = {};\n const cachedCount: Record<string, number> = {};\n for (const schemaConfig of pluginConfig.schemas) {\n const { name, tadaTurboLocation } = schemaConfig;\n if (!tadaTurboLocation) {\n throw logger.errorMessage(\n `No output path was specified to write the '${name}' type cache to.\\n` +\n logger.hint(\n `You have to set ${logger.code('\"tadaTurboLocation\"')} in each schema configuration.`\n )\n );\n }\n\n try {\n documentCount[name] = 0;\n cachedCount[name] = 0;\n const cache: TurboDocument[] = [];\n for (const item of documents) {\n if (item.schemaName === name) {\n cache.push(item);\n documentCount[name]++;\n if (item.isCached) cachedCount[name]++;\n }\n }\n const destination = path.resolve(projectPath, tadaTurboLocation);\n const existing = await readOutput(destination);\n const contents = createCacheContents(cache, graphqlSources, destination, existing);\n await writeOutput(destination, contents);\n } catch (error) {\n throw logger.externalError(\n `Something went wrong while writing the '${name}' schema's type cache file.`,\n error\n );\n }\n }\n\n if (warnings && opts.failOnWarn) {\n if (!deferWarnings) throw logger.warningSummary(warnings);\n return { warnings, failed: true };\n } else {\n yield logger.infoSummary(warnings, documentCount, cachedCount);\n }\n }\n\n return { warnings, failed: false };\n}\n\nexport function createCacheContents(\n cache: TurboDocument[],\n graphqlSources: GraphQLSourceFile[],\n turboDestination: WriteTarget,\n existing?: string\n): string {\n const preamble = (existing && extractIntrospectionHeader(existing)) || PREAMBLE_IGNORE;\n const documentsByKey = new Map<string, TurboDocument>();\n for (const document of cache) documentsByKey.set(document.argumentKey, document);\n\n // Entries are sorted so the output only depends on the set of documents,\n // rather than the order files are traversed in. This keeps the file stable across\n // refactors and reduces line adjacency of unrelated changes in merge conflicts\n const documents = [...documentsByKey.values()].sort((a, b) =>\n compareUtf16(a.argumentKey, b.argumentKey)\n );\n\n let output = '';\n for (const document of documents) {\n if (output) output += '\\n';\n if (document.documentHash) output += ` /** @gql.tada/hash ${document.documentHash} */\\n`;\n output += ` ${document.argumentKey}:\\n ${document.documentType};`;\n }\n\n let imports = \"import type { TadaDocumentNode, $tada } from 'gql.tada';\\n\";\n\n const isFilePath =\n typeof turboDestination === 'string' ||\n (turboDestination &&\n typeof turboDestination === 'object' &&\n 'toString' in turboDestination &&\n !('writable' in turboDestination));\n\n // Sources are sorted by path for the same reason documents are sorted above\n const sortedSources = [...graphqlSources].sort((a, b) =>\n compareUtf16(a.absolutePath, b.absolutePath)\n );\n\n const addedImports = new Set<string>();\n for (const source of sortedSources) {\n for (const importInfo of source.imports) {\n if (isFilePath) {\n const turboPath = turboDestination.toString();\n const sourceDir = path.dirname(source.absolutePath);\n const absoluteImportPath = path.resolve(sourceDir, importInfo.specifier);\n const absoluteTurboPath = path.resolve(turboPath);\n\n if (absoluteImportPath === absoluteTurboPath || addedImports.has(importInfo.specifier))\n continue;\n\n addedImports.add(importInfo.specifier);\n }\n\n imports += importInfo.importClause + '\\n';\n }\n }\n\n return (\n preamble +\n imports +\n '\\n' +\n \"declare module 'gql.tada' {\\n\" +\n ' interface setupCache {\\n' +\n output +\n '\\n }' +\n '\\n}\\n'\n );\n}\n\nfunction compareUtf16(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","import { Command, Option } from 'clipanion';\n\nimport type { TurboOptions } from './runner';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class TurboCommand extends Command {\n static paths = [['generate', 'turbo'], ['turbo']];\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` read for configuration.',\n });\n\n failOnWarn = Option.Boolean('--fail-on-warn,-w', false, {\n description: 'Triggers an error and a non-zero exit code if any warnings have been reported',\n });\n\n output = Option.String('--output,-o', {\n description:\n 'Specifies where to output the file to.\\tDefault: The `tadaTurboLocation` configuration option',\n });\n\n async execute() {\n // TODO: Add verbose/log/list/debug/trace option that outputs discovered documents (by name) per file\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n failOnWarn: this.failOnWarn,\n output: this.output,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Generates a cache typings file for all GraphQL document types ahead of time.\n *\n * @remarks\n * The `generateTurbo()` function generates a cache for all GraphQL document types ahead of time.\n * This cache speeds up type evaluation and is especially useful when it's checked into the\n * repository after making changes to GraphQL documents, which speeds up all further type\n * checks and evaluation.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#generateturbo}\n */\nexport async function generateTurbo(opts: TurboOptions) {\n const tty = initTTY({ disableTTY: true });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","import * as path from 'node:path';\n\nexport interface ModuleReach {\n /** The module itself plus every module that transitively depends on it. */\n modules: string[];\n /** Distinct areas covered by {@link modules}. */\n areas: string[];\n /** Entry points among {@link modules}. */\n entryPoints: string[];\n}\n\n/**\n * The project's static module dependency graph (file → its project imports).\n *\n * A self-contained, reusable structure: all reachability/area analytics live\n * here and are memoised internally, so the {@link ScanContext} exposes it as a\n * single primitive and rules can do graph analysis without the context growing.\n */\nexport class ModuleGraph {\n private readonly _edges: Map<string, readonly string[]>;\n private readonly _cwd: string;\n private _reverse: Map<string, Set<string>> | undefined;\n private _entryPoints: Set<string> | undefined;\n private _distance: Map<string, number> | undefined;\n private readonly _dependents = new Map<string, Set<string>>();\n\n constructor(edges: Map<string, string[]>, cwd: string = process.cwd()) {\n this._edges = edges;\n this._cwd = cwd;\n }\n\n /** All import edges (module → the project modules it imports). */\n importMap(): ReadonlyMap<string, readonly string[]> {\n return this._edges;\n }\n\n /** The \"area\" a module belongs to: its directory, relative to the cwd. */\n areaOf(modulePath: string): string {\n const rel = path.relative(this._cwd, modulePath);\n const dir = path.dirname(!rel.startsWith('..') ? rel : modulePath);\n return dir === '.' ? '(root)' : dir;\n }\n\n /** Modules that nothing else imports — the roots of the graph. */\n entryPoints(): Set<string> {\n if (this._entryPoints) return this._entryPoints;\n const nodes = new Set<string>();\n const targets = new Set<string>();\n for (const [from, tos] of this._edges) {\n nodes.add(from);\n for (const to of tos) {\n nodes.add(to);\n targets.add(to);\n }\n }\n return (this._entryPoints = new Set([...nodes].filter((node) => !targets.has(node))));\n }\n\n /** Modules that transitively import the given module (its reverse closure). */\n dependents(modulePath: string): Set<string> {\n const cached = this._dependents.get(modulePath);\n if (cached) return cached;\n\n const reverse = this._reverseGraph();\n const result = new Set<string>();\n const stack = [...(reverse.get(modulePath) || [])];\n let node: string | undefined;\n while ((node = stack.pop())) {\n if (result.has(node)) continue;\n result.add(node);\n stack.push(...(reverse.get(node) || []));\n }\n\n this._dependents.set(modulePath, result);\n return result;\n }\n\n /** Shortest distance from any entry point to the module (entry points are 0). */\n distanceFromEntry(modulePath: string): number | undefined {\n if (!this._distance) {\n const distance = new Map<string, number>();\n let frontier = [...this.entryPoints()];\n let depth = 0;\n while (frontier.length) {\n const next: string[] = [];\n for (const node of frontier) {\n if (distance.has(node)) continue;\n distance.set(node, depth);\n for (const to of this._edges.get(node) || []) {\n if (!distance.has(to)) next.push(to);\n }\n }\n frontier = next;\n depth++;\n }\n this._distance = distance;\n }\n return this._distance.get(modulePath);\n }\n\n /** The blast radius of a module: itself plus everything that depends on it. */\n reach(modulePath: string): ModuleReach {\n const entryPoints = this.entryPoints();\n const modules = new Set<string>([modulePath, ...this.dependents(modulePath)]);\n const areas = new Set<string>();\n const reachedEntries = new Set<string>();\n for (const module of modules) {\n areas.add(this.areaOf(module));\n if (entryPoints.has(module)) reachedEntries.add(module);\n }\n return { modules: [...modules], areas: [...areas].sort(), entryPoints: [...reachedEntries] };\n }\n\n private _reverseGraph(): Map<string, Set<string>> {\n if (this._reverse) return this._reverse;\n const reverse = new Map<string, Set<string>>();\n for (const [from, tos] of this._edges) {\n for (const to of tos) {\n let importers = reverse.get(to);\n if (!importers) reverse.set(to, (importers = new Set()));\n importers.add(from);\n }\n }\n return (this._reverse = reverse);\n }\n}\n","import type { SchemaName } from './types';\n\nexport interface FragmentGraphDefinition {\n id: string;\n kind: 'operation' | 'fragment';\n schemaName: SchemaName;\n /** The fragment's name (present for fragment definitions). */\n name?: string;\n /** Names of fragments spread directly by this definition. */\n fragmentSpreads: readonly string[];\n}\n\nconst key = (schemaName: SchemaName, name: string): string => `${schemaName ?? ''}\\0${name}`;\n\n/**\n * The fragment spread graph: resolution by name and reachability between\n * definitions.\n *\n * A self-contained, reusable structure (the GraphQL-side analogue of\n * {@link ModuleGraph}). Reachability is memoised internally, so the\n * {@link ScanContext} exposes it as a single primitive and rules can do\n * fragment-graph analysis without the context growing per rule.\n */\nexport class FragmentGraph {\n private readonly _byId = new Map<string, FragmentGraphDefinition>();\n private readonly _idByName = new Map<string, string>();\n private readonly _operationIds: string[] = [];\n private readonly _reachable = new Map<string, Set<string>>();\n private _operationsReaching: Map<string, Set<string>> | undefined;\n\n constructor(definitions: readonly FragmentGraphDefinition[]) {\n for (const definition of definitions) {\n this._byId.set(definition.id, definition);\n if (definition.kind === 'operation') {\n this._operationIds.push(definition.id);\n } else if (definition.name != null) {\n this._idByName.set(key(definition.schemaName, definition.name), definition.id);\n }\n }\n }\n\n /** Resolves a fragment name to its id within a schema. */\n resolve(schemaName: SchemaName, name: string): string | undefined {\n return this._idByName.get(key(schemaName, name));\n }\n\n /** Ids of fragments reachable from a definition via (nested) spreads. */\n reachableFragments(definitionId: string): Set<string> {\n const cached = this._reachable.get(definitionId);\n if (cached) return cached;\n\n const result = new Set<string>();\n const start = this._byId.get(definitionId);\n if (start) {\n const stack = [...start.fragmentSpreads];\n let name: string | undefined;\n while ((name = stack.pop())) {\n const id = this.resolve(start.schemaName, name);\n if (!id || result.has(id)) continue;\n result.add(id);\n const fragment = this._byId.get(id);\n if (fragment) stack.push(...fragment.fragmentSpreads);\n }\n }\n\n this._reachable.set(definitionId, result);\n return result;\n }\n\n /** Operation ids that reach a fragment directly or transitively. */\n operationsReaching(fragmentId: string): Set<string> {\n if (!this._operationsReaching) {\n const map = new Map<string, Set<string>>();\n for (const operationId of this._operationIds) {\n for (const reachableId of this.reachableFragments(operationId)) {\n let set = map.get(reachableId);\n if (!set) map.set(reachableId, (set = new Set()));\n set.add(operationId);\n }\n }\n this._operationsReaching = map;\n }\n return this._operationsReaching.get(fragmentId) || new Set();\n }\n}\n","import * as crypto from 'node:crypto';\nimport * as path from 'node:path';\nimport { parse, print, visit, Kind } from 'graphql';\nimport type {\n GraphQLSchema,\n GraphQLCompositeType,\n GraphQLField,\n GraphQLOutputType,\n GraphQLInputType,\n GraphQLEnumValue,\n TypeInfo,\n ASTNode,\n ASTVisitor,\n DefinitionNode,\n OperationDefinitionNode,\n FragmentDefinitionNode,\n} from 'graphql';\n\nimport type {\n SchemaName,\n RawScanDocument,\n ScanWarning,\n ModuleInfo,\n OperationInfo,\n FragmentInfo,\n DefinitionRecord,\n} from './types';\nimport { ModuleGraph } from './module-graph';\nimport { FragmentGraph } from './fragment-graph';\nimport type { FragmentGraphDefinition } from './fragment-graph';\n\nconst CWD = process.cwd();\n\nexport interface ScanContextParams {\n documents: RawScanDocument[];\n schemas: Map<SchemaName, GraphQLSchema>;\n imports: Map<string, string[]>;\n warnings: ScanWarning[];\n}\n\nconst hashOf = (input: string): string =>\n crypto.createHash('sha256').update(input).digest('hex').slice(0, 16);\n\n/** Collects the names of fragments spread anywhere within a definition. */\nfunction collectFragmentSpreads(node: DefinitionNode): string[] {\n const names = new Set<string>();\n visit(node, {\n FragmentSpread(spread) {\n names.add(spread.name.value);\n },\n });\n return [...names];\n}\n\n/**\n * Shared state passed to every scan rule, modelled on graphql-js's\n * `ValidationContext`.\n *\n * It exposes only *primitives*: the loaded schemas, the corpus of discovered\n * definitions (identities + AST nodes), fragment resolution, structural\n * reachability helpers, and TypeInfo-backed accessors for the current\n * traversal position. It never holds derived insight data — rules build that\n * themselves.\n */\nexport class ScanContext {\n private readonly _schemas: Map<SchemaName, GraphQLSchema>;\n private readonly _warnings: ScanWarning[];\n private readonly _operations: OperationInfo[] = [];\n private readonly _fragments: FragmentInfo[] = [];\n private readonly _definitions: DefinitionRecord[] = [];\n private readonly _recordByNode = new Map<ASTNode, DefinitionRecord>();\n private readonly _recordById = new Map<string, DefinitionRecord>();\n private readonly _modules: ModuleInfo[];\n\n private _typeInfo: TypeInfo | null = null;\n private _currentDefinition: DefinitionRecord | null = null;\n\n // Static module dependency graph (every scanned file → its project imports).\n private readonly _importGraph: Map<string, string[]>;\n private _moduleGraph: ModuleGraph | undefined;\n private _fragmentGraph: FragmentGraph | undefined;\n\n constructor(params: ScanContextParams) {\n this._schemas = params.schemas;\n this._warnings = [...params.warnings];\n this._importGraph = params.imports;\n this._buildCorpus(params.documents);\n this._modules = this._buildModules(params.imports);\n }\n\n /* -- Corpus accessors (base facts) -- */\n\n get operations(): readonly OperationInfo[] {\n return this._operations;\n }\n\n get fragments(): readonly FragmentInfo[] {\n return this._fragments;\n }\n\n get modules(): readonly ModuleInfo[] {\n return this._modules;\n }\n\n get warnings(): readonly ScanWarning[] {\n return this._warnings;\n }\n\n getSchemas(): Map<SchemaName, GraphQLSchema> {\n return this._schemas;\n }\n\n /** Definition AST nodes for a single schema, for per-schema traversal. */\n definitionNodesForSchema(schemaName: SchemaName): DefinitionNode[] {\n const nodes: DefinitionNode[] = [];\n for (const record of this._definitions) {\n if (record.schemaName === schemaName) nodes.push(record.node);\n }\n return nodes;\n }\n\n /* -- Traversal primitives (set by the driver) -- */\n\n /** @internal Used by the driver to bind the active schema's TypeInfo. */\n setTypeInfo(typeInfo: TypeInfo): void {\n this._typeInfo = typeInfo;\n }\n\n /** A visitor the driver runs first so rules can read the current definition. */\n trackingVisitor(): ASTVisitor {\n return {\n OperationDefinition: {\n enter: (node) => void (this._currentDefinition = this._recordByNode.get(node) || null),\n leave: () => void (this._currentDefinition = null),\n },\n FragmentDefinition: {\n enter: (node) => void (this._currentDefinition = this._recordByNode.get(node) || null),\n leave: () => void (this._currentDefinition = null),\n },\n };\n }\n\n getCurrentDefinition(): DefinitionRecord | null {\n return this._currentDefinition;\n }\n\n getParentType(): GraphQLCompositeType | null | undefined {\n return this._typeInfo?.getParentType();\n }\n\n /** The current output type at this traversal position — the third TypeInfo\n * accessor alongside {@link getParentType} and {@link getFieldDef}. Unused\n * today, but kept as a generic primitive for rules that inspect return types\n * (e.g. list/non-null wrapping) without the context having to grow. */\n getType(): GraphQLOutputType | null | undefined {\n return this._typeInfo?.getType();\n }\n\n getFieldDef(): GraphQLField<unknown, unknown> | null | undefined {\n return this._typeInfo?.getFieldDef();\n }\n\n /** The input type expected at this position (argument / input-field / list value). */\n getInputType(): GraphQLInputType | null | undefined {\n return this._typeInfo?.getInputType();\n }\n\n /** The enclosing input-object type when inside an input object literal. */\n getParentInputType(): GraphQLInputType | null | undefined {\n return this._typeInfo?.getParentInputType();\n }\n\n /** The enum value definition at the current position, if any. */\n getEnumValue(): GraphQLEnumValue | null | undefined {\n return this._typeInfo?.getEnumValue();\n }\n\n /* -- Generic primitives for graph-level rules -- */\n\n /** The project's static module dependency graph, as a reusable structure.\n * All reachability/area analysis lives on it, so graph rules need no bespoke\n * context methods. */\n getModuleGraph(): ModuleGraph {\n return (this._moduleGraph ??= new ModuleGraph(this._importGraph, CWD));\n }\n\n /** The fragment spread graph (resolution + reachability), as a reusable\n * structure. Built from the corpus, so fragment-graph rules need no bespoke\n * context methods. */\n getFragmentGraph(): FragmentGraph {\n if (!this._fragmentGraph) {\n const definitions: FragmentGraphDefinition[] = [];\n for (const op of this._operations) {\n definitions.push({\n id: op.id,\n kind: 'operation',\n schemaName: op.schemaName,\n fragmentSpreads: op.fragmentSpreads,\n });\n }\n for (const fragment of this._fragments) {\n definitions.push({\n id: fragment.id,\n kind: 'fragment',\n schemaName: fragment.schemaName,\n name: fragment.name,\n fragmentSpreads: fragment.fragmentSpreads,\n });\n }\n this._fragmentGraph = new FragmentGraph(definitions);\n }\n return this._fragmentGraph;\n }\n\n /* -- Construction -- */\n\n private _addWarning(message: string, doc: RawScanDocument): void {\n this._warnings.push({ message, file: doc.filePath, line: doc.line, col: doc.col });\n }\n\n private _uniqueId(base: string): string {\n if (!this._recordById.has(base)) return base;\n let n = 2;\n while (this._recordById.has(`${base}#${n}`)) n++;\n return `${base}#${n}`;\n }\n\n private _register(record: DefinitionRecord): void {\n this._definitions.push(record);\n this._recordByNode.set(record.node, record);\n this._recordById.set(record.id, record);\n // Keep the AST node and discriminant internal; expose only clean identities.\n if (record.defKind === 'operation') {\n const { node: _node, defKind: _defKind, ...info } = record;\n this._operations.push(info);\n } else {\n const { node: _node, defKind: _defKind, ...info } = record;\n this._fragments.push(info);\n }\n }\n\n private _buildCorpus(documents: RawScanDocument[]): void {\n let anonCount = 0;\n for (const doc of documents) {\n if (!this._schemas.has(doc.schemaName)) {\n this._addWarning(\n `No schema was loaded for ${doc.schemaName ? `'${doc.schemaName}'` : 'the default schema'}.`,\n doc\n );\n continue;\n }\n\n let definitions: readonly DefinitionNode[];\n try {\n definitions = parse(doc.document, { noLocation: true }).definitions;\n } catch (error) {\n this._addWarning(\n `The document could not be parsed. Run \\`check\\` to see validation errors.\\n` +\n `${error instanceof Error ? error.message : error}`,\n doc\n );\n continue;\n }\n\n const loc = { file: doc.filePath, line: doc.line, col: doc.col };\n for (const definition of definitions) {\n if (definition.kind === Kind.OPERATION_DEFINITION) {\n const op = definition as OperationDefinitionNode;\n const name = op.name ? op.name.value : null;\n const id = this._uniqueId(\n `${doc.schemaName ?? ''}:operation:${name ?? `anonymous-${++anonCount}`}`\n );\n this._register({\n defKind: 'operation',\n node: op,\n id,\n name,\n kind: op.operation,\n schemaName: doc.schemaName,\n module: doc.filePath,\n loc,\n variables: (op.variableDefinitions || []).map((v) => ({\n name: v.variable.name.value,\n type: print(v.type),\n defaultValue: v.defaultValue ? print(v.defaultValue) : undefined,\n })),\n fragmentSpreads: collectFragmentSpreads(op),\n hash: hashOf(print(op)),\n });\n } else if (definition.kind === Kind.FRAGMENT_DEFINITION) {\n const fragment = definition as FragmentDefinitionNode;\n const id = this._uniqueId(`${doc.schemaName ?? ''}:fragment:${fragment.name.value}`);\n this._register({\n defKind: 'fragment',\n node: fragment,\n id,\n name: fragment.name.value,\n typeCondition: fragment.typeCondition.name.value,\n schemaName: doc.schemaName,\n module: doc.filePath,\n loc,\n fragmentSpreads: collectFragmentSpreads(fragment),\n hash: hashOf(print(fragment)),\n });\n }\n }\n }\n }\n\n private _buildModules(imports: Map<string, string[]>): ModuleInfo[] {\n const byPath = new Map<string, ModuleInfo>();\n const ensure = (modulePath: string): ModuleInfo => {\n let info = byPath.get(modulePath);\n if (!info) {\n info = {\n path: modulePath,\n relativePath: path.relative(CWD, modulePath) || modulePath,\n operations: [],\n fragments: [],\n imports: [],\n };\n byPath.set(modulePath, info);\n }\n return info;\n };\n\n for (const op of this._operations) ensure(op.module).operations.push(op.id);\n for (const fragment of this._fragments) ensure(fragment.module).fragments.push(fragment.id);\n\n for (const info of byPath.values()) {\n const resolved = imports.get(info.path);\n if (resolved) {\n for (const target of resolved) {\n if (target !== info.path && byPath.has(target)) info.imports.push(target);\n }\n }\n }\n\n return [...byPath.values()].sort((a, b) => a.relativePath.localeCompare(b.relativePath));\n }\n}\n","import type { ScanRule, RuleDatapoint } from '../types';\n\nexport interface FieldUsageData {\n typeName: string;\n fieldName: string;\n fieldType: string;\n deprecated: boolean;\n deprecationReason?: string | undefined;\n count: number;\n directUsages: { defId: string; module: string }[];\n /** Operation ids that reach this field directly or transitively. */\n operations: string[];\n /** Blast radius: how much of the codebase transitively depends on this field. */\n reach: { modules: number; areas: string[]; entryPoints: number };\n}\n\ninterface Accumulated {\n typeName: string;\n fieldName: string;\n fieldType: string;\n deprecationReason?: string;\n directUsages: { defId: string; module: string }[];\n}\n\n/** Indexes every field that is actually selected: which operations/fragments\n * select each schema coordinate, the operations that reach it, and its blast\n * radius. Fields the schema declares but no document selects are absent (derive\n * them from the schema if needed; the overview carries aggregate coverage). */\nexport const fieldUsage: ScanRule<FieldUsageData> = {\n name: 'field-usage',\n description: 'Used fields, keyed by schema coordinate, with their reach.',\n create(context) {\n const byCoordinate = new Map<string, Accumulated>();\n let seen = new Set<string>();\n const resetSeen = () => void (seen = new Set());\n\n return {\n visitor: {\n OperationDefinition: { enter: resetSeen },\n FragmentDefinition: { enter: resetSeen },\n Field: {\n enter() {\n const parentType = context.getParentType();\n const fieldDef = context.getFieldDef();\n const definition = context.getCurrentDefinition();\n if (!parentType || !fieldDef || !definition) return;\n // Skip reserved introspection meta-fields (__typename, __schema, __type).\n if (fieldDef.name.startsWith('__')) return;\n\n const coordinate = `${parentType.name}.${fieldDef.name}`;\n if (seen.has(coordinate)) return;\n seen.add(coordinate);\n\n let entry = byCoordinate.get(coordinate);\n if (!entry) {\n entry = {\n typeName: parentType.name,\n fieldName: fieldDef.name,\n fieldType: String(fieldDef.type),\n deprecationReason: fieldDef.deprecationReason ?? undefined,\n directUsages: [],\n };\n byCoordinate.set(coordinate, entry);\n }\n entry.directUsages.push({ defId: definition.id, module: definition.module });\n },\n },\n },\n\n collect() {\n const operationIds = new Set(context.operations.map((op) => op.id));\n const moduleById = new Map(context.operations.map((op) => [op.id, op.module] as const));\n const graph = context.getModuleGraph();\n const fragments = context.getFragmentGraph();\n const hasEntryPoints = graph.entryPoints().size > 0;\n\n const datapoints: RuleDatapoint<FieldUsageData>[] = [];\n for (const [coordinate, entry] of byCoordinate) {\n const operations = new Set<string>();\n for (const usage of entry.directUsages) {\n if (operationIds.has(usage.defId)) operations.add(usage.defId);\n else for (const id of fragments.operationsReaching(usage.defId)) operations.add(id);\n }\n\n // Blast radius: every module that selects the field, plus the modules\n // of the operations that reach it, expanded by who depends on them.\n const sourceModules = new Set<string>(entry.directUsages.map((u) => u.module));\n for (const id of operations) {\n const module = moduleById.get(id);\n if (module) sourceModules.add(module);\n }\n const reachModules = new Set<string>();\n const reachAreas = new Set<string>();\n const reachEntries = new Set<string>();\n for (const module of sourceModules) {\n const reach = graph.reach(module);\n for (const m of reach.modules) reachModules.add(m);\n for (const a of reach.areas) reachAreas.add(a);\n for (const e of reach.entryPoints) reachEntries.add(e);\n }\n\n datapoints.push({\n ref: { kind: 'field', coordinate },\n message: `${coordinate} selected ${entry.directUsages.length} time(s)`,\n weight: hasEntryPoints ? reachEntries.size : reachModules.size,\n data: {\n typeName: entry.typeName,\n fieldName: entry.fieldName,\n fieldType: entry.fieldType,\n deprecated: entry.deprecationReason != null,\n deprecationReason: entry.deprecationReason,\n count: entry.directUsages.length,\n directUsages: entry.directUsages,\n operations: [...operations],\n reach: {\n modules: reachModules.size,\n areas: [...reachAreas].sort(),\n entryPoints: reachEntries.size,\n },\n },\n });\n }\n\n // Rank by selection count, then reach, then coordinate for stable ties —\n // so the terminal's top-N shows the most-used fields first.\n const coordinateOf = (d: FieldUsageData) => `${d.typeName}.${d.fieldName}`;\n return datapoints.sort(\n (a, b) =>\n b.data.count - a.data.count ||\n (b.weight ?? 0) - (a.weight ?? 0) ||\n coordinateOf(a.data).localeCompare(coordinateOf(b.data))\n );\n },\n };\n },\n};\n","import type { ScanRule } from '../types';\n\nimport { fieldUsage } from './field-usage';\nimport { inputUsage } from './input-usage';\nimport { deprecatedUsage } from './deprecated-usage';\nimport { orphanFragments } from './orphan-fragments';\nimport { crossFeatureFragments } from './cross-feature-fragments';\nimport { operationComplexity } from './operation-complexity';\nimport { fetchDepth } from './fetch-depth';\nimport { directiveUsage } from './directive-usage';\n\nexport type { FieldUsageData } from './field-usage';\n\n/** The rules run out of the box. Each is a `(context) => { visitor, collect }`\n * factory that owns its state — adding an insight means writing one rule file\n * and registering it here. */\nexport const DEFAULT_RULES: ScanRule[] = [\n // The per-field usage index (reverse lookup + blast radius).\n fieldUsage,\n // Input-side usage: enum values and input-object fields.\n inputUsage,\n // Schema evolution & safety\n deprecatedUsage,\n // Code navigation & refactoring\n orphanFragments,\n crossFeatureFragments,\n // Performance & DX\n operationComplexity,\n // Code-structure (dependency graph)\n fetchDepth,\n // Conventions\n directiveUsage,\n];\n","import { getNamedType } from 'graphql';\n\nimport type { ScanRule, RuleDatapoint } from '../types';\n\nexport interface InputUsageData {\n kind: 'enum-value' | 'input-field';\n count: number;\n}\n\n/** Usage counts for the input side of the schema: which enum values are passed\n * and which input-object fields are set, keyed by coordinate (`Enum.VALUE` /\n * `Input.field`). Answers \"which enum values / input fields do we actually\n * use\", which neither field usage nor coverage captures. */\nexport const inputUsage: ScanRule<InputUsageData> = {\n name: 'input-usage',\n description: 'Usage counts for enum values and input-object fields.',\n create(context) {\n const counts = new Map<string, { kind: InputUsageData['kind']; count: number }>();\n const bump = (coordinate: string, kind: InputUsageData['kind']) => {\n const entry = counts.get(coordinate);\n if (entry) entry.count++;\n else counts.set(coordinate, { kind, count: 1 });\n };\n\n return {\n visitor: {\n EnumValue: {\n enter(node) {\n const inputType = context.getInputType();\n if (inputType) bump(`${getNamedType(inputType).name}.${node.value}`, 'enum-value');\n },\n },\n ObjectField: {\n enter(node) {\n const parentInput = context.getParentInputType();\n if (parentInput)\n bump(`${getNamedType(parentInput).name}.${node.name.value}`, 'input-field');\n },\n },\n },\n\n collect() {\n const datapoints: RuleDatapoint<InputUsageData>[] = [...counts.entries()]\n .sort((a, b) => b[1].count - a[1].count || a[0].localeCompare(b[0]))\n .map(([coordinate, { kind, count }]) => ({\n ref: { kind: 'field', coordinate },\n message: `${coordinate} (${kind}) used ${count} time(s)`,\n weight: count,\n data: { kind, count },\n }));\n return datapoints;\n },\n };\n },\n};\n","import type { ScanRule } from '../types';\n\nexport interface DeprecatedUsageData {\n reason?: string | undefined;\n count: number;\n operations: string[];\n}\n\ninterface Accumulated {\n reason?: string | undefined;\n defIds: Set<string>;\n}\n\n/** Deprecated schema fields that are still selected, ranked by how many\n * operations reach them — the migration's remaining blast radius. */\nexport const deprecatedUsage: ScanRule<DeprecatedUsageData> = {\n name: 'deprecated-usage',\n description: 'Deprecated schema fields that are still in use.',\n create(context) {\n const byCoordinate = new Map<string, Accumulated>();\n\n return {\n visitor: {\n Field: {\n enter() {\n const parentType = context.getParentType();\n const fieldDef = context.getFieldDef();\n const definition = context.getCurrentDefinition();\n if (!parentType || !fieldDef || !definition) return;\n if (fieldDef.deprecationReason == null) return;\n\n const coordinate = `${parentType.name}.${fieldDef.name}`;\n let entry = byCoordinate.get(coordinate);\n if (!entry) {\n byCoordinate.set(\n coordinate,\n (entry = { reason: fieldDef.deprecationReason ?? undefined, defIds: new Set() })\n );\n }\n entry.defIds.add(definition.id);\n },\n },\n },\n\n collect() {\n const operationIds = new Set(context.operations.map((op) => op.id));\n const fragments = context.getFragmentGraph();\n return [...byCoordinate.entries()]\n .map(([coordinate, entry]) => {\n const operations = new Set<string>();\n for (const defId of entry.defIds) {\n if (operationIds.has(defId)) operations.add(defId);\n else for (const id of fragments.operationsReaching(defId)) operations.add(id);\n }\n return { coordinate, reason: entry.reason, operations: [...operations] };\n })\n .sort((a, b) => b.operations.length - a.operations.length)\n .map(({ coordinate, reason, operations }) => ({\n ref: { kind: 'field', coordinate },\n message: `${coordinate} is deprecated but used by ${operations.length} operation(s)`,\n weight: operations.length,\n data: { reason, count: operations.length, operations },\n }));\n },\n };\n },\n};\n","import type { ScanRule } from '../types';\n\nexport interface OrphanFragmentData {\n typeCondition: string;\n module: string;\n}\n\n/** Fragments that are defined but never spread by any operation or fragment. */\nexport const orphanFragments: ScanRule<OrphanFragmentData> = {\n name: 'orphan-fragments',\n description: 'Fragments that are defined but never used.',\n create(context) {\n const spreadIds = new Set<string>();\n const fragments = context.getFragmentGraph();\n\n return {\n visitor: {\n FragmentSpread: {\n enter(node) {\n const definition = context.getCurrentDefinition();\n if (!definition) return;\n const id = fragments.resolve(definition.schemaName, node.name.value);\n if (id) spreadIds.add(id);\n },\n },\n },\n\n collect() {\n return context.fragments\n .filter((fragment) => !spreadIds.has(fragment.id))\n .map((fragment) => ({\n ref: { kind: 'fragment', id: fragment.id },\n message: `Fragment '${fragment.name}' is never spread`,\n data: { typeCondition: fragment.typeCondition, module: fragment.module },\n }));\n },\n };\n },\n};\n","import type { ScanRule, RuleDatapoint } from '../types';\n\nexport interface CrossFeatureData {\n definingArea: string;\n consumerAreas: string[];\n spreadCount: number;\n}\n\n/** Fragments consumed across area boundaries — a quantified signal of coupling\n * between features. The weight is the number of distinct consuming areas. */\nexport const crossFeatureFragments: ScanRule<CrossFeatureData> = {\n name: 'cross-feature-fragments',\n description: 'Fragments spread across multiple areas of the codebase.',\n create(context) {\n // fragment id -> areas of the definitions that spread it\n const consumerAreas = new Map<string, Set<string>>();\n const spreadCount = new Map<string, number>();\n\n const graph = context.getModuleGraph();\n const fragments = context.getFragmentGraph();\n\n return {\n visitor: {\n FragmentSpread: {\n enter(node) {\n const definition = context.getCurrentDefinition();\n if (!definition) return;\n const id = fragments.resolve(definition.schemaName, node.name.value);\n if (!id) return;\n let areas = consumerAreas.get(id);\n if (!areas) consumerAreas.set(id, (areas = new Set()));\n areas.add(graph.areaOf(definition.module));\n spreadCount.set(id, (spreadCount.get(id) || 0) + 1);\n },\n },\n },\n\n collect() {\n const byId = new Map(context.fragments.map((fragment) => [fragment.id, fragment]));\n const datapoints: RuleDatapoint<CrossFeatureData>[] = [];\n for (const [id, areas] of consumerAreas) {\n const fragment = byId.get(id);\n if (!fragment) continue;\n const definingArea = graph.areaOf(fragment.module);\n // Areas other than where the fragment itself lives.\n const externalAreas = [...areas].filter((area) => area !== definingArea).sort();\n if (!externalAreas.length) continue;\n\n datapoints.push({\n ref: { kind: 'fragment' as const, id },\n message: `Fragment '${fragment.name}' (${definingArea}) is consumed by ${externalAreas.length} other area(s)`,\n weight: externalAreas.length,\n data: {\n definingArea,\n consumerAreas: [...areas].sort(),\n spreadCount: spreadCount.get(id) || 0,\n },\n });\n }\n return datapoints.sort((a, b) => (b.weight || 0) - (a.weight || 0));\n },\n };\n },\n};\n","import { isListType, getNullableType } from 'graphql';\n\nimport type { ScanRule, RuleDatapoint } from '../types';\n\n/** Extra weight per list field — list selections drive response size / N+1 risk. */\nconst LIST_WEIGHT = 3;\n\nexport interface ComplexityData {\n /** Selection depth, expanded through fragment spreads. */\n depth: number;\n /** Number of distinct fields selected, expanded through fragment spreads. */\n fieldCount: number;\n /** How many of those distinct fields return a list. */\n listFields: number;\n /** The distinct schema coordinates selected (the operation's footprint). */\n fields: string[];\n /** Combined cost score. */\n score: number;\n}\n\n/** Per-definition metrics gathered during traversal (own selections only). */\ninterface DefMetrics {\n schemaName: string | null;\n ownDepth: number;\n /** Distinct coordinates selected directly in this definition. */\n fields: Set<string>;\n /** Subset of {@link fields} whose field returns a list. */\n listFields: Set<string>;\n /** Fragment spreads with the selection-set depth they occur at. */\n spreads: { name: string; depth: number }[];\n}\n\n/** Operations ranked by cost, expanded through fragment spreads (an operation\n * that delegates to a big fragment is correctly counted as large). Reports the\n * operation's full field footprint, its transitive depth, and how many of its\n * fields return lists (weighted more heavily as a proxy for response size /\n * N+1 risk). */\nexport const operationComplexity: ScanRule<ComplexityData> = {\n name: 'operation-complexity',\n description: 'Operations ranked by transitive footprint, depth, and list fan-out.',\n create(context) {\n const byDef = new Map<string, DefMetrics>();\n let current: DefMetrics | null = null;\n let depth = 0;\n\n const startDefinition = () => {\n const definition = context.getCurrentDefinition();\n if (!definition) {\n current = null;\n return;\n }\n current = {\n schemaName: definition.schemaName,\n ownDepth: 0,\n fields: new Set(),\n listFields: new Set(),\n spreads: [],\n };\n byDef.set(definition.id, current);\n depth = 0;\n };\n\n return {\n visitor: {\n OperationDefinition: { enter: startDefinition, leave: () => void (current = null) },\n FragmentDefinition: { enter: startDefinition, leave: () => void (current = null) },\n SelectionSet: {\n enter() {\n if (current && ++depth > current.ownDepth) current.ownDepth = depth;\n },\n leave() {\n if (current) depth--;\n },\n },\n Field: {\n enter() {\n const parentType = context.getParentType();\n const fieldDef = context.getFieldDef();\n if (!current || !parentType || !fieldDef || fieldDef.name.startsWith('__')) return;\n const coordinate = `${parentType.name}.${fieldDef.name}`;\n current.fields.add(coordinate);\n if (isListType(getNullableType(fieldDef.type))) current.listFields.add(coordinate);\n },\n },\n FragmentSpread: {\n enter(node) {\n if (current) current.spreads.push({ name: node.name.value, depth });\n },\n },\n },\n\n collect() {\n const fragments = context.getFragmentGraph();\n\n // Transitive selection depth, expanding spreads (memoised, cycle-guarded).\n const depthMemo = new Map<string, number>();\n const effectiveDepth = (defId: string, visiting: Set<string>): number => {\n const cached = depthMemo.get(defId);\n if (cached != null) return cached;\n const metrics = byDef.get(defId);\n if (!metrics) return 0;\n let result = metrics.ownDepth;\n for (const spread of metrics.spreads) {\n const fragmentId = fragments.resolve(metrics.schemaName, spread.name);\n if (!fragmentId || visiting.has(fragmentId)) continue;\n visiting.add(fragmentId);\n result = Math.max(result, spread.depth - 1 + effectiveDepth(fragmentId, visiting));\n visiting.delete(fragmentId);\n }\n depthMemo.set(defId, result);\n return result;\n };\n\n const datapoints: RuleDatapoint<ComplexityData>[] = context.operations.map((op) => {\n const fields = new Set<string>(byDef.get(op.id)?.fields);\n const listFields = new Set<string>(byDef.get(op.id)?.listFields);\n for (const fragmentId of fragments.reachableFragments(op.id)) {\n const metrics = byDef.get(fragmentId);\n if (!metrics) continue;\n for (const coordinate of metrics.fields) fields.add(coordinate);\n for (const coordinate of metrics.listFields) listFields.add(coordinate);\n }\n const operationDepth = effectiveDepth(op.id, new Set());\n const score =\n fields.size + operationDepth * operationDepth + listFields.size * LIST_WEIGHT;\n\n return {\n ref: { kind: 'operation', id: op.id },\n message: `${op.name || '(anonymous)'}: depth ${operationDepth}, ${fields.size} fields (${listFields.size} list)`,\n weight: score,\n data: {\n depth: operationDepth,\n fieldCount: fields.size,\n listFields: listFields.size,\n fields: [...fields].sort(),\n score,\n },\n };\n });\n\n return datapoints.sort((a, b) => b.data.score - a.data.score);\n },\n };\n },\n};\n","import type { ScanRule } from '../types';\n\nexport interface FetchDepthData {\n /** Shortest import-distance from an entry point to the defining module. */\n depth: number | null;\n area: string;\n module: string;\n}\n\n/** Where each query sits in the module graph: how far its defining module is\n * from an entry point. As a distribution this describes data-fetching placement\n * (hoisted to route boundaries vs. scattered deep in the tree, i.e. waterfalls).\n *\n * Restricted to queries: mutations and subscriptions are naturally triggered\n * deep in the tree (event handlers, forms), so their depth carries no signal. */\nexport const fetchDepth: ScanRule<FetchDepthData> = {\n name: 'fetch-depth',\n description: 'Distance from an entry point to where each query is defined.',\n create(context) {\n // Reads the static module graph in collect(); no traversal state needed.\n return {\n visitor: {},\n collect() {\n const graph = context.getModuleGraph();\n return context.operations\n .filter((op) => op.kind === 'query')\n .map((op) => {\n const depth = graph.distanceFromEntry(op.module);\n return { op, depth: depth ?? null };\n })\n .sort((a, b) => (b.depth ?? -1) - (a.depth ?? -1))\n .map(({ op, depth }) => ({\n ref: { kind: 'operation' as const, id: op.id },\n message: `${op.name || '(anonymous)'} is ${\n depth == null\n ? 'unreachable from any entry point'\n : `${depth} hop(s) from an entry point`\n }`,\n weight: depth ?? undefined,\n data: { depth, area: graph.areaOf(op.module), module: op.module },\n }));\n },\n };\n },\n};\n","import type { ScanRule } from '../types';\n\nexport interface DirectiveUsageData {\n count: number;\n}\n\n/** How often each directive is applied across all documents (e.g. `@skip`,\n * `@include`, `@defer`, `@_unmask`, custom client directives). Useful for\n * gauging adoption of directive-based features. */\nexport const directiveUsage: ScanRule<DirectiveUsageData> = {\n name: 'directive-usage',\n description: 'Application count per directive across documents.',\n create() {\n const counts = new Map<string, number>();\n return {\n visitor: {\n Directive: {\n enter(node) {\n counts.set(node.name.value, (counts.get(node.name.value) || 0) + 1);\n },\n },\n },\n collect() {\n return [...counts.entries()]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([name, count]) => ({\n ref: { kind: 'directive', name },\n message: `@${name} applied ${count} time(s)`,\n weight: count,\n data: { count },\n }));\n },\n };\n },\n};\n","import type { ScanContext } from '../context';\nimport type { RuleResults } from '../types';\nimport { allSchemaFields } from '../schema-util';\n\nexport interface ScanOverview {\n operations: number;\n fragments: number;\n modules: number;\n operationsByKind: { query: number; mutation: number; subscription: number };\n coverage: { usedFields: number; totalFields: number; percent: number };\n}\n\n/** Project-level totals, derived from the corpus, the schema, and the\n * field-usage rule. Shared so the JSON `overview` and the terminal header show\n * the same numbers. */\nexport function buildOverview(context: ScanContext, rules: RuleResults): ScanOverview {\n const operationsByKind = { query: 0, mutation: 0, subscription: 0 };\n for (const op of context.operations) operationsByKind[op.kind]++;\n\n // field-usage emits one datapoint per used schema field.\n const usedFields = (rules['field-usage'] || []).length;\n const totalFields = allSchemaFields(context.getSchemas()).length;\n const percent = totalFields ? Math.round((usedFields / totalFields) * 100) : 100;\n\n return {\n operations: context.operations.length,\n fragments: context.fragments.length,\n modules: context.modules.length,\n operationsByKind,\n coverage: { usedFields, totalFields, percent },\n };\n}\n","import { isObjectType, isInterfaceType } from 'graphql';\nimport type { GraphQLSchema } from 'graphql';\n\nimport type { SchemaName } from './types';\n\nexport interface SchemaFieldInfo {\n coordinate: string;\n typeName: string;\n fieldName: string;\n fieldType: string;\n deprecationReason?: string | undefined;\n}\n\n/** Enumerates every object/interface field across the schemas, deduped by\n * coordinate. A pure helper rules use to reconcile usage against the schema. */\nexport function allSchemaFields(schemas: Map<SchemaName, GraphQLSchema>): SchemaFieldInfo[] {\n const seen = new Map<string, SchemaFieldInfo>();\n for (const schema of schemas.values()) {\n for (const type of Object.values(schema.getTypeMap())) {\n if (type.name.startsWith('__')) continue;\n if (!isObjectType(type) && !isInterfaceType(type)) continue;\n for (const field of Object.values(type.getFields())) {\n const coordinate = `${type.name}.${field.name}`;\n if (!seen.has(coordinate)) {\n seen.set(coordinate, {\n coordinate,\n typeName: type.name,\n fieldName: field.name,\n fieldType: String(field.type),\n deprecationReason: field.deprecationReason ?? undefined,\n });\n }\n }\n }\n }\n return [...seen.values()];\n}\n","import type { ScanContext } from '../context';\nimport type { RuleResults, OperationInfo, FragmentInfo } from '../types';\nimport { buildOverview, type ScanOverview } from './overview';\n\nexport interface ScanJsonOutput {\n version: number;\n /** Project-level totals (same numbers the terminal header shows). */\n overview: ScanOverview;\n /** Discovered operations, with identity (kind, module, loc, variables, hash). */\n operations: OperationInfo[];\n /** Discovered fragments, with identity (type condition, module, loc, hash). */\n fragments: FragmentInfo[];\n /** Each rule's datapoints, keyed by rule name. */\n rules: RuleResults;\n}\n\n/** Serialises the analysis result — overview, operation/fragment identities, and\n * the rule datapoints the terminal report renders — to the stable JSON\n * substrate. The relationship graph is emitted separately via `--graph`. */\nexport function renderJson(context: ScanContext, rules: RuleResults): string {\n const output: ScanJsonOutput = {\n version: 1,\n overview: buildOverview(context, rules),\n operations: [...context.operations],\n fragments: [...context.fragments],\n rules,\n };\n return JSON.stringify(output, null, 2) + '\\n';\n}\n","import * as path from 'node:path';\n\nimport type { ScanContext } from '../context';\nimport type { RuleResults, ScanGraph, ScanGraphNode, ScanGraphEdge, SchemaName } from '../types';\nimport type { FieldUsageData } from '../rules';\n\nconst CWD = process.cwd();\nconst relative = (modulePath: string): string => path.relative(CWD, modulePath) || modulePath;\n\nconst moduleNodeId = (modulePath: string): string => `module:${modulePath}`;\nconst fieldNodeId = (coordinate: string): string => `field:${coordinate}`;\nconst typeNodeId = (typeName: string): string => `type:${typeName}`;\nconst fragmentKey = (schemaName: SchemaName, name: string): string =>\n `${schemaName ?? ''}\\0${name}`;\n\n/** Serialises the pure relationship graph (emitted via `--graph`). */\nexport function renderGraph(context: ScanContext, rules: RuleResults): string {\n return JSON.stringify(buildGraph(context, rules), null, 2) + '\\n';\n}\n\n/** Composes the module ↔ document ↔ fragment ↔ schema relationship graph from\n * the corpus (identities, spreads, imports) and the field-usage rule (the\n * field selections). A derived view assembled at output time. */\nexport function buildGraph(context: ScanContext, rules: RuleResults): ScanGraph {\n const nodes = new Map<string, ScanGraphNode>();\n const edges: ScanGraphEdge[] = [];\n const addNode = (node: ScanGraphNode): void => {\n if (!nodes.has(node.id)) nodes.set(node.id, node);\n };\n\n const fragmentIdByName = new Map<string, string>();\n for (const fragment of context.fragments) {\n fragmentIdByName.set(fragmentKey(fragment.schemaName, fragment.name), fragment.id);\n }\n\n const moduleNode = (modulePath: string): void => {\n addNode({ id: moduleNodeId(modulePath), kind: 'module', label: relative(modulePath) });\n };\n\n // The full project import graph (not just GraphQL-bearing modules), so the\n // emitted `imports` edges match what reachability/fetch-depth actually use.\n for (const [from, tos] of context.getModuleGraph().importMap()) {\n moduleNode(from);\n for (const target of tos) {\n moduleNode(target);\n edges.push({ from: moduleNodeId(from), to: moduleNodeId(target), kind: 'imports' });\n }\n }\n\n // Schema field/type nodes + `selects` edges come from the field-usage rule\n // (which only indexes used fields, so the graph is bounded to what's used).\n for (const datapoint of rules['field-usage'] || []) {\n if (datapoint.ref.kind !== 'field') continue;\n const coordinate = datapoint.ref.coordinate;\n const usage = datapoint.data as FieldUsageData;\n addNode({ id: fieldNodeId(coordinate), kind: 'schemaField', label: coordinate });\n addNode({ id: typeNodeId(usage.typeName), kind: 'schemaType', label: usage.typeName });\n edges.push({ from: fieldNodeId(coordinate), to: typeNodeId(usage.typeName), kind: 'onType' });\n for (const site of usage.directUsages) {\n edges.push({ from: site.defId, to: fieldNodeId(coordinate), kind: 'selects' });\n }\n }\n\n const addDefinition = (\n id: string,\n kind: 'operation' | 'fragment',\n label: string,\n module: string,\n spreads: readonly string[],\n schemaName: SchemaName\n ): void => {\n addNode({ id, kind, label });\n moduleNode(module); // ensure the defining module is a node even if it has no imports\n edges.push({ from: moduleNodeId(module), to: id, kind: 'defines' });\n for (const spreadName of spreads) {\n const target = fragmentIdByName.get(fragmentKey(schemaName, spreadName));\n if (target) edges.push({ from: id, to: target, kind: 'spreads' });\n }\n };\n\n for (const op of context.operations) {\n addDefinition(\n op.id,\n 'operation',\n op.name || '(anonymous)',\n op.module,\n op.fragmentSpreads,\n op.schemaName\n );\n }\n for (const fragment of context.fragments) {\n addDefinition(\n fragment.id,\n 'fragment',\n fragment.name,\n fragment.module,\n fragment.fragmentSpreads,\n fragment.schemaName\n );\n }\n\n return { nodes: [...nodes.values()], edges };\n}\n","import * as path from 'node:path';\nimport * as t from '../../../term';\n\nimport type { ScanContext } from '../context';\nimport type { RuleResults, DatapointRef } from '../types';\nimport { DEFAULT_RULES } from '../rules';\nimport { buildOverview } from './overview';\n\nconst CWD = process.cwd();\n/** Maximum datapoints shown per rule in the terminal report. */\nconst MAX_PER_RULE = 8;\n/** Below this many columns left for the message, the locator is dropped first. */\nconst MIN_MESSAGE_WIDTH = 24;\n\nconst RULE_DESCRIPTIONS = new Map(DEFAULT_RULES.map((rule) => [rule.name, rule.description]));\n\nconst truncate = (text: string, max: number): string =>\n text.length <= max\n ? text\n : max > 1\n ? text.slice(0, max - 1) + t.Chars.Ellipsis\n : t.Chars.Ellipsis;\n\nconst relative = (filePath: string): string => {\n const rel = path.relative(CWD, filePath);\n return !rel.startsWith('..') ? rel : filePath;\n};\n\n/** Resolves a datapoint's `ref` to a short `file:line` locator, where one exists. */\nfunction locator(ref: DatapointRef, context: ScanContext): string | undefined {\n switch (ref.kind) {\n case 'operation': {\n const op = context.operations.find((item) => item.id === ref.id);\n return op ? `${relative(op.loc.file)}:${op.loc.line}` : undefined;\n }\n case 'fragment': {\n const fragment = context.fragments.find((item) => item.id === ref.id);\n return fragment ? `${relative(fragment.loc.file)}:${fragment.loc.line}` : undefined;\n }\n default:\n return undefined;\n }\n}\n\nfunction coverageLine(context: ScanContext, rules: RuleResults): string {\n const { usedFields, totalFields, percent } = buildOverview(context, rules).coverage;\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Foreground),\n 'Schema coverage: ',\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${percent}% `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `(${usedFields}/${totalFields} fields used)\\n`,\n ]);\n}\n\n/** Renders the default human-facing report: coverage plus the top datapoints of\n * each rule that produced findings. `width` (terminal columns) bounds each item\n * line so it doesn't wrap; omit it for unbounded output. */\nexport function renderTerminalReport(\n context: ScanContext,\n rules: RuleResults,\n width?: number\n): string {\n let out = '\\n' + coverageLine(context, rules);\n\n for (const [name, datapoints] of Object.entries(rules)) {\n if (!datapoints.length) continue;\n\n out += t.text([\n '\\n',\n t.cmd(t.CSI.Style, t.Style.Magenta),\n `${t.SmallTriangle.Right} `,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n name,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n ` (${datapoints.length})\\n`,\n ]);\n\n const description = RULE_DESCRIPTIONS.get(name);\n if (description) {\n const text = width ? truncate(description, Math.max(width - 2, 1)) : description;\n out += t.text([t.cmd(t.CSI.Style, t.Style.BrightBlack), ` ${text}\\n`]);\n }\n\n const shown = datapoints.slice(0, MAX_PER_RULE);\n const truncated = datapoints.length > shown.length;\n // \" \" + connector + \" \"\n const prefixWidth = 4;\n shown.forEach((datapoint, index) => {\n const isLast = !truncated && index === shown.length - 1;\n const weightText = datapoint.weight != null ? `~${datapoint.weight}` : '';\n let message = datapoint.message;\n let locText = locator(datapoint.ref, context);\n\n if (width) {\n const weightWidth = weightText ? weightText.length + 2 : 0;\n let locWidth = locText ? locText.length + 2 : 0;\n let budget = width - prefixWidth - weightWidth - locWidth;\n // Too cramped for the message — drop the (long) locator before the message.\n if (locText && budget < MIN_MESSAGE_WIDTH) {\n budget += locWidth;\n locText = undefined;\n locWidth = 0;\n }\n message = truncate(message, Math.max(budget, 1));\n }\n\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n ` ${isLast ? t.Box.BottomLeft : t.Box.VerticalRight} `,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n message,\n ...(weightText ? [t.cmd(t.CSI.Style, t.Style.BrightBlue), ` ${weightText}`] : []),\n ...(locText ? [t.cmd(t.CSI.Style, t.Style.BrightBlack), ` ${locText}`] : []),\n '\\n',\n ]);\n });\n\n if (truncated) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n ` ${t.Box.BottomLeft} ${t.Chars.Ellipsis} and ${datapoints.length - shown.length} more\\n`,\n ]);\n }\n }\n\n return out;\n}\n","import { pipe, interval, map, concat, fromValue } from 'wonka';\n\nimport * as path from 'node:path';\nimport * as t from '../../term';\n\nimport type { ScanWarning } from './types';\nimport { indent } from '../shared/logger';\n\nexport * from '../shared/logger';\n\nconst CWD = process.cwd();\nconst INDENT = ' ';\n\nexport function warningFile(filePath: string) {\n const relativePath = path.relative(CWD, filePath);\n if (!relativePath.startsWith('..')) filePath = relativePath;\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Underline),\n filePath,\n t.cmd(t.CSI.Style, t.Style.NoUnderline),\n '\\n',\n ]);\n}\n\nexport function warningMessage(message: ScanWarning) {\n return t.text([\n INDENT,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${message.line}:${message.col}`,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n indent(message.message.trim(), t.text([INDENT, t.Chars.Tab])),\n t.Chars.Newline,\n ]);\n}\n\nexport function warningGithub(message: ScanWarning): void {\n t.githubAnnotation('warning', message.message, {\n file: message.file,\n line: message.line,\n col: message.col,\n });\n}\n\nexport function runningScan(file?: number, ofFiles?: number) {\n const progress = file ? (ofFiles ? `(${file}/${ofFiles})` : `(${file})`) : '';\n const frame = (state: number) =>\n t.text([\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.dotSpinner[state % t.dotSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n `Scanning files${t.Chars.Ellipsis} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n progress,\n ]);\n return concat([\n fromValue(frame(0)),\n pipe(\n interval(150),\n map((state) => frame(state + 1))\n ),\n ]);\n}\n\nexport function summary(args: {\n warnings: number;\n operations: number;\n fragments: number;\n modules: number;\n}) {\n let out = '\\n';\n if (args.warnings) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ` ${args.warnings} warnings\\n`,\n ]);\n }\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Scan completed `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `(${args.operations} operations, ${args.fragments} fragments across ${args.modules} modules)\\n`,\n ]);\n return out;\n}\n\nexport function warningSummary(warningCount: number) {\n return t.error([t.cmd(t.CSI.Style, t.Style.Red), `${t.Icons.Cross} ${warningCount} warnings\\n`]);\n}\n\nexport function wroteOutput(label: string, filePath: string) {\n const relativePath = path.relative(CWD, filePath);\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `Wrote ${label} to `,\n t.cmd(t.CSI.Style, t.Style.Blue),\n `${!relativePath.startsWith('..') ? relativePath : filePath}\\n`,\n ]);\n}\n","import * as path from 'node:path';\nimport type { GraphQLSchema } from 'graphql';\nimport { loadRef } from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, writeOutput } from '../shared';\n\nimport type { SchemaName, RawScanDocument, ScanWarning } from './types';\nimport { analyze } from './analyze';\nimport { renderJson } from './output/json';\nimport { renderGraph } from './output/graph';\nimport { renderTerminalReport } from './output/terminal';\nimport * as logger from './logger';\n\nexport type ScanFormat = 'json';\n\nexport interface ScanOptions {\n /** The `tsconfig.json` to use for configurations and the TypeScript program. */\n tsconfig: string | undefined;\n /** When `json`, write the JSON report; otherwise show the terminal report. */\n format: ScanFormat | undefined;\n /** When set, output the pure relationship graph (implies machine output). */\n graph: boolean;\n /** Where to write machine output to. Defaults to standard output. */\n output: string | undefined;\n /** Whether to fail with a non-zero exit code if any warnings are reported. */\n failOnWarn: boolean;\n}\n\nasync function loadSchemas(project: ProjectContext): Promise<Map<SchemaName, GraphQLSchema>> {\n const ref = await loadRef(project.pluginConfig).load({ rootPath: project.projectPath });\n const schemas = new Map<SchemaName, GraphQLSchema>();\n if (ref.current) schemas.set(null, ref.current.schema);\n for (const name in ref.multi) {\n const result = ref.multi[name];\n if (result) schemas.set(name, result.schema);\n }\n return schemas;\n}\n\nexport async function* run(tty: TTY, opts: ScanOptions): AsyncIterable<ComposeInput> {\n if (opts.format && opts.format !== 'json') {\n throw logger.errorMessage(\n `Unknown ${logger.code('--format')} '${opts.format}'.\\n` +\n logger.hint(`The only supported format is ${logger.code('json')}.`)\n );\n }\n\n let projects: ProjectContext[];\n try {\n projects = await loadProjects(opts.tsconfig);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n // Machine output goes to a single destination, so it can't span projects.\n if (projects.length > 1 && (opts.format || opts.graph)) {\n throw logger.errorMessage(\n 'Machine output can only target a single project.\\n' +\n logger.hint(`Run scan per-project with an explicit ${logger.code('--tsconfig')}.`)\n );\n }\n\n let totalWarnings = 0;\n for (const project of projects) {\n if (projects.length > 1) yield logger.projectHeader(project.label);\n totalWarnings += yield* runProject(tty, opts, project);\n }\n\n if (opts.failOnWarn && totalWarnings) {\n throw logger.warningSummary(totalWarnings);\n }\n}\n\nasync function* runProject(\n tty: TTY,\n opts: ScanOptions,\n project: ProjectContext\n): AsyncGenerator<ComposeInput, number> {\n const { runScan } = await import('./thread');\n\n // `--graph` implies machine output (the pure relationship graph).\n const machine = !!opts.format || opts.graph;\n // When machine output shares the (single) stdout stream, human chatter would\n // corrupt it — so suppress progress/warnings/summary in that case.\n const quiet = machine && !opts.output && !tty.pipeTo;\n\n let schemas: Map<SchemaName, GraphQLSchema>;\n try {\n schemas = await loadSchemas(project);\n } catch (error) {\n throw logger.externalError('Failed to load schema.', error);\n }\n\n const generator = runScan({\n rootPath: project.configResult.rootPath,\n tsconfigPath: project.configResult.tsconfigPath,\n configPath: project.configResult.configPath,\n pluginConfig: project.pluginConfig,\n });\n\n const documents: RawScanDocument[] = [];\n const imports = new Map<string, string[]>();\n const warnings: ScanWarning[] = [];\n let totalFileCount = 0;\n let fileCount = 0;\n\n try {\n if (tty.isInteractive && !quiet) yield logger.runningScan();\n\n for await (const signal of generator) {\n if (signal.kind === 'EXTERNAL_WARNING') {\n if (!quiet) {\n yield logger.experimentMessage(\n `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n );\n }\n } else if (signal.kind === 'FILE_COUNT') {\n totalFileCount = signal.fileCount;\n } else {\n fileCount++;\n documents.push(...signal.documents);\n if (signal.imports.length) imports.set(signal.filePath, signal.imports);\n if (signal.warnings.length) {\n warnings.push(...signal.warnings);\n if (!quiet) {\n let buffer = logger.warningFile(signal.filePath);\n for (const warning of signal.warnings) {\n buffer += logger.warningMessage(warning);\n logger.warningGithub(warning);\n }\n yield buffer + '\\n';\n }\n }\n }\n\n if (tty.isInteractive && !quiet) yield logger.runningScan(fileCount, totalFileCount);\n }\n } catch (error) {\n throw logger.externalError('Could not scan files', error);\n }\n\n // Both outputs render from the same analysis result (the rule datapoints, plus\n // the context's identities for resolving locators).\n const { context, rules } = analyze({ documents, schemas, imports, warnings });\n\n if (machine) {\n const label = opts.graph ? 'graph' : 'JSON report';\n const render = opts.graph ? renderGraph : renderJson;\n // Default to stdout; `--output` writes a file instead.\n const destination: WriteTarget = opts.output\n ? path.resolve(process.cwd(), opts.output)\n : (tty.pipeTo ?? process.stdout);\n try {\n await writeOutput(destination, render(context, rules));\n } catch (error) {\n throw logger.externalError(`Something went wrong while writing the ${label}`, error);\n }\n if (!quiet && typeof destination === 'string') {\n yield logger.wroteOutput(label, destination);\n }\n } else {\n // Bound item lines to the terminal width so they don't wrap; unbounded when\n // not writing to an interactive terminal.\n const width = tty.isInteractive ? tty.output.columns || 80 : undefined;\n yield renderTerminalReport(context, rules, width);\n }\n\n if (!quiet) {\n yield logger.summary({\n warnings: context.warnings.length,\n operations: context.operations.length,\n fragments: context.fragments.length,\n modules: context.modules.length,\n });\n }\n\n return context.warnings.length;\n}\n","import { visit, visitInParallel, visitWithTypeInfo, TypeInfo, Kind } from 'graphql';\nimport type { DocumentNode } from 'graphql';\n\nimport { ScanContext } from './context';\nimport type { ScanContextParams } from './context';\nimport { DEFAULT_RULES } from './rules';\nimport type { ScanRule, RuleResults } from './types';\n\nexport interface ScanAnalysis {\n context: ScanContext;\n rules: RuleResults;\n}\n\n/**\n * Runs the analysis: builds the context (corpus + primitives), then walks every\n * definition once per schema with all rule visitors merged in parallel —\n * mirroring graphql-js `validate`. Each rule accumulates its own state during\n * the traversal and converts it to datapoints in `collect()`.\n */\nexport function analyze(\n params: ScanContextParams,\n rules: ScanRule[] = DEFAULT_RULES\n): ScanAnalysis {\n const context = new ScanContext(params);\n const instances = rules.map((rule) => ({ name: rule.name, instance: rule.create(context) }));\n\n for (const [schemaName, schema] of context.getSchemas()) {\n const definitions = context.definitionNodesForSchema(schemaName);\n if (!definitions.length) continue;\n\n const typeInfo = new TypeInfo(schema);\n context.setTypeInfo(typeInfo);\n\n // A fresh `visitInParallel` per schema (its skip-state is per-call), but the\n // same rule instances, so their accumulated state carries across schemas.\n const visitor = visitInParallel([\n context.trackingVisitor(),\n ...instances.map(({ instance }) => instance.visitor),\n ]);\n\n const document: DocumentNode = { kind: Kind.DOCUMENT, definitions };\n visit(document, visitWithTypeInfo(typeInfo, visitor));\n }\n\n const results: RuleResults = {};\n for (const { name, instance } of instances) results[name] = instance.collect();\n return { context, rules: results };\n}\n","import { Command, Option } from 'clipanion';\n\nimport type { ScanOptions, ScanFormat } from './runner';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class ScanCommand extends Command {\n static paths = [['scan']];\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` read for configuration.',\n });\n\n format = Option.String('--format,-f', {\n description: 'Emit the machine-readable `json` report.\\tDefault: a terminal report',\n });\n\n graph = Option.Boolean('--graph', false, {\n description: 'Emit only the relationship graph as JSON (implies machine output).',\n });\n\n output = Option.String('--output,-o', {\n description: 'Write machine output to this file.\\tDefault: standard output',\n });\n\n failOnWarn = Option.Boolean('--fail-on-warn,-w', false, {\n description: 'Triggers an error and a non-zero exit code if any warnings have been reported',\n });\n\n async execute() {\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n tsconfig: this.tsconfig,\n format: this.format as ScanFormat | undefined,\n graph: this.graph,\n output: this.output,\n failOnWarn: this.failOnWarn,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Scans a project for all GraphQL documents and fragments, keys them to the\n * schema, and emits a JSON report (when piped or given `--output`) or a\n * human-readable terminal report.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#scan}\n */\nexport async function scan(opts: ScanOptions) {\n const tty = initTTY({ disableTTY: true });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","import { pipe, interval, map, concat, fromValue } from 'wonka';\n\nimport * as path from 'node:path';\nimport * as t from '../../term';\nimport type { DiagnosticMessage } from './types';\nimport type { SeveritySummary } from './types';\n\nexport * from '../shared/logger';\nimport { indent } from '../shared/logger';\n\nconst CWD = process.cwd();\nconst INDENT = ' ';\n\nexport function diagnosticFile(filePath: string) {\n const relativePath = path.relative(CWD, filePath);\n if (!relativePath.startsWith('..')) filePath = relativePath;\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Underline),\n filePath,\n t.cmd(t.CSI.Style, t.Style.NoUnderline),\n '\\n',\n ]);\n}\n\nexport function diagnosticMessage(message: DiagnosticMessage) {\n let color = t.Style.Foreground;\n if (message.severity === 'info') {\n color = t.Style.BrightBlue;\n } else if (message.severity === 'warn') {\n color = t.Style.BrightYellow;\n } else if (message.severity === 'error') {\n color = t.Style.BrightRed;\n }\n\n return t.text([\n INDENT,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${message.line}:${message.col}`,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, color),\n message.severity,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n indent(message.message.trim(), t.text([INDENT, t.Chars.Tab, t.Chars.Tab])),\n t.Chars.Newline,\n ]);\n}\n\nexport function infoSummary(summary: SeveritySummary) {\n const { info, error, warn } = summary;\n let out = '';\n if (info) {\n out += t.text([t.cmd(t.CSI.Style, t.Style.Blue), t.Icons.Info, ` ${info} notices\\n`]);\n }\n if (error || warn) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ` ${error + warn} problems (${error} errors, ${warn} warnings)\\n`,\n ]);\n } else {\n out += t.text([t.cmd(t.CSI.Style, t.Style.BrightGreen), t.Icons.Tick, ` No problems found\\n`]);\n }\n return out;\n}\n\nexport function problemsSummary(summary: SeveritySummary) {\n const { info, error, warn } = summary;\n let out = '';\n if (info) {\n out += t.text([t.cmd(t.CSI.Style, t.Style.Blue), t.Icons.Info, ` ${info} notices\\n`]);\n }\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.Red),\n t.Icons.Cross,\n ` ${error + warn} problems (${error} errors, ${warn} warnings)\\n`,\n ]);\n return t.error(out);\n}\n\nexport function diagnosticMessageGithub(message: DiagnosticMessage): void {\n const kind =\n message.severity === 'warn' ? 'warning' : message.severity === 'error' ? 'error' : 'notice';\n t.githubAnnotation(kind, message.message, {\n file: message.file,\n line: message.line,\n col: message.col,\n endLine: message.endLine,\n endColumn: message.endColumn,\n });\n}\n\nexport function runningDiagnostics(file?: number, ofFiles?: number) {\n const progress = file ? (ofFiles ? `(${file}/${ofFiles})` : `(${file})`) : '';\n const frame = (state: number) =>\n t.text([\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.dotSpinner[state % t.dotSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n `Checking files${t.Chars.Ellipsis} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n progress,\n ]);\n return concat([\n fromValue(frame(0)),\n pipe(\n interval(150),\n map((state) => frame(state + 1))\n ),\n ]);\n}\n","import * as logger from './logger';\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext } from '../shared';\nimport { loadProjects } from '../shared';\nimport type { Severity, SeveritySummary } from './types';\n\nconst isMinSeverity = (severity: Severity, minSeverity: Severity) => {\n switch (severity) {\n case 'info':\n return minSeverity !== 'warn' && minSeverity !== 'error';\n case 'warn':\n return minSeverity !== 'error';\n case 'error':\n return true;\n }\n};\n\nexport interface FormattedDisplayableDiagnostic {\n severity: Severity;\n message: string;\n line: number;\n col: number;\n file: string | undefined;\n}\n\nexport interface Options {\n failOnWarn: boolean | undefined;\n minSeverity: Severity;\n tsconfig: string | undefined;\n}\n\nexport async function* run(tty: TTY, opts: Options): AsyncIterable<ComposeInput> {\n const { runDiagnostics } = await import('./thread');\n\n let projects: ProjectContext[];\n try {\n projects = await loadProjects(opts.tsconfig);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n const summary: SeveritySummary = { warn: 0, error: 0, info: 0 };\n const minSeverity = opts.minSeverity;\n let warnedAboutExternalFiles = false;\n\n for (const project of projects) {\n if (projects.length > 1) yield logger.projectHeader(project.label);\n\n const generator = runDiagnostics({\n rootPath: project.configResult.rootPath,\n tsconfigPath: project.configResult.tsconfigPath,\n configPath: project.configResult.configPath,\n pluginConfig: project.pluginConfig,\n });\n\n let totalFileCount = 0;\n let fileCount = 0;\n\n try {\n if (tty.isInteractive) yield logger.runningDiagnostics();\n\n for await (const signal of generator) {\n if (signal.kind === 'EXTERNAL_WARNING') {\n if (!warnedAboutExternalFiles) {\n warnedAboutExternalFiles = true;\n yield logger.experimentMessage(\n `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n );\n }\n } else if (signal.kind === 'FILE_COUNT') {\n totalFileCount = signal.fileCount;\n } else {\n fileCount++;\n let buffer = '';\n for (const message of signal.messages) {\n summary[message.severity]++;\n if (isMinSeverity(message.severity, minSeverity)) {\n buffer += logger.diagnosticMessage(message);\n logger.diagnosticMessageGithub(message);\n }\n }\n if (buffer) {\n yield logger.diagnosticFile(signal.filePath) + buffer + '\\n';\n }\n }\n\n if (tty.isInteractive) yield logger.runningDiagnostics(fileCount, totalFileCount);\n }\n } catch (error: any) {\n throw logger.externalError('Could not check files', error);\n }\n }\n\n // Reset notice count if it's outside of min severity\n if (minSeverity !== 'info') summary.info = 0;\n\n if ((opts.failOnWarn && summary.warn) || summary.error) {\n throw logger.problemsSummary(summary);\n } else {\n yield logger.infoSummary(summary);\n }\n}\n","import * as t from 'typanion';\nimport { Command, Option } from 'clipanion';\n\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class CheckCommand extends Command {\n static paths = [['check']];\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` used to read',\n });\n\n failOnWarn = Option.Boolean('--fail-on-warn,-w', false, {\n description: 'Triggers an error and a non-zero exit code if any warnings have been reported',\n });\n\n minSeverity =\n Option.String('--level,-l', {\n description: 'The minimum severity of diagnostics to display (info, warn, error)',\n validator: t.isOneOf([t.isLiteral('info'), t.isLiteral('warn'), t.isLiteral('error')]),\n }) || 'info';\n\n async execute() {\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n failOnWarn: this.failOnWarn,\n minSeverity: this.minSeverity,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n","var fn = new Intl.Collator(0, { numeric:1 }).compare;\n\nexport default function (a, b, bool) {\n\ta = a.split('.');\n\tb = b.split('.');\n\n\treturn fn(a[0], b[0]) || fn(a[1], b[1]) || (\n\t\tb[2] = b.slice(2).join('.'),\n\t\tbool = /[.-]/.test(a[2] = a.slice(2).join('.')),\n\t\tbool == /[.-]/.test(b[2]) ? fn(a[2], b[2]) : bool ? -1 : 1\n\t);\n}\n","import semiver from 'semiver';\n\nexport const MINIMUM_VERSIONS = {\n typescript_embed_lsp: '5.5.0',\n typescript: '4.1.0',\n tada: '1.0.0',\n lsp: '1.0.0',\n};\n\nexport const semverComply = (version: string, compare: string) => {\n const match = version.match(/\\d+\\.\\d+\\.\\d+/);\n return match ? semiver(match[0], compare) >= 0 : false;\n};\n","import type ts from 'typescript';\n\nexport interface SourcePosition {\n fileName: string;\n line: number;\n col: number;\n endLine: number | undefined;\n endColumn: number | undefined;\n}\n\nexport const spanToFilePosition = (\n file: ts.SourceFile,\n span: ts.TextSpan | number\n): SourcePosition => {\n const output: SourcePosition = {\n fileName: file.fileName,\n line: 1,\n col: 1,\n endLine: undefined,\n endColumn: undefined,\n };\n let lineAndChar = file.getLineAndCharacterOfPosition(\n typeof span === 'number' ? span : span.start\n );\n output.line = lineAndChar.line + 1;\n output.col = lineAndChar.character + 1;\n if (typeof span !== 'number' && span.length > 1) {\n lineAndChar = file.getLineAndCharacterOfPosition(span.start + span.length - 1);\n output.endLine = lineAndChar.line + 1;\n output.endColumn = lineAndChar.character + 1;\n }\n return output;\n};\n","/**!\n * The MIT License (MIT)\n * Copyright (c) Microsoft Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and\n * associated documentation files (the \"Software\"), to deal in the Software without restriction,\n * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial\n * portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n * @see {@link https://github.com/microsoft/TypeScript-Website/blob/7f1c6e0577a0df9f945530a876ec87145a8b1fee/packages/typescript-vfs/src/index.ts}\n */\n\nimport type {\n System,\n CompilerOptions,\n CustomTransformers,\n LanguageServiceHost,\n CompilerHost,\n SourceFile,\n} from 'typescript';\n\nimport * as path from 'node:path';\nimport * as fs from 'node:fs';\n\ntype TS = typeof import('typescript');\n\nexport interface VirtualTypeScriptEnvironment {\n sys: System;\n languageService: import('typescript').LanguageService;\n getSourceFile: (fileName: string) => import('typescript').SourceFile | undefined;\n createFile: (fileName: string, content: string) => void;\n updateFile: (\n fileName: string,\n content: string,\n replaceTextSpan?: import('typescript').TextSpan\n ) => void;\n}\n\n/**\n * Makes a virtual copy of the TypeScript environment. This is the main API you want to be using with\n * `@typescript/vfs`. A lot of the other exposed functions are used by this function to get set up.\n *\n * @param sys - an object which conforms to the TS Sys (a shim over read/write access to the fs)\n * @param rootFiles - a list of files which are considered inside the project\n * @param ts - a copy of the TypeScript module\n * @param compilerOptions - the options for this compiler run\n * @param customTransformers - custom transformers for this compiler run\n */\nexport function createVirtualTypeScriptEnvironment(\n sys: System,\n rootFiles: string[],\n ts: TS,\n compilerOptions: CompilerOptions = {},\n customTransformers?: CustomTransformers\n): VirtualTypeScriptEnvironment {\n const mergedCompilerOpts = { ...defaultCompilerOptions(ts), ...compilerOptions };\n\n const { languageServiceHost, updateFile } = createVirtualLanguageServiceHost(\n sys,\n rootFiles,\n mergedCompilerOpts,\n ts,\n customTransformers\n );\n const languageService = ts.createLanguageService(languageServiceHost);\n const diagnostics = languageService.getCompilerOptionsDiagnostics();\n\n if (diagnostics.length) {\n const compilerHost = createVirtualCompilerHost(sys, compilerOptions, ts);\n throw new Error(ts.formatDiagnostics(diagnostics, compilerHost.compilerHost));\n }\n\n return {\n // @ts-ignore\n name: 'vfs',\n sys,\n languageService,\n getSourceFile: (fileName) => languageService.getProgram()?.getSourceFile(fileName),\n\n createFile: (fileName, content) => {\n updateFile(ts.createSourceFile(fileName, content, mergedCompilerOpts.target!, false));\n },\n updateFile: (fileName, content, optPrevTextSpan) => {\n const prevSourceFile = languageService.getProgram()!.getSourceFile(fileName);\n if (!prevSourceFile) {\n throw new Error('Did not find a source file for ' + fileName);\n }\n const prevFullContents = prevSourceFile.text;\n\n // TODO: Validate if the default text span has a fencepost error?\n const prevTextSpan = optPrevTextSpan ?? ts.createTextSpan(0, prevFullContents.length);\n const newText =\n prevFullContents.slice(0, prevTextSpan.start) +\n content +\n prevFullContents.slice(prevTextSpan.start + prevTextSpan.length);\n const newSourceFile = ts.updateSourceFile(prevSourceFile, newText, {\n span: prevTextSpan,\n newLength: content.length,\n });\n\n updateFile(newSourceFile);\n },\n };\n}\n\n// TODO: This could be replaced by grabbing: https://github.com/microsoft/TypeScript/blob/main/src/lib/libs.json\n// and then using that to generate the list of files from the server, but it is not included in the npm package\n\n/**\n * Grab the list of lib files for a particular target, will return a bit more than necessary (by including\n * the dom) but that's OK, we're really working with the constraint that you can't get a list of files\n * when running in a browser.\n *\n * @param target - The compiler settings target baseline\n * @param ts - A copy of the TypeScript module\n */\nexport const knownLibFilesForCompilerOptions = (compilerOptions: CompilerOptions, ts: TS) => {\n const target = compilerOptions.target || ts.ScriptTarget.ES5;\n const lib = compilerOptions.lib || [];\n\n // Note that this will include files which can't be found for particular versions of TS\n // TODO: Replace this with some sort of API call if https://github.com/microsoft/TypeScript/pull/54011\n // or similar is merged.\n const files = [\n 'lib.d.ts',\n 'lib.decorators.d.ts',\n 'lib.decorators.legacy.d.ts',\n 'lib.dom.d.ts',\n 'lib.dom.iterable.d.ts',\n 'lib.webworker.d.ts',\n 'lib.webworker.importscripts.d.ts',\n 'lib.webworker.iterable.d.ts',\n 'lib.scripthost.d.ts',\n 'lib.es5.d.ts',\n 'lib.es6.d.ts',\n 'lib.es2015.collection.d.ts',\n 'lib.es2015.core.d.ts',\n 'lib.es2015.d.ts',\n 'lib.es2015.generator.d.ts',\n 'lib.es2015.iterable.d.ts',\n 'lib.es2015.promise.d.ts',\n 'lib.es2015.proxy.d.ts',\n 'lib.es2015.reflect.d.ts',\n 'lib.es2015.symbol.d.ts',\n 'lib.es2015.symbol.wellknown.d.ts',\n 'lib.es2016.array.include.d.ts',\n 'lib.es2016.d.ts',\n 'lib.es2016.full.d.ts',\n 'lib.es2017.d.ts',\n 'lib.es2017.date.d.ts',\n 'lib.es2017.full.d.ts',\n 'lib.es2017.intl.d.ts',\n 'lib.es2017.object.d.ts',\n 'lib.es2017.sharedmemory.d.ts',\n 'lib.es2017.string.d.ts',\n 'lib.es2017.typedarrays.d.ts',\n 'lib.es2018.asyncgenerator.d.ts',\n 'lib.es2018.asynciterable.d.ts',\n 'lib.es2018.d.ts',\n 'lib.es2018.full.d.ts',\n 'lib.es2018.intl.d.ts',\n 'lib.es2018.promise.d.ts',\n 'lib.es2018.regexp.d.ts',\n 'lib.es2019.array.d.ts',\n 'lib.es2019.d.ts',\n 'lib.es2019.full.d.ts',\n 'lib.es2019.intl.d.ts',\n 'lib.es2019.object.d.ts',\n 'lib.es2019.string.d.ts',\n 'lib.es2019.symbol.d.ts',\n 'lib.es2020.bigint.d.ts',\n 'lib.es2020.d.ts',\n 'lib.es2020.date.d.ts',\n 'lib.es2020.full.d.ts',\n 'lib.es2020.intl.d.ts',\n 'lib.es2020.number.d.ts',\n 'lib.es2020.promise.d.ts',\n 'lib.es2020.sharedmemory.d.ts',\n 'lib.es2020.string.d.ts',\n 'lib.es2020.symbol.wellknown.d.ts',\n 'lib.es2021.d.ts',\n 'lib.es2021.full.d.ts',\n 'lib.es2021.intl.d.ts',\n 'lib.es2021.promise.d.ts',\n 'lib.es2021.string.d.ts',\n 'lib.es2021.weakref.d.ts',\n 'lib.es2022.array.d.ts',\n 'lib.es2022.d.ts',\n 'lib.es2022.error.d.ts',\n 'lib.es2022.full.d.ts',\n 'lib.es2022.intl.d.ts',\n 'lib.es2022.object.d.ts',\n 'lib.es2022.regexp.d.ts',\n 'lib.es2022.sharedmemory.d.ts',\n 'lib.es2022.string.d.ts',\n 'lib.es2023.array.d.ts',\n 'lib.es2023.collection.d.ts',\n 'lib.es2023.d.ts',\n 'lib.es2023.full.d.ts',\n 'lib.esnext.array.d.ts',\n 'lib.esnext.asynciterable.d.ts',\n 'lib.esnext.bigint.d.ts',\n 'lib.esnext.d.ts',\n 'lib.esnext.decorators.d.ts',\n 'lib.esnext.disposable.d.ts',\n 'lib.esnext.full.d.ts',\n 'lib.esnext.intl.d.ts',\n 'lib.esnext.promise.d.ts',\n 'lib.esnext.string.d.ts',\n 'lib.esnext.symbol.d.ts',\n 'lib.esnext.weakref.d.ts',\n ];\n\n const targetToCut = ts.ScriptTarget[target];\n const matches = files.filter((f) => f.startsWith(`lib.${targetToCut.toLowerCase()}`));\n const targetCutIndex = files.indexOf(matches.pop()!);\n\n const getMax = (array: number[]) =>\n array && array.length\n ? array.reduce((max, current) => (current > max ? current : max))\n : undefined;\n\n // Find the index for everything in\n const indexesForCutting = lib.map((lib) => {\n const matches = files.filter((f) => f.startsWith(`lib.${lib.toLowerCase()}`));\n if (matches.length === 0) return 0;\n\n const cutIndex = files.indexOf(matches.pop()!);\n return cutIndex;\n });\n\n const libCutIndex = getMax(indexesForCutting) || 0;\n\n const finalCutIndex = Math.max(targetCutIndex, libCutIndex);\n return files.slice(0, finalCutIndex + 1);\n};\n\n/**\n * Sets up a Map with lib contents by grabbing the necessary files from\n * the local copy of typescript via the file system.\n *\n * The first two args are un-used, but kept around so as to not cause a\n * semver major bump for no gain to module users.\n */\nexport const createDefaultMapFromNodeModules = (\n _compilerOptions: CompilerOptions,\n _ts?: typeof import('typescript'),\n tsLibDirectory?: string\n) => {\n const getLib = (name: string) => {\n const lib = tsLibDirectory || path.dirname(require.resolve('typescript'));\n return fs.readFileSync(path.join(lib, name), 'utf8');\n };\n\n const libFiles = fs.readdirSync(tsLibDirectory || path.dirname(require.resolve('typescript')));\n const knownLibFiles = libFiles.filter((f) => f.startsWith('lib.') && f.endsWith('.d.ts'));\n\n const fsMap = new Map<string, string>();\n knownLibFiles.forEach((lib) => {\n fsMap.set('/' + lib, getLib(lib));\n });\n return fsMap;\n};\n\n/**\n * Adds recursively files from the FS into the map based on the folder\n */\nexport const addAllFilesFromFolder = (map: Map<string, string>, workingDir: string): void => {\n const walk = function (dir: string) {\n let results: string[] = [];\n const list = fs.readdirSync(dir);\n list.forEach(function (file: string) {\n file = path.join(dir, file);\n const stat = fs.statSync(file);\n if (stat && stat.isDirectory()) {\n /* Recurse into a subdirectory */\n results = results.concat(walk(file));\n } else {\n /* Is a file */\n results.push(file);\n }\n });\n return results;\n };\n\n const allFiles = walk(workingDir);\n\n allFiles.forEach((lib) => {\n const fsPath = '/node_modules/@types' + lib.replace(workingDir, '');\n const content = fs.readFileSync(lib, 'utf8');\n const validExtensions = ['.ts', '.tsx'];\n\n if (validExtensions.includes(path.extname(fsPath))) {\n map.set(fsPath, content);\n }\n });\n};\n\n/** Adds all files from `node_modules/@types` into the FS Map */\nexport const addFilesForTypesIntoFolder = (map: Map<string, string>) =>\n addAllFilesFromFolder(map, 'node_modules/@types');\n\nfunction notImplemented(methodName: string): any {\n throw new Error(`Method '${methodName}' is not implemented.`);\n}\n\n/** The default compiler options if TypeScript could ever change the compiler options */\nconst defaultCompilerOptions = (ts: typeof import('typescript')): CompilerOptions => {\n return {\n ...ts.getDefaultCompilerOptions(),\n jsx: ts.JsxEmit.React,\n strict: true,\n esModuleInterop: true,\n module: ts.ModuleKind.ESNext,\n suppressOutputPathCheck: true,\n skipLibCheck: true,\n skipDefaultLibCheck: true,\n moduleResolution: ts.ModuleResolutionKind.NodeJs,\n };\n};\n\n// \"/DOM.d.ts\" => \"/lib.dom.d.ts\"\nconst libize = (path: string) => path.replace('/', '/lib.').toLowerCase();\n\n/**\n * Creates an in-memory System object which can be used in a TypeScript program, this\n * is what provides read/write aspects of the virtual fs\n */\nexport function createSystem(files: Map<string, string>): System {\n return {\n args: [],\n createDirectory: () => notImplemented('createDirectory'),\n // TODO: could make a real file tree\n directoryExists: (directory) => {\n return Array.from(files.keys()).some((path) => path.startsWith(directory));\n },\n exit: () => notImplemented('exit'),\n fileExists: (fileName) => files.has(fileName) || files.has(libize(fileName)),\n getCurrentDirectory: () => '/',\n getDirectories: () => [],\n getExecutingFilePath: () => notImplemented('getExecutingFilePath'),\n readDirectory: (directory) => (directory === '/' ? Array.from(files.keys()) : []),\n readFile: (fileName) => files.get(fileName) || files.get(libize(fileName)),\n resolvePath: (path) => path,\n newLine: '\\n',\n useCaseSensitiveFileNames: true,\n write: () => notImplemented('write'),\n writeFile: (fileName, contents) => {\n files.set(fileName, contents);\n },\n };\n}\n\n/**\n * Creates a file-system backed System object which can be used in a TypeScript program, you provide\n * a set of virtual files which are prioritised over the FS versions, then a path to the root of your\n * project (basically the folder your node_modules lives)\n */\nexport function createFSBackedSystem(\n files: Map<string, string>,\n _projectRoot: string,\n ts: TS,\n tsLibDirectory?: string\n): System {\n // We need to make an isolated folder for the tsconfig, but also need to be able to resolve the\n // existing node_modules structures going back through the history\n const root = _projectRoot + '/vfs';\n\n // The default System in TypeScript\n const nodeSys = ts.sys;\n const tsLib = tsLibDirectory ?? path.dirname(require.resolve('typescript'));\n\n return {\n // @ts-ignore\n name: 'fs-vfs',\n root,\n args: [],\n realpath: (directory) => {\n if (nodeSys.realpath) return nodeSys.realpath(directory);\n return directory;\n },\n createDirectory: () => notImplemented('createDirectory'),\n // TODO: could make a real file tree\n directoryExists: (directory) => {\n return (\n Array.from(files.keys()).some((path) => path.startsWith(directory)) ||\n nodeSys.directoryExists(directory)\n );\n },\n exit: nodeSys.exit,\n fileExists: (fileName) => {\n if (files.has(fileName)) return true;\n // Don't let other tsconfigs end up touching the vfs\n if (fileName.includes('tsconfig.json') || fileName.includes('tsconfig.json')) return false;\n if (fileName.startsWith('/lib')) {\n const tsLibName = `${tsLib}/${fileName.replace('/', '')}`;\n return nodeSys.fileExists(tsLibName);\n }\n return nodeSys.fileExists(fileName);\n },\n getCurrentDirectory: () => root,\n getDirectories: nodeSys.getDirectories,\n getExecutingFilePath: () => notImplemented('getExecutingFilePath'),\n readDirectory: (...args) => {\n if (args[0] === '/') {\n return Array.from(files.keys());\n } else {\n return nodeSys.readDirectory(...args);\n }\n },\n readFile: (fileName) => {\n if (files.has(fileName)) return files.get(fileName);\n if (fileName.startsWith('/lib')) {\n const tsLibName = `${tsLib}/${fileName.replace('/', '')}`;\n const result = nodeSys.readFile(tsLibName);\n if (!result) {\n const libs = nodeSys.readDirectory(tsLib);\n throw new Error(\n `TSVFS: A request was made for ${tsLibName} but there wasn't a file found in the file map. You likely have a mismatch in the compiler options for the CDN download vs the compiler program. Existing Libs: ${libs}.`\n );\n }\n return result;\n }\n return nodeSys.readFile(fileName);\n },\n resolvePath: (path) => {\n if (files.has(path)) return path;\n return nodeSys.resolvePath(path);\n },\n newLine: '\\n',\n useCaseSensitiveFileNames: true,\n write: () => notImplemented('write'),\n writeFile: (fileName, contents) => {\n files.set(fileName, contents);\n },\n };\n}\n\n/**\n * Creates an in-memory CompilerHost -which is essentially an extra wrapper to System\n * which works with TypeScript objects - returns both a compiler host, and a way to add new SourceFile\n * instances to the in-memory file system.\n */\nexport function createVirtualCompilerHost(sys: System, compilerOptions: CompilerOptions, ts: TS) {\n const sourceFiles = new Map<string, SourceFile>();\n const save = (sourceFile: SourceFile) => {\n sourceFiles.set(sourceFile.fileName, sourceFile);\n return sourceFile;\n };\n\n type Return = {\n compilerHost: CompilerHost;\n updateFile: (sourceFile: SourceFile) => boolean;\n };\n\n const vHost: Return = {\n compilerHost: {\n ...sys,\n getCanonicalFileName: (fileName) => fileName,\n getDefaultLibFileName: () => '/' + ts.getDefaultLibFileName(compilerOptions), // '/lib.d.ts',\n // getDefaultLibLocation: () => '/',\n getDirectories: () => [],\n getNewLine: () => sys.newLine,\n getSourceFile: (fileName) => {\n return (\n sourceFiles.get(fileName) ||\n save(\n ts.createSourceFile(\n fileName,\n sys.readFile(fileName)!,\n compilerOptions.target || defaultCompilerOptions(ts).target!,\n false\n )\n )\n );\n },\n useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,\n },\n updateFile: (sourceFile) => {\n const alreadyExists = sourceFiles.has(sourceFile.fileName);\n sys.writeFile(sourceFile.fileName, sourceFile.text);\n sourceFiles.set(sourceFile.fileName, sourceFile);\n return alreadyExists;\n },\n };\n return vHost;\n}\n\n/**\n * Creates an object which can host a language service against the virtual file-system\n */\nexport function createVirtualLanguageServiceHost(\n sys: System,\n rootFiles: string[],\n compilerOptions: CompilerOptions,\n ts: TS,\n customTransformers?: CustomTransformers\n) {\n const fileNames = [...rootFiles];\n const { compilerHost, updateFile } = createVirtualCompilerHost(sys, compilerOptions, ts);\n const fileVersions = new Map<string, string>();\n let projectVersion = 0;\n const languageServiceHost: LanguageServiceHost = {\n ...compilerHost,\n getProjectVersion: () => projectVersion.toString(),\n getCompilationSettings: () => compilerOptions,\n getCustomTransformers: () => customTransformers,\n // A couple weeks of 4.8 TypeScript nightlies had a bug where the Program's\n // list of files was just a reference to the array returned by this host method,\n // which means mutations by the host that ought to result in a new Program being\n // created were not detected, since the old list of files and the new list of files\n // were in fact a reference to the same underlying array. That was fixed in\n // https://github.com/microsoft/TypeScript/pull/49813, but since the twoslash runner\n // is used in bisecting for changes, it needs to guard against being busted in that\n // couple-week period, so we defensively make a slice here.\n getScriptFileNames: () => fileNames.slice(),\n getScriptSnapshot: (fileName) => {\n const contents = sys.readFile(fileName);\n if (contents) {\n return ts.ScriptSnapshot.fromString(contents);\n }\n return;\n },\n getScriptVersion: (fileName) => {\n return fileVersions.get(fileName) || '0';\n },\n writeFile: sys.writeFile,\n };\n\n type Return = {\n languageServiceHost: LanguageServiceHost;\n updateFile: (sourceFile: import('typescript').SourceFile) => void;\n };\n\n const lsHost: Return = {\n languageServiceHost,\n updateFile: (sourceFile) => {\n projectVersion++;\n fileVersions.set(sourceFile.fileName, projectVersion.toString());\n if (!fileNames.includes(sourceFile.fileName)) {\n fileNames.push(sourceFile.fileName);\n }\n updateFile(sourceFile);\n },\n };\n return lsHost;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.binarySearch = void 0;\nfunction binarySearch(offsets, start) {\n let low = 0;\n let high = offsets.length - 1;\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const midValue = offsets[mid];\n if (midValue < start) {\n low = mid + 1;\n }\n else if (midValue > start) {\n high = mid - 1;\n }\n else {\n low = mid;\n high = mid;\n break;\n }\n }\n return Math.max(Math.min(low, high, offsets.length - 1), 0);\n}\nexports.binarySearch = binarySearch;\n//# sourceMappingURL=binarySearch.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getStack = exports.track = exports.resetOffsetStack = exports.offsetStack = exports.setTracking = void 0;\nlet tracking = true;\nlet stackOffset = 0;\nfunction setTracking(value) {\n tracking = value;\n}\nexports.setTracking = setTracking;\nfunction offsetStack() {\n stackOffset++;\n}\nexports.offsetStack = offsetStack;\nfunction resetOffsetStack() {\n stackOffset--;\n}\nexports.resetOffsetStack = resetOffsetStack;\nfunction track(segments, stacks = []) {\n return [\n new Proxy(segments, {\n get(target, prop, receiver) {\n if (tracking) {\n if (prop === 'push')\n return push;\n if (prop === 'pop')\n return pop;\n if (prop === 'shift')\n return shift;\n if (prop === 'unshift')\n return unshift;\n if (prop === 'splice')\n return splice;\n if (prop === 'sort')\n return sort;\n if (prop === 'reverse')\n return reverse;\n }\n return Reflect.get(target, prop, receiver);\n }\n }),\n stacks,\n ];\n function push(...items) {\n stacks.push({ stack: getStack(), length: items.length });\n return segments.push(...items);\n }\n function pop() {\n if (stacks.length) {\n const last = stacks[stacks.length - 1];\n if (last.length > 1) {\n last.length--;\n }\n else {\n stacks.pop();\n }\n }\n return segments.pop();\n }\n function shift() {\n if (stacks.length) {\n const first = stacks[0];\n if (first.length > 1) {\n first.length--;\n }\n else {\n stacks.shift();\n }\n }\n return segments.shift();\n }\n function unshift(...items) {\n stacks.unshift({ stack: getStack(), length: items.length });\n return segments.unshift(...items);\n }\n function splice(start, deleteCount, ...items) {\n if (deleteCount === undefined) {\n deleteCount = segments.length - start;\n }\n let _stackStart = 0;\n let operateIndex;\n for (let i = 0; i < stacks.length; i++) {\n const stack = stacks[i];\n const stackStart = _stackStart;\n const stackEnd = stackStart + stack.length;\n _stackStart = stackEnd;\n if (start >= stackStart) {\n operateIndex = i + 1;\n const originalLength = stack.length;\n stack.length = start - stackStart;\n stacks.splice(operateIndex, 0, { stack: stack.stack, length: originalLength - stack.length });\n break;\n }\n }\n if (operateIndex === undefined) {\n throw new Error('Invalid splice operation');\n }\n let _deleteCount = deleteCount;\n for (let i = operateIndex; i < stacks.length; i++) {\n const stack = stacks[i];\n while (_deleteCount > 0 && stack.length > 0) {\n stack.length--;\n _deleteCount--;\n }\n if (_deleteCount === 0) {\n break;\n }\n }\n stacks.splice(operateIndex, 0, { stack: getStack(), length: items.length });\n return segments.splice(start, deleteCount, ...items);\n }\n function sort(compareFn) {\n stacks.splice(0, stacks.length, { stack: getStack(), length: segments.length });\n return segments.sort(compareFn);\n }\n function reverse() {\n stacks.splice(0, stacks.length, { stack: getStack(), length: segments.length });\n return segments.reverse();\n }\n}\nexports.track = track;\nfunction getStack() {\n const stack = new Error().stack;\n let source = stack.split('\\n')[3 + stackOffset].trim();\n if (source.endsWith(')')) {\n source = source.slice(source.lastIndexOf('(') + 1, -1);\n }\n else {\n source = source.slice(source.lastIndexOf(' ') + 1);\n }\n return source;\n}\nexports.getStack = getStack;\n//# sourceMappingURL=track.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=types.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.replaceRange = exports.replaceSourceRange = exports.replaceAll = exports.replace = exports.create = exports.toString = exports.getLength = void 0;\nconst binarySearch_1 = require(\"./binarySearch\");\nconst track_1 = require(\"./track\");\n__exportStar(require(\"./types\"), exports);\n__exportStar(require(\"./track\"), exports);\nfunction getLength(segments) {\n let length = 0;\n for (const segment of segments) {\n length += typeof segment == 'string' ? segment.length : segment[0].length;\n }\n return length;\n}\nexports.getLength = getLength;\nfunction toString(segments) {\n return segments.map(s => typeof s === 'string' ? s : s[0]).join('');\n}\nexports.toString = toString;\nfunction create(source) {\n return [[source, undefined, 0]];\n}\nexports.create = create;\nfunction replace(segments, pattern, ...replacers) {\n const str = toString(segments);\n const match = str.match(pattern);\n if (match && match.index !== undefined) {\n const startOffset = match.index;\n const endOffset = startOffset + match[0].length;\n (0, track_1.offsetStack)();\n replaceRange(segments, startOffset, endOffset, ...replacers.map(replacer => typeof replacer === 'function' ? replacer(match[0]) : replacer));\n (0, track_1.resetOffsetStack)();\n }\n}\nexports.replace = replace;\nfunction replaceAll(segments, pattern, ...replacers) {\n const str = toString(segments);\n const allMatch = str.matchAll(pattern);\n let length = str.length;\n let lengthDiff = 0;\n for (const match of allMatch) {\n if (match.index !== undefined) {\n const startOffset = match.index + lengthDiff;\n const endOffset = startOffset + match[0].length;\n (0, track_1.offsetStack)();\n replaceRange(segments, startOffset, endOffset, ...replacers.map(replacer => typeof replacer === 'function' ? replacer(match[0]) : replacer));\n (0, track_1.resetOffsetStack)();\n const newLength = getLength(segments);\n lengthDiff += newLength - length;\n length = newLength;\n }\n }\n}\nexports.replaceAll = replaceAll;\nfunction replaceSourceRange(segments, source, startOffset, endOffset, ...newSegments) {\n for (const segment of segments) {\n if (typeof segment === 'string') {\n continue;\n }\n if (segment[1] === source) {\n const segmentStart = segment[2];\n const segmentEnd = segment[2] + segment[0].length;\n if (segmentStart <= startOffset && segmentEnd >= endOffset) {\n const inserts = [];\n if (startOffset > segmentStart) {\n inserts.push(trimSegmentEnd(segment, startOffset - segmentStart));\n }\n for (const newSegment of newSegments) {\n inserts.push(newSegment);\n }\n if (endOffset < segmentEnd) {\n inserts.push(trimSegmentStart(segment, endOffset - segmentEnd));\n }\n combineStrings(inserts);\n (0, track_1.offsetStack)();\n segments.splice(segments.indexOf(segment), 1, ...inserts);\n (0, track_1.resetOffsetStack)();\n return true;\n }\n }\n }\n return false;\n}\nexports.replaceSourceRange = replaceSourceRange;\nfunction replaceRange(segments, startOffset, endOffset, ...newSegments) {\n const offsets = toOffsets(segments);\n const startIndex = (0, binarySearch_1.binarySearch)(offsets, startOffset);\n const endIndex = (0, binarySearch_1.binarySearch)(offsets, endOffset);\n const startSegment = segments[startIndex];\n const endSegment = segments[endIndex];\n const startSegmentStart = offsets[startIndex];\n const endSegmentStart = offsets[endIndex];\n const endSegmentEnd = offsets[endIndex] + (typeof endSegment === 'string' ? endSegment.length : endSegment[0].length);\n const inserts = [];\n if (startOffset > startSegmentStart) {\n inserts.push(trimSegmentEnd(startSegment, startOffset - startSegmentStart));\n }\n for (const newSegment of newSegments) {\n inserts.push(newSegment);\n }\n if (endOffset < endSegmentEnd) {\n inserts.push(trimSegmentStart(endSegment, endOffset - endSegmentStart));\n }\n combineStrings(inserts);\n (0, track_1.offsetStack)();\n segments.splice(startIndex, endIndex - startIndex + 1, ...inserts);\n (0, track_1.resetOffsetStack)();\n}\nexports.replaceRange = replaceRange;\nfunction combineStrings(segments) {\n for (let i = segments.length - 1; i >= 1; i--) {\n if (typeof segments[i] === 'string' && typeof segments[i - 1] === 'string') {\n segments[i - 1] = segments[i - 1] + segments[i];\n (0, track_1.offsetStack)();\n segments.splice(i, 1);\n (0, track_1.resetOffsetStack)();\n }\n }\n}\nfunction trimSegmentEnd(segment, trimEnd) {\n if (typeof segment === 'string') {\n return segment.slice(0, trimEnd);\n }\n return [\n segment[0].slice(0, trimEnd),\n ...segment.slice(1),\n ];\n}\nfunction trimSegmentStart(segment, trimStart) {\n if (typeof segment === 'string') {\n return segment.slice(trimStart);\n }\n if (trimStart < 0) {\n trimStart += segment[0].length;\n }\n return [\n segment[0].slice(trimStart),\n segment[1],\n segment[2] + trimStart,\n ...segment.slice(3),\n ];\n}\nfunction toOffsets(segments) {\n const offsets = [];\n let offset = 0;\n for (const segment of segments) {\n offsets.push(offset);\n offset += typeof segment == 'string' ? segment.length : segment[0].length;\n }\n return offsets;\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.binarySearch = void 0;\nfunction binarySearch(values, searchValue) {\n let low = 0;\n let high = values.length - 1;\n let match;\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const midValue = values[mid];\n if (midValue < searchValue) {\n low = mid + 1;\n }\n else if (midValue > searchValue) {\n high = mid - 1;\n }\n else {\n low = mid;\n high = mid;\n match = mid;\n break;\n }\n }\n const finalLow = Math.max(Math.min(low, high, values.length - 1), 0);\n const finalHigh = Math.min(Math.max(low, high, 0), values.length - 1);\n return { low: finalLow, high: finalHigh, match };\n}\nexports.binarySearch = binarySearch;\n//# sourceMappingURL=binarySearch.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.translateOffset = void 0;\nfunction translateOffset(start, fromOffsets, toOffsets, lengths) {\n for (let i = 0; i < fromOffsets.length; i++) {\n const fromOffset = fromOffsets[i];\n const toOffset = toOffsets[i];\n const length = lengths[i];\n if (start >= fromOffset && start <= fromOffset + length) {\n return toOffset + start - fromOffset;\n }\n }\n}\nexports.translateOffset = translateOffset;\n//# sourceMappingURL=translateOffset.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SourceMap = void 0;\nconst binarySearch_1 = require(\"./binarySearch\");\nconst translateOffset_1 = require(\"./translateOffset\");\nclass SourceMap {\n constructor(mappings) {\n this.mappings = mappings;\n }\n getSourceOffset(generatedOffset) {\n for (const mapped of this.findMatching(generatedOffset, 'generatedOffsets', 'sourceOffsets')) {\n return mapped;\n }\n }\n getGeneratedOffset(sourceOffset) {\n for (const mapped of this.findMatching(sourceOffset, 'sourceOffsets', 'generatedOffsets')) {\n return mapped;\n }\n }\n getSourceOffsets(generatedOffset) {\n return this.findMatching(generatedOffset, 'generatedOffsets', 'sourceOffsets');\n }\n getGeneratedOffsets(sourceOffset) {\n return this.findMatching(sourceOffset, 'sourceOffsets', 'generatedOffsets');\n }\n *findMatching(offset, fromRange, toRange) {\n const memo = this.getMemoBasedOnRange(fromRange);\n if (memo.offsets.length === 0) {\n return;\n }\n const { low: start, high: end } = (0, binarySearch_1.binarySearch)(memo.offsets, offset);\n const skip = new Set();\n for (let i = start; i <= end; i++) {\n for (const mapping of memo.mappings[i]) {\n if (skip.has(mapping)) {\n continue;\n }\n skip.add(mapping);\n const mapped = (0, translateOffset_1.translateOffset)(offset, mapping[fromRange], mapping[toRange], mapping.lengths);\n if (mapped !== undefined) {\n yield [mapped, mapping];\n }\n }\n }\n }\n getMemoBasedOnRange(fromRange) {\n return fromRange === 'sourceOffsets'\n ? this.sourceCodeOffsetsMemo ??= this.createMemo('sourceOffsets')\n : this.generatedCodeOffsetsMemo ??= this.createMemo('generatedOffsets');\n }\n createMemo(key) {\n const offsetsSet = new Set();\n for (const mapping of this.mappings) {\n for (let i = 0; i < mapping[key].length; i++) {\n offsetsSet.add(mapping[key][i]);\n offsetsSet.add(mapping[key][i] + mapping.lengths[i]);\n }\n }\n const offsets = [...offsetsSet].sort((a, b) => a - b);\n const mappings = offsets.map(() => new Set());\n for (const mapping of this.mappings) {\n for (let i = 0; i < mapping[key].length; i++) {\n const startIndex = (0, binarySearch_1.binarySearch)(offsets, mapping[key][i]).match;\n const endIndex = (0, binarySearch_1.binarySearch)(offsets, mapping[key][i] + mapping.lengths[i]).match;\n for (let i = startIndex; i <= endIndex; i++) {\n mappings[i].add(mapping);\n }\n }\n }\n return { offsets, mappings };\n }\n}\nexports.SourceMap = SourceMap;\n//# sourceMappingURL=sourceMap.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.buildMappings = void 0;\nfunction buildMappings(chunks) {\n let length = 0;\n const mappings = [];\n for (const segment of chunks) {\n if (typeof segment === 'string') {\n length += segment.length;\n }\n else {\n mappings.push({\n source: segment[1],\n sourceOffsets: [segment[2]],\n generatedOffsets: [length],\n lengths: [segment[0].length],\n data: segment[3],\n });\n length += segment[0].length;\n }\n }\n return mappings;\n}\nexports.buildMappings = buildMappings;\n//# sourceMappingURL=buildMappings.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.buildStacks = void 0;\nfunction buildStacks(chunks, stacks) {\n let offset = 0;\n let index = 0;\n const result = [];\n for (const stack of stacks) {\n const start = offset;\n for (let i = 0; i < stack.length; i++) {\n const segment = chunks[index + i];\n if (typeof segment === 'string') {\n offset += segment.length;\n }\n else {\n offset += segment[0].length;\n }\n }\n index += stack.length;\n result.push({\n source: stack.stack,\n range: [start, offset],\n });\n }\n return result;\n}\nexports.buildStacks = buildStacks;\n//# sourceMappingURL=buildStacks.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"muggle-string\"), exports);\n__exportStar(require(\"./lib/sourceMap\"), exports);\n__exportStar(require(\"./lib/translateOffset\"), exports);\n__exportStar(require(\"./lib/buildMappings\"), exports);\n__exportStar(require(\"./lib/buildStacks\"), exports);\n//# sourceMappingURL=index.js.map","import type ts from 'typescript';\nimport { SourceMap } from '@volar/source-map';\nimport type { Mapping } from '@volar/source-map';\n\nexport type VirtualMap = Map<string, SourceMappedFile>;\nexport type { Mapping };\n\nexport interface FileSpan extends ts.TextSpan {\n fileName: string;\n}\n\nexport class SourceMappedFile extends SourceMap {\n readonly sourceFile: ts.SourceFile;\n readonly sourceFileId: string;\n readonly generatedFileId: string;\n\n constructor(\n mappings: readonly Mapping[],\n params: {\n sourceFile: ts.SourceFile;\n sourceFileId: string;\n generatedFileId: string;\n }\n ) {\n super(mappings as Mapping[]);\n this.sourceFile = params.sourceFile;\n this.sourceFileId = params.sourceFileId;\n this.generatedFileId = params.generatedFileId;\n }\n\n getSourceSpan(span: ts.TextSpan | number): FileSpan {\n const sourceStart = this.getSourceOffset(typeof span === 'number' ? span : span.start);\n if (sourceStart != null) {\n const sourceEnd =\n typeof span !== 'number' ? this.getSourceOffset(span.start + span.length - 1) : null;\n return {\n fileName: this.sourceFileId,\n start: sourceStart[0],\n length:\n sourceEnd != null\n ? sourceEnd[0] - sourceStart[0] + 1\n : typeof span !== 'number'\n ? span.length\n : 1,\n };\n } else {\n return {\n fileName: this.generatedFileId,\n start: typeof span !== 'number' ? span.start : span,\n length: typeof span !== 'number' ? span.length : 1,\n };\n }\n }\n}\n","import ts from 'typescript';\nimport * as path from 'node:path';\nimport type { GraphQLSPConfig } from '@gql.tada/internal';\nimport { createVirtualLanguageServiceHost } from './vendor/typescript-vfs';\n\nimport type { VirtualMap, SourceMappedFile, FileSpan } from './mapping';\n\nimport type { SourcePosition } from './utils';\nimport { spanToFilePosition } from './utils';\n\nfunction maybeBind<T extends Function>(that: object, fn: T): T;\nfunction maybeBind(that: object, fn: undefined): undefined;\nfunction maybeBind<T extends Function>(that: object, fn: T | undefined): T | undefined {\n return fn ? (fn.bind(that) as T) : undefined;\n}\n\nexport interface PluginCreateInfo<Config extends {} = GraphQLSPConfig>\n extends ts.server.PluginCreateInfo {\n config: Config;\n}\n\nexport interface ProgramContainer {\n readonly program: ts.Program;\n readonly languageService: ts.LanguageService;\n buildPluginInfo<Config extends {}>(config: Config): PluginCreateInfo<Config>;\n\n getSourceFile(fileId: string): ts.SourceFile | undefined;\n getSourceFiles(): readonly ts.SourceFile[];\n getSourceMappedFile(fileId: string | ts.SourceFile): SourceMappedFile | undefined;\n getSourceSpan(fileId: string | ts.SourceFile, span: ts.TextSpan | number): FileSpan;\n getSourcePosition(fileId: string | ts.SourceFile, span: ts.TextSpan | number): SourcePosition;\n}\n\nexport interface ContainerParams {\n virtualMap: VirtualMap;\n projectRoot: string;\n compilerHost: ts.CompilerHost;\n rootNames: readonly string[];\n options: ts.CompilerOptions;\n system: ts.System;\n documentRegistry?: ts.DocumentRegistry;\n}\n\nexport const buildContainer = (params: ContainerParams): ProgramContainer => {\n let program: ts.Program | undefined;\n let service: ts.LanguageService | undefined;\n let serviceHost: ts.LanguageServiceHost | undefined;\n let pluginInfo: PluginCreateInfo<any> | undefined;\n\n const getLanguageServiceHost = () =>\n serviceHost ||\n (serviceHost = createVirtualLanguageServiceHost(\n params.system,\n [...params.rootNames],\n params.options,\n ts\n ).languageServiceHost);\n\n const getLanguageService = () =>\n service ||\n (service = buildLanguageService({\n system: params.system,\n rootNames: params.rootNames,\n virtualMap: params.virtualMap,\n options: params.options,\n projectRoot: params.projectRoot,\n languageServiceHost: getLanguageServiceHost(),\n documentRegistry: params.documentRegistry,\n }));\n\n const getProgram = () => {\n if (!program) {\n program =\n getLanguageService().getProgram() ||\n ts.createProgram({\n rootNames: params.rootNames,\n options: params.options,\n host: params.compilerHost,\n });\n }\n return program;\n };\n\n return {\n get program() {\n return getProgram();\n },\n get languageService() {\n return getLanguageService();\n },\n buildPluginInfo(config) {\n return (\n pluginInfo ||\n (pluginInfo = buildPluginInfo({\n getLanguageService,\n getLanguageServiceHost,\n projectRoot: params.projectRoot,\n rootNames: params.rootNames,\n system: params.system,\n options: params.options,\n config,\n }))\n );\n },\n\n getSourceFile(fileId) {\n return getProgram().getSourceFile(fileId);\n },\n getSourceFiles() {\n return getProgram().getSourceFiles();\n },\n getSourceMappedFile(file) {\n const fileId = typeof file !== 'string' ? file.fileName : file;\n return params.virtualMap.get(fileId);\n },\n getSourceSpan(file, span) {\n const fileId = typeof file !== 'string' ? file.fileName : file;\n const mappedFile = params.virtualMap.get(fileId);\n return mappedFile\n ? mappedFile.getSourceSpan(span)\n : {\n fileName: fileId,\n start: typeof span !== 'number' ? span.start : span,\n length: typeof span !== 'number' ? span.length : 1,\n };\n },\n getSourcePosition(file, position) {\n const fileId = typeof file !== 'string' ? file.fileName : file;\n const mappedFile = params.virtualMap.get(fileId);\n if (mappedFile) {\n const span = mappedFile.getSourceSpan(position);\n if (span.fileName === mappedFile.sourceFileId)\n return spanToFilePosition(mappedFile.sourceFile, span);\n }\n return spanToFilePosition(\n typeof file === 'string' ? getProgram().getSourceFile(file)! : file,\n position\n );\n },\n };\n};\n\nconst buildProgram = (params: {\n program: ts.Program;\n virtualMap: VirtualMap;\n projectRoot: string;\n}): ts.Program => {\n const { program, virtualMap, projectRoot } = params;\n\n const isSourceFileFromExternalLibrary = maybeBind(\n program,\n program.isSourceFileFromExternalLibrary\n );\n const getModeForResolutionAtIndex = maybeBind(program, program.getModeForResolutionAtIndex);\n const getSourceFile = maybeBind(program, program.getSourceFile);\n const getSourceFiles = maybeBind(program, program.getSourceFiles);\n\n /** Remap source file to generated source file if it's a mapped file */\n const mapSourceFileFn =\n <TReturn, TArgs extends readonly any[]>(\n fileFn: (file: ts.SourceFile, ...args: TArgs) => TReturn\n ) =>\n (file: ts.SourceFile | undefined, ...args: TArgs): TReturn => {\n const mappedFile = file && virtualMap.get(file.fileName);\n if (mappedFile && mappedFile.sourceFileId === file?.fileName)\n file = getSourceFile(mappedFile.generatedFileId) || file;\n return fileFn.call(program, file!, ...args);\n };\n\n return Object.assign(program, {\n getSyntacticDiagnostics: mapSourceFileFn(program.getSyntacticDiagnostics),\n getSemanticDiagnostics: mapSourceFileFn(program.getSemanticDiagnostics),\n getDeclarationDiagnostics: mapSourceFileFn(program.getDeclarationDiagnostics),\n isSourceFileDefaultLibrary: mapSourceFileFn(program.isSourceFileDefaultLibrary),\n getModeForUsageLocation: mapSourceFileFn(program.getModeForUsageLocation),\n\n isSourceFileFromExternalLibrary(source) {\n const mappedFile = virtualMap.get(source.fileName);\n return (\n !!(mappedFile && mappedFile.sourceFileId === source.fileName) ||\n isSourceFileFromExternalLibrary(source)\n );\n },\n\n getSourceFiles() {\n const sourceFiles: ts.SourceFile[] = [];\n for (const sourceFile of getSourceFiles()) {\n const relativePath = path.relative(projectRoot, sourceFile.fileName);\n if (\n !relativePath.startsWith('..') &&\n !program.isSourceFileFromExternalLibrary(sourceFile)\n ) {\n sourceFiles.push(sourceFile);\n }\n }\n return sourceFiles;\n },\n\n getSourceFile(fileId) {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) fileId = mappedFile.generatedFileId;\n return getSourceFile(fileId);\n },\n\n getModeForResolutionAtIndex(file, index) {\n const mappedFile = virtualMap.get(file.fileName);\n if (mappedFile && mappedFile.sourceFileId === file.fileName) {\n file = getSourceFile(mappedFile.generatedFileId) || file;\n index = mappedFile.getGeneratedOffset(index)?.[0] ?? index;\n }\n return getModeForResolutionAtIndex(file, index);\n },\n } satisfies Partial<ts.Program>);\n};\n\nconst buildLanguageService = (params: {\n virtualMap: VirtualMap;\n languageServiceHost: ts.LanguageServiceHost;\n system: ts.System;\n rootNames: readonly string[];\n projectRoot: string;\n options: ts.CompilerOptions;\n documentRegistry?: ts.DocumentRegistry;\n}): ts.LanguageService => {\n const { virtualMap } = params;\n const languageService = ts.createLanguageService(\n params.languageServiceHost,\n params.documentRegistry\n );\n const getProgram = maybeBind(languageService, languageService.getProgram);\n\n /** Remap filename to generated file if it's a mapped file */\n const mapFileFn =\n <TReturn, TArgs extends readonly any[]>(fileFn: (fileId: string, ...args: TArgs) => TReturn) =>\n (fileId: string, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) fileId = mappedFile.generatedFileId;\n return fileFn.call(languageService, fileId, ...args);\n };\n\n /** Remap input to generated file and span if it's a mapped file */\n const mapFileTextSpanFn =\n <TReturn, TArgs extends readonly any[]>(\n textSpanFn: (fileId: string, span: ts.TextSpan, ...args: TArgs) => TReturn\n ) =>\n (fileId: string, span: ts.TextSpan, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) {\n fileId = mappedFile.generatedFileId;\n const start = mappedFile.getGeneratedOffset(span.start)?.[0];\n const end = mappedFile.getGeneratedOffset(span.start + span.length - 1)?.[0];\n if (start != null) {\n span = { start, length: span.length };\n if (end != null) span.length = end - start + 1;\n }\n }\n return textSpanFn.call(languageService, fileId, span, ...args);\n };\n\n /** Remap input to generated file and range if it's a mapped file */\n const mapFileTextRangeFn =\n <TReturn, TArgs extends readonly any[]>(\n textSpanFn: (fileId: string, range: ts.TextRange, ...args: TArgs) => TReturn\n ) =>\n (fileId: string, range: ts.TextRange, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) {\n fileId = mappedFile.generatedFileId;\n const pos = mappedFile.getGeneratedOffset(range.pos)?.[0];\n const end = mappedFile.getGeneratedOffset(range.end)?.[0];\n if (pos != null) {\n range = { pos, end: pos + (range.end - range.pos) };\n if (end != null) range.end = end;\n }\n }\n return textSpanFn.call(languageService, fileId, range, ...args);\n };\n\n /** Remap input to generated file and position if it's a mapped file */\n const mapFilePositionFn =\n <TReturn, TArgs extends readonly any[]>(\n positionFn: (fileId: string, position: number, ...args: TArgs) => TReturn\n ) =>\n (fileId: string, position: number, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) {\n fileId = mappedFile.generatedFileId;\n position = mappedFile.getGeneratedOffset(position)?.[0] ?? position;\n }\n return positionFn.call(languageService, fileId, position, ...args);\n };\n\n /** Remap input to generated file and position if it's a mapped file */\n const mapFileStartEndFn =\n <TReturn, TArgs extends readonly any[]>(\n positionFn: (fileId: string, start: number, end: number, ...args: TArgs) => TReturn\n ) =>\n (fileId: string, start: number, end: number, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) {\n fileId = mappedFile.generatedFileId;\n start = mappedFile.getGeneratedOffset(start)?.[0] ?? start;\n end = mappedFile.getGeneratedOffset(end)?.[0] ?? end;\n }\n return positionFn.call(languageService, fileId, start, end, ...args);\n };\n\n let program: ts.Program | undefined;\n\n return Object.assign(languageService, {\n getProgram() {\n if (program) {\n return program;\n } else {\n const serviceProgram = getProgram();\n return serviceProgram\n ? (program = buildProgram({\n program: serviceProgram,\n virtualMap: params.virtualMap,\n projectRoot: params.projectRoot,\n }))\n : undefined;\n }\n },\n\n getReferencesAtPosition: mapFilePositionFn(languageService.getReferencesAtPosition),\n findReferences: mapFilePositionFn(languageService.findReferences),\n getDefinitionAtPosition: mapFilePositionFn(languageService.getDefinitionAtPosition),\n getDefinitionAndBoundSpan: mapFilePositionFn(languageService.getDefinitionAndBoundSpan),\n getTypeDefinitionAtPosition: mapFilePositionFn(languageService.getTypeDefinitionAtPosition),\n getImplementationAtPosition: mapFilePositionFn(languageService.getImplementationAtPosition),\n getCompletionsAtPosition: mapFilePositionFn(languageService.getCompletionsAtPosition),\n getCompletionEntryDetails: mapFilePositionFn(languageService.getCompletionEntryDetails),\n getCompletionEntrySymbol: mapFilePositionFn(languageService.getCompletionEntrySymbol),\n getQuickInfoAtPosition: mapFilePositionFn(languageService.getQuickInfoAtPosition),\n getBreakpointStatementAtPosition: mapFilePositionFn(\n languageService.getBreakpointStatementAtPosition\n ),\n getSignatureHelpItems: mapFilePositionFn(languageService.getSignatureHelpItems),\n getRenameInfo: mapFilePositionFn(languageService.getRenameInfo),\n getSmartSelectionRange: mapFilePositionFn(languageService.getSmartSelectionRange),\n getDocumentHighlights: mapFilePositionFn(languageService.getDocumentHighlights),\n prepareCallHierarchy: mapFilePositionFn(languageService.prepareCallHierarchy),\n provideCallHierarchyIncomingCalls: mapFilePositionFn(\n languageService.provideCallHierarchyIncomingCalls\n ),\n provideCallHierarchyOutgoingCalls: mapFilePositionFn(\n languageService.provideCallHierarchyOutgoingCalls\n ),\n getBraceMatchingAtPosition: mapFilePositionFn(languageService.getBraceMatchingAtPosition),\n getIndentationAtPosition: mapFilePositionFn(languageService.getIndentationAtPosition),\n getFormattingEditsAfterKeystroke: mapFilePositionFn(\n languageService.getFormattingEditsAfterKeystroke\n ),\n getDocCommentTemplateAtPosition: mapFilePositionFn(\n languageService.getDocCommentTemplateAtPosition\n ),\n isValidBraceCompletionAtPosition: mapFilePositionFn(\n languageService.isValidBraceCompletionAtPosition\n ),\n getJsxClosingTagAtPosition: mapFilePositionFn(languageService.getJsxClosingTagAtPosition),\n getLinkedEditingRangeAtPosition: mapFilePositionFn(\n languageService.getLinkedEditingRangeAtPosition\n ),\n getSpanOfEnclosingComment: mapFilePositionFn(languageService.getSpanOfEnclosingComment),\n\n getSyntacticClassifications: mapFileTextSpanFn(\n languageService.getSyntacticClassifications\n ) as typeof languageService.getSyntacticClassifications,\n getSemanticClassifications: mapFileTextSpanFn(\n languageService.getSemanticClassifications\n ) as typeof languageService.getSemanticClassifications,\n getEncodedSyntacticClassifications: mapFileTextSpanFn(\n languageService.getEncodedSyntacticClassifications\n ),\n getEncodedSemanticClassifications: mapFileTextSpanFn(\n languageService.getEncodedSemanticClassifications\n ),\n provideInlayHints: mapFileTextSpanFn(languageService.provideInlayHints),\n\n getNameOrDottedNameSpan: mapFileStartEndFn(languageService.getNameOrDottedNameSpan),\n getFormattingEditsForRange: mapFileStartEndFn(languageService.getFormattingEditsForRange),\n getCodeFixesAtPosition: mapFileStartEndFn(languageService.getCodeFixesAtPosition),\n\n getFileReferences: mapFileFn(languageService.getFileReferences),\n getNavigationBarItems: mapFileFn(languageService.getNavigationBarItems),\n getNavigationTree: mapFileFn(languageService.getNavigationTree),\n getOutliningSpans: mapFileFn(languageService.getOutliningSpans),\n getTodoComments: mapFileFn(languageService.getTodoComments),\n getFormattingEditsForDocument: mapFileFn(languageService.getFormattingEditsForDocument),\n getEditsForRefactor: mapFileFn(languageService.getEditsForRefactor),\n getEmitOutput: mapFileFn(languageService.getEmitOutput),\n getSuggestionDiagnostics: mapFileFn(languageService.getSuggestionDiagnostics),\n getSemanticDiagnostics: mapFileFn(languageService.getSemanticDiagnostics),\n getSyntacticDiagnostics: mapFileFn(languageService.getSyntacticDiagnostics),\n getSupportedCodeFixes: mapFileFn(languageService.getSupportedCodeFixes),\n\n toggleLineComment: mapFileTextRangeFn(languageService.toggleLineComment),\n toggleMultilineComment: mapFileTextRangeFn(languageService.toggleMultilineComment),\n commentSelection: mapFileTextRangeFn(languageService.commentSelection),\n uncommentSelection: mapFileTextRangeFn(languageService.uncommentSelection),\n } satisfies Partial<ts.LanguageService>);\n};\n\nconst buildPluginInfo = <Config extends {}>(params: {\n config: Config;\n projectRoot: string;\n getLanguageService(): ts.LanguageService;\n getLanguageServiceHost(): ts.LanguageServiceHost;\n system: ts.System;\n rootNames: readonly string[];\n options: ts.CompilerOptions;\n}): PluginCreateInfo<Config> => {\n let languageServiceHost: ts.LanguageServiceHost | undefined;\n return {\n config: params.config,\n\n get languageService() {\n return params.getLanguageService();\n },\n\n get languageServiceHost() {\n return (\n languageServiceHost ||\n (languageServiceHost = createVirtualLanguageServiceHost(\n params.system,\n [...params.rootNames],\n params.options,\n ts\n ).languageServiceHost)\n );\n },\n\n // NOTE: this is an inexact and incomplete implementation\n project: {\n getProjectName: () => params.projectRoot,\n projectService: { logger: console } as any,\n } as PluginCreateInfo['project'],\n\n // NOTE: this is an inexact and incomplete implementation\n serverHost: {\n ...params.system,\n setImmediate,\n clearImmediate,\n } as PluginCreateInfo['serverHost'],\n };\n};\n","import type ts from 'typescript';\nimport * as path from 'node:path';\n\nimport { TadaError, TadaErrorCode } from '../utils/error';\n\nlet _svelte: typeof import('@gql.tada/svelte-support');\nlet _vue: typeof import('@gql.tada/vue-support');\n\nconst transformSvelte = async (\n ...args: Parameters<typeof _svelte.transform>\n): Promise<ReturnType<typeof _svelte.transform>> => {\n if (!_svelte) {\n try {\n _svelte = await import('@gql.tada/svelte-support');\n } catch (_error) {\n throw new TadaError(\n TadaErrorCode.SVELTE_SUPPORT,\n 'For Svelte support the `@gql.tada/svelte-support` package must be installed.\\n' +\n 'Install the package and try again.'\n );\n }\n }\n return _svelte.transform(...args);\n};\n\nconst transformVue = async (\n ...args: Parameters<typeof _vue.transform>\n): Promise<ReturnType<typeof _vue.transform>> => {\n if (!_vue) {\n try {\n _vue = await import('@gql.tada/vue-support');\n } catch (_error) {\n throw new TadaError(\n TadaErrorCode.VUE_SUPPORT,\n 'For Vue support the `@gql.tada/vue-support` package must be installed.\\n' +\n 'Install the package and try again.'\n );\n }\n }\n return _vue.transform(...args);\n};\n\nconst checkVue = async (): Promise<void> => {\n if (!_vue) {\n try {\n _vue = await import('@gql.tada/vue-support');\n } catch (_error) {\n throw new TadaError(\n TadaErrorCode.VUE_SUPPORT,\n 'For Vue support the `@gql.tada/vue-support` package must be installed.\\n' +\n 'Install the package and try again.'\n );\n }\n }\n return _vue.check();\n};\n\nexport const transformExtensions = ['.svelte', '.vue'] as const;\n\nexport const transform = async (sourceFile: ts.SourceFile) => {\n const extname = path.extname(sourceFile.fileName);\n if (extname === '.svelte') {\n return transformSvelte(sourceFile);\n } else if (extname === '.vue') {\n await checkVue();\n return transformVue(sourceFile);\n } else {\n throw new TadaError(\n TadaErrorCode.UNKNOWN_EXTERNAL_FILE,\n `Tried transforming unknown file type \"${extname}\". Supported: ${transformExtensions.join(\n ', '\n )}`\n );\n }\n};\n","import ts from 'typescript';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { init } from '@0no-co/graphqlsp/api';\n\nimport { createFSBackedSystem, createVirtualCompilerHost } from './vendor/typescript-vfs';\n\nimport type { VirtualMap, Mapping } from './mapping';\nimport type { ProgramContainer } from './container';\nimport { SourceMappedFile } from './mapping';\nimport { buildContainer } from './container';\nimport { transform, transformExtensions } from './transformers';\n\nexport type VirtualExtension = (typeof transformExtensions)[number];\n\nexport interface ProgramFactoryParams {\n rootPath: string;\n tsconfigPath?: string;\n configPath: string;\n}\n\nexport interface SourceFileParams {\n fileId: string;\n sourceText: string | ts.IScriptSnapshot;\n scriptKind?: ts.ScriptKind;\n}\n\nexport interface MappedFileParams {\n fileId: string;\n mappings: readonly Mapping[];\n}\n\nexport interface ProgramFactory {\n readonly projectPath: string;\n readonly wasOriginallyNodeNext: boolean;\n readonly projectDirectories: readonly string[];\n readonly rootFileNames: readonly string[];\n\n createSourceFile(params: SourceFileParams, scriptKind?: ts.ScriptKind): ts.SourceFile;\n createExternalFiles(exts?: readonly VirtualExtension[]): readonly ts.SourceFile[];\n\n addSourceFile(file: SourceFileParams | ts.SourceFile): this;\n addMappedFile(file: SourceFileParams | ts.SourceFile, params: MappedFileParams): this;\n\n addVirtualFiles(files: readonly ts.SourceFile[]): Promise<this>;\n\n resolveModulePath(importSpecifier: string, fromPath: string): string | undefined;\n resolveModuleName(importSpecifier: string, fromPath: string, toPath: string): string;\n\n build(): ProgramContainer;\n}\n\n/** Bumps the Error stack traces to a length of 25 for better debugging. */\nconst bumpStackTraceLimit = () => {\n if ('stackTraceLimit' in Error && Error.stackTraceLimit < 25) {\n Error.stackTraceLimit = 25;\n }\n};\n\nexport const programFactory = (params: ProgramFactoryParams): ProgramFactory => {\n const vfsMap = new Map<string, string>();\n const virtualMap: VirtualMap = new Map();\n\n const system = createFSBackedSystem(vfsMap, params.rootPath, ts, resolveDefaultLibsPath(params));\n const config = resolveConfig(params);\n\n const rootNames = new Set(config.fileNames);\n const options: ts.CompilerOptions = {\n ...ts.getDefaultCompilerOptions(),\n getDefaultLibFilePath: ts.getDefaultLibFilePath(config.options),\n noCheck: true,\n ...config.options,\n };\n\n let orignallyNodeNext = false;\n // NOTE: Using \"NodeNext\" instead of \"Bundler\" is almost always a mistake\n // this should be revisited in the next major version.\n if (\n 'Bundler' in ts.ModuleResolutionKind &&\n (options.moduleResolution === ts.ModuleResolutionKind.NodeNext ||\n options.moduleResolution === ts.ModuleResolutionKind.Node16)\n ) {\n orignallyNodeNext = true;\n options.moduleResolution = ts.ModuleResolutionKind.Bundler;\n }\n\n const host = createVirtualCompilerHost(system, options, ts);\n const documentRegistry = ts.createDocumentRegistry();\n\n const factory: ProgramFactory = {\n get projectPath() {\n return params.rootPath;\n },\n\n get wasOriginallyNodeNext() {\n return orignallyNodeNext;\n },\n\n get projectDirectories() {\n const directories = new Set([params.rootPath]);\n for (const rootName of rootNames) directories.add(path.dirname(rootName));\n return [...directories];\n },\n\n get rootFileNames() {\n return [...rootNames];\n },\n\n createSourceFile(params, scriptKind) {\n return ts.createSourceFile(\n params.fileId,\n typeof params.sourceText === 'object'\n ? params.sourceText.getText(0, params.sourceText.getLength())\n : params.sourceText,\n options.target || ts.ScriptTarget.ESNext,\n /*setParentNodes*/ true,\n scriptKind || (params.scriptKind != null ? params.scriptKind : ts.ScriptKind.TSX)\n );\n },\n\n createExternalFiles(exts: readonly VirtualExtension[] = transformExtensions) {\n const files: ts.SourceFile[] = [];\n const seen = new Set(rootNames);\n const directories = new Set([params.rootPath]);\n for (const rootName of rootNames) directories.add(path.dirname(rootName));\n for (const directory of directories) {\n for (const fileId of system.readDirectory(directory, exts, ['**/node_modules'])) {\n if (!seen.has(fileId)) {\n seen.add(fileId);\n const contents = system.readFile(fileId, 'utf8');\n if (contents) {\n files.push(\n factory.createSourceFile(\n {\n fileId,\n sourceText: contents,\n },\n ts.ScriptKind.External\n )\n );\n }\n }\n }\n }\n return files;\n },\n\n addSourceFile(input) {\n const sourceFile =\n 'fileName' in input ? input : factory.createSourceFile(input, ts.ScriptKind.TSX);\n host.updateFile(sourceFile);\n rootNames.add(sourceFile.fileName);\n return factory;\n },\n\n addMappedFile(input, params) {\n const sourceFile =\n 'fileName' in input ? input : factory.createSourceFile(input, ts.ScriptKind.External);\n if (params.mappings.length) rootNames.delete(sourceFile.fileName);\n const sourceMappedFile = new SourceMappedFile(params.mappings, {\n sourceFile,\n sourceFileId: sourceFile.fileName,\n generatedFileId: params.fileId,\n });\n virtualMap.set(sourceMappedFile.sourceFileId, sourceMappedFile);\n virtualMap.set(sourceMappedFile.generatedFileId, sourceMappedFile);\n return factory;\n },\n\n async addVirtualFiles(sourceFiles) {\n for (const sourceFile of sourceFiles) {\n const virtualFileId = `${sourceFile.fileName}.ts`;\n const virtualCode = await transform(sourceFile);\n if (virtualCode) {\n factory\n .addSourceFile({\n fileId: virtualFileId,\n sourceText: virtualCode.snapshot,\n })\n .addMappedFile(sourceFile, {\n mappings: virtualCode.mappings,\n fileId: virtualFileId,\n });\n }\n }\n return factory;\n },\n\n resolveModulePath(importSpecifier: string, fromPath: string): string | undefined {\n const resolved = ts.resolveModuleName(importSpecifier, fromPath, options, host.compilerHost);\n\n return resolved.resolvedModule?.resolvedFileName;\n },\n\n resolveModuleName(importSpecifier: string, fromPath: string, toPath: string): string {\n // For absolute imports (including path-mapped ones), keep them as-is\n // TypeScript's module resolution will handle them correctly\n if (!importSpecifier.startsWith('.')) {\n return importSpecifier;\n }\n\n // For relative imports, we need to adjust the path using the virtual compiler host\n // First, resolve the import from the original location to get the actual file\n const resolvedFileName = factory.resolveModulePath(importSpecifier, fromPath);\n\n if (resolvedFileName) {\n // Now create a relative path from the new location (toPath) to the target\n const fromDir = path.dirname(toPath);\n let relativePath = path.relative(fromDir, resolvedFileName);\n\n // Ensure it starts with ./ or ../\n if (!relativePath.startsWith('.')) {\n relativePath = './' + relativePath;\n }\n\n // Convert Windows backslashes to forward slashes for imports\n return relativePath.replace(/\\\\/g, '/');\n }\n\n // Fallback to simple path resolution if TypeScript resolution fails\n const fromDir = path.dirname(fromPath);\n const toDir = path.dirname(toPath);\n\n const absoluteImportPath = path.resolve(fromDir, importSpecifier);\n let relativeImportPath = path.relative(toDir, absoluteImportPath);\n\n // Ensure it starts with ./ if it's a relative path\n if (!relativeImportPath.startsWith('.')) {\n relativeImportPath = './' + relativeImportPath;\n }\n\n // Convert Windows backslashes to forward slashes for imports\n return relativeImportPath.replace(/\\\\/g, '/');\n },\n\n build() {\n bumpStackTraceLimit();\n\n // NOTE: This is necessary for `@0no-co/graphqlsp/api` to use the right instance\n // of the typescript library\n init({ typescript: ts });\n\n return buildContainer({\n virtualMap,\n projectRoot: params.rootPath,\n compilerHost: host.compilerHost,\n rootNames: [...rootNames],\n options,\n system,\n documentRegistry,\n });\n },\n };\n\n return factory;\n};\n\nconst resolveDefaultLibsPath = (params: ProgramFactoryParams): string => {\n const target = ts.getDefaultLibFilePath({});\n if (!ts.sys.fileExists(target)) {\n const require = createRequire(params.configPath);\n const request = 'typescript/package.json';\n try {\n return path.dirname(\n require.resolve(request, {\n paths: [\n path.join(path.dirname(params.configPath), 'node_modules'),\n path.join(params.rootPath, 'node_modules'),\n ...(require.resolve.paths(request) || []),\n ],\n })\n );\n } catch (_error) {\n return path.resolve(params.rootPath, 'node_modules', 'typescript', 'lib');\n }\n } else {\n return path.dirname(target);\n }\n};\n\nconst resolveConfig = (params: ProgramFactoryParams): ts.ParsedCommandLine => {\n const configPath = params.tsconfigPath || params.configPath;\n const text = ts.sys.readFile(configPath, 'utf8') || '{}';\n const parseResult = ts.parseConfigFileTextToJson(configPath, text);\n if (parseResult.error != null) throw new Error(parseResult.error.messageText.toString());\n const projectRoot = path.dirname(configPath);\n return ts.parseJsonConfigFileContent(\n parseResult.config,\n ts.sys,\n projectRoot,\n ts.getDefaultCompilerOptions(),\n configPath\n );\n};\n","import * as fs from 'node:fs/promises';\n\nexport const enum FileType {\n File,\n Directory,\n}\n\nexport const stat = async (file: string, type = FileType.File): Promise<boolean> =>\n await fs\n .stat(file)\n .then((stat) => {\n switch (type) {\n case FileType.File:\n return stat.isFile();\n case FileType.Directory:\n return stat.isDirectory();\n }\n })\n .catch(() => false);\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport { stat, FileType } from './fs';\nimport { findWorkspaceRoot } from './workspaceRoot';\n\nconst configFileRe = /^(?:graphql\\.config|\\.graphqlrc)\\.(?:cjs|[jt]s|json|toml|ya?ml)$/i;\n\n/** Loads list of suggested in-repo VSCode extensions */\nexport const findGraphQLConfig = async (targetPath?: string): Promise<string | null> => {\n let target = targetPath || process.cwd();\n const rootPath = path.resolve(target, '/');\n while (target !== rootPath) {\n let dir: readonly string[] = [];\n try {\n dir = await fs.readdir(target);\n } catch (_error) {}\n const configFile = dir.find((item) => configFileRe.test(item));\n if (configFile) return configFile;\n if (await stat(path.resolve(target, '.git'), FileType.Directory)) {\n break;\n } else if (await stat(path.resolve(target, '.vscode'), FileType.Directory)) {\n break;\n }\n target = path.resolve(target, '..');\n }\n\n const workspaceRoot = await findWorkspaceRoot(targetPath);\n if (workspaceRoot) {\n const packageJsonPath = path.resolve(workspaceRoot, 'package.json');\n if (await stat(packageJsonPath)) {\n try {\n const meta = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));\n if (\n meta &&\n typeof meta === 'object' &&\n 'graphql' in meta &&\n meta.graphql &&\n typeof meta.graphql === 'object'\n ) {\n return packageJsonPath;\n }\n } catch (_error) {}\n }\n }\n\n return null;\n};\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { stat, FileType } from './fs';\n\nexport const findWorkspaceRoot = async (targetPath?: string): Promise<string | null> => {\n let target = targetPath || process.cwd();\n const rootPath = path.resolve(target, '/');\n while (target !== rootPath) {\n if (await stat(path.resolve(target, '.git'), FileType.Directory)) {\n return target;\n } else if (await stat(path.resolve(target, '.vscode'), FileType.Directory)) {\n return target;\n } else if (await stat(path.resolve(target, 'pnpm-workspace.yml'))) {\n return target;\n }\n const packageJsonPath = path.resolve(target, 'package.json');\n if (await stat(packageJsonPath)) {\n try {\n const meta = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));\n if (meta && typeof meta === 'object' && Array.isArray(meta.workspaces)) {\n return target;\n }\n } catch (_error) {}\n }\n target = path.resolve(target, '..');\n }\n return null;\n};\n","/**\n * Version resolution utilities with support for workspace catalogs.\n *\n * Supports catalog-based dependency management for:\n * - pnpm (pnpm-workspace.yaml format)\n * - bun (package.json workspaces format)\n *\n * Catalog references follow the format:\n * - \"catalog:\" for default catalog\n * - \"catalog:name\" for named catalogs\n */\n\nimport { createRequire } from 'node:module';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nexport interface PackageJson {\n name?: string;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n}\n\nexport interface WorkspaceConfig {\n packages?: string[];\n catalog?: Record<string, string>;\n catalogs?: Record<string, Record<string, string>>;\n}\n\nexport interface PnpmWorkspaceConfig extends WorkspaceConfig {\n // Inherits from WorkspaceConfig - supports pnpm-workspace.yaml format\n}\n\nexport interface BunWorkspaceConfig extends WorkspaceConfig {\n // Inherits from WorkspaceConfig - supports package.json workspaces format\n}\n\nconst parseYaml = (content: string): PnpmWorkspaceConfig => {\n const lines = content.split('\\n');\n const result: PnpmWorkspaceConfig = {};\n let currentSection: string | null = null;\n let currentCatalog: string | null = null;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n if (trimmed.endsWith(':') && !trimmed.includes(' ')) {\n const key = trimmed.slice(0, -1).replace(/['\"]/g, '');\n if (key === 'packages') {\n currentSection = 'packages';\n result.packages = [];\n } else if (key === 'catalog') {\n currentSection = 'catalog';\n result.catalog = {};\n } else if (key === 'catalogs') {\n currentSection = 'catalogs';\n result.catalogs = {};\n } else if (currentSection === 'catalogs') {\n currentCatalog = key;\n result.catalogs![key] = {};\n }\n } else if (trimmed.startsWith('- ')) {\n if (currentSection === 'packages') {\n result.packages!.push(trimmed.slice(2).replace(/['\"]/g, ''));\n }\n } else if (trimmed.includes(':')) {\n const colonIndex = trimmed.indexOf(':');\n const key = trimmed.slice(0, colonIndex).trim().replace(/['\"]/g, '');\n const value = trimmed\n .slice(colonIndex + 1)\n .trim()\n .replace(/['\"]/g, '');\n\n if (currentSection === 'catalog') {\n result.catalog![key] = value;\n } else if (currentSection === 'catalogs' && currentCatalog) {\n result.catalogs![currentCatalog][key] = value;\n }\n }\n }\n\n return result;\n};\n\nconst findPnpmWorkspaceroot = async (startPath: string = process.cwd()): Promise<string | null> => {\n let currentPath = startPath;\n const root = path.parse(currentPath).root;\n\n while (currentPath !== root) {\n const workspaceFile = path.join(currentPath, 'pnpm-workspace.yaml');\n try {\n await fs.access(workspaceFile);\n return currentPath;\n } catch {\n // File doesn't exist, continue searching\n }\n currentPath = path.dirname(currentPath);\n }\n\n return null;\n};\n\nconst findBunWorkspaceRoot = async (startPath: string = process.cwd()): Promise<string | null> => {\n let currentPath = startPath;\n const root = path.parse(currentPath).root;\n\n while (currentPath !== root) {\n const packageJsonFile = path.join(currentPath, 'package.json');\n try {\n await fs.access(packageJsonFile);\n const content = await fs.readFile(packageJsonFile, 'utf-8');\n const packageJson: PackageJson & { workspaces?: any } = JSON.parse(content);\n\n // Check if this package.json has workspaces with catalog/catalogs\n // Bun stores catalogs in workspaces.catalog and workspaces.catalogs\n if (\n packageJson.workspaces &&\n (packageJson.workspaces.catalog || packageJson.workspaces.catalogs)\n ) {\n return currentPath;\n }\n } catch {\n // File doesn't exist or can't be parsed, continue searching\n }\n currentPath = path.dirname(currentPath);\n }\n\n return null;\n};\n\nconst loadPnpmWorkspaceCatalogs = async (): Promise<PnpmWorkspaceConfig | null> => {\n const workspaceRoot = await findPnpmWorkspaceroot();\n if (!workspaceRoot) return null;\n\n try {\n const workspaceFile = path.join(workspaceRoot, 'pnpm-workspace.yaml');\n const content = await fs.readFile(workspaceFile, 'utf-8');\n return parseYaml(content);\n } catch {\n return null;\n }\n};\n\nconst loadBunWorkspaceCatalogs = async (): Promise<BunWorkspaceConfig | null> => {\n const workspaceRoot = await findBunWorkspaceRoot();\n if (!workspaceRoot) return null;\n\n try {\n const packageJsonFile = path.join(workspaceRoot, 'package.json');\n const content = await fs.readFile(packageJsonFile, 'utf-8');\n const packageJson: PackageJson & { workspaces?: any } = JSON.parse(content);\n\n if (!packageJson.workspaces) return null;\n\n const result: BunWorkspaceConfig = {};\n\n if (packageJson.workspaces.packages) {\n result.packages = packageJson.workspaces.packages;\n }\n\n if (packageJson.workspaces.catalog) {\n result.catalog = packageJson.workspaces.catalog;\n }\n\n if (packageJson.workspaces.catalogs) {\n result.catalogs = packageJson.workspaces.catalogs;\n }\n\n return result;\n } catch {\n return null;\n }\n};\n\nconst loadWorkspaceCatalogs = async (): Promise<WorkspaceConfig | null> => {\n const pnpmCatalogs = await loadPnpmWorkspaceCatalogs();\n if (pnpmCatalogs) return pnpmCatalogs;\n\n const bunCatalogs = await loadBunWorkspaceCatalogs();\n if (bunCatalogs) return bunCatalogs;\n\n return null;\n};\n\nconst resolveCatalogVersion = (catalogRef: string): string | null => {\n if (!catalogRef.startsWith('catalog:')) return null;\n\n const catalogName = catalogRef.slice(8); // Remove 'catalog:' prefix\n\n if (!catalogName || catalogName === 'default') {\n return null; // Will be resolved by package name lookup\n }\n\n return catalogName;\n};\n\nconst getVersionFromCatalog = (\n packageName: string,\n catalogName: string | null,\n catalogs: WorkspaceConfig\n): string | null => {\n if (catalogName) {\n // Named catalog\n return catalogs.catalogs?.[catalogName]?.[packageName] || null;\n } else {\n // Default catalog\n return catalogs.catalog?.[packageName] || null;\n }\n};\n\nconst getPackageVersion = async (\n packageName: string,\n meta: PackageJson\n): Promise<string | null> => {\n const devVersion = meta.devDependencies?.[packageName];\n if (devVersion) {\n if (devVersion.startsWith('catalog:')) {\n const catalogs = await loadWorkspaceCatalogs();\n if (catalogs) {\n const catalogName = resolveCatalogVersion(devVersion);\n const resolvedVersion = getVersionFromCatalog(packageName, catalogName, catalogs);\n if (resolvedVersion) return resolvedVersion;\n }\n } else {\n return devVersion;\n }\n }\n\n const depVersion = meta.dependencies?.[packageName];\n if (depVersion) {\n if (depVersion.startsWith('catalog:')) {\n const catalogs = await loadWorkspaceCatalogs();\n if (catalogs) {\n const catalogName = resolveCatalogVersion(depVersion);\n const resolvedVersion = getVersionFromCatalog(packageName, catalogName, catalogs);\n if (resolvedVersion) return resolvedVersion;\n }\n } else {\n return depVersion;\n }\n }\n\n return null;\n};\n\nexport const readPackageJson = async (): Promise<PackageJson> => {\n const packageJsonPath = path.resolve(process.cwd(), 'package.json');\n const file = path.resolve(packageJsonPath);\n return JSON.parse(await fs.readFile(file, 'utf-8'));\n};\n\nexport const getTypeScriptVersion = async (meta: PackageJson): Promise<string | null> => {\n const pkg = 'typescript';\n\n // Try to get version with catalog support\n const catalogVersion = await getPackageVersion(pkg, meta);\n if (catalogVersion) return catalogVersion;\n\n // Fallback to direct resolution\n try {\n return (await import(pkg)).version || null;\n } catch (_error) {\n return null;\n }\n};\n\nexport const getGraphQLSPVersion = async (meta: PackageJson): Promise<string | null> => {\n const pkg = '@0no-co/graphqlsp';\n\n // Try to get version with catalog support\n const catalogVersion = await getPackageVersion(pkg, meta);\n if (catalogVersion) return catalogVersion;\n\n // Fallback to direct resolution\n try {\n // NOTE: Resolved from current folder, since it's a child dependency\n return createRequire(__dirname)(`${pkg}/package.json`)?.version || null;\n } catch (_error) {\n return null;\n }\n};\n\nexport const getGqlTadaVersion = async (meta: PackageJson): Promise<string | null> => {\n const pkg = 'gql.tada';\n\n // Try to get version with catalog support\n const catalogVersion = await getPackageVersion(pkg, meta);\n if (catalogVersion) return catalogVersion;\n\n // Fallback to direct resolution\n try {\n // NOTE: Resolved from working directory, since it's a parent dependency\n return createRequire(process.cwd())(`${pkg}/package.json`)?.version || null;\n } catch (_error) {\n return null;\n }\n};\n\nconst hasPackageSupport = async (packageName: string, meta: PackageJson): Promise<boolean> => {\n // Check if package is listed in dependencies with catalog support\n const catalogVersion = await getPackageVersion(packageName, meta);\n if (catalogVersion) return true;\n\n // Fallback to direct resolution\n try {\n // NOTE: Resolved from current folder, since it's a child dependency\n return !!createRequire(__dirname)(`${packageName}/package.json`)?.version;\n } catch (_error) {\n return false;\n }\n};\n\nexport const hasSvelteSupport = async (meta: PackageJson): Promise<boolean> => {\n return hasPackageSupport('@gql.tada/svelte-support', meta);\n};\n\nexport const hasVueSupport = async (meta: PackageJson): Promise<boolean> => {\n return hasPackageSupport('@gql.tada/vue-support', meta);\n};\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport ts from 'typescript';\nimport { stat, FileType } from './fs';\n\nconst jsonParse = async (fileName: string): Promise<unknown> => {\n const contents = await fs.readFile(fileName, 'utf8');\n const sourceFile = ts.parseJsonText(fileName, contents);\n return ts.convertToObject(sourceFile, []);\n};\n\nexport const isVSCodeInstalled = async (): Promise<boolean> => {\n if (!process.env.HOME) return false;\n const vscodeFolder = path.resolve(process.env.HOME, '.vscode');\n return !!(await stat(vscodeFolder, FileType.Directory));\n};\n\n/** Loads list of suggested in-repo VSCode extensions */\nexport const loadSuggestedExtensionsList = async (\n targetPath?: string\n): Promise<readonly string[]> => {\n let target = targetPath || process.cwd();\n const rootPath = path.resolve(target, '/');\n while (target !== rootPath) {\n if (await stat(path.resolve(target, '.git'), FileType.Directory)) {\n break;\n } else if (await stat(path.resolve(target, '.vscode'), FileType.Directory)) {\n break;\n }\n target = path.resolve(target, '..');\n }\n const configFile = path.resolve(target, '.vscode', 'extensions.json');\n if (!(await stat(configFile))) return [];\n let json: unknown;\n try {\n json = await jsonParse(configFile);\n } catch (_error) {\n return [];\n }\n if (json && typeof json === 'object' && 'recommendations' in json) {\n return Array.isArray(json.recommendations)\n ? json.recommendations\n .filter((x): x is string => x && typeof x === 'string')\n .map((x) => `${x}`.toLowerCase())\n : [];\n } else {\n return [];\n }\n};\n\n/** Loads list of installed VSCode extensions */\nexport const loadExtensionsList = async (): Promise<readonly string[]> => {\n if (!process.env.HOME) return [];\n const vscodeFolder = path.resolve(process.env.HOME, '.vscode');\n const configFile = path.resolve(vscodeFolder, 'extensions', 'extensions.json');\n if (!(await stat(configFile))) return [];\n let json: unknown;\n try {\n json = await jsonParse(configFile);\n } catch (_error) {\n return [];\n }\n return (Array.isArray(json) ? json : [])\n .map((entry) => {\n if (!entry || typeof entry !== 'object' || !('identifier' in entry)) return null;\n if (!entry.identifier || typeof entry.identifier !== 'object' || !('id' in entry.identifier))\n return null;\n return entry.identifier.id && typeof entry.identifier.id === 'string'\n ? `${entry.identifier.id}`.toLowerCase()\n : null;\n })\n .filter((x): x is string => !!x);\n};\n","import { pipe, interval, map, concat, fromValue } from 'wonka';\n\nimport * as t from '../../term';\nimport { indent } from '../shared/logger';\n\nexport * from '../shared/logger';\n\nexport function console(error: any) {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n error && error instanceof Error ? error.message : `${error}`,\n ]);\n}\n\nexport function emptyLine() {\n return t.text([t.cmd(t.CSI.Style, t.Style.BrightBlack), t.HeavyBox.Vertical, '\\n']);\n}\n\nexport function title(title: string, description?: string) {\n let out = t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n t.HeavyBox.TopLeft,\n ' ',\n t.cmd(t.CSI.Style, [t.Style.Magenta, t.Style.Invert]),\n ` ${title.trim()} `,\n t.cmd(t.CSI.Style, [t.Style.NoInvert]),\n '\\n',\n ]);\n if (description) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n t.HeavyBox.Vertical,\n ` ${description}\\n`,\n ]);\n }\n return out;\n}\n\nexport function completedTask(description: string, isLast = false) {\n return t.text([\n emptyLine(),\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n isLast ? t.HeavyBox.BottomLeft : t.HeavyBox.VerticalRight,\n ' ',\n t.cmd(t.CSI.Style, t.Style.Green),\n t.Icons.TickSwoosh,\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n description,\n '\\n',\n ]);\n}\n\nexport function failedTask(description: string) {\n return t.text([\n emptyLine(),\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n t.HeavyBox.BottomLeft,\n ' ',\n t.cmd(t.CSI.Style, t.Style.BrightRed),\n t.Icons.CrossSwoosh,\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n description,\n '\\n',\n ]);\n}\n\nexport function warningTask(description: string) {\n return t.text([\n emptyLine(),\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n t.HeavyBox.VerticalRight,\n ' ',\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n description,\n '\\n',\n ]);\n}\n\nexport function hintMessage(text: string) {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.VerticalRight} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${t.Icons.Info} `,\n t.cmd(t.CSI.Style, t.Style.Blue),\n indent(\n text,\n t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.Vertical} `,\n t.cmd(t.CSI.Style, t.Style.Blue),\n ])\n ),\n ]);\n}\n\nexport function runningTask(description: string) {\n const frame = (state: number) =>\n t.text([\n emptyLine(),\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.circleSpinner[state % t.circleSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n description.trim(),\n ]);\n return concat([\n fromValue(frame(0)),\n pipe(\n interval(150),\n map((state) => frame(state + 1))\n ),\n ]);\n}\n\nexport function success() {\n return t.text([\n '\\n',\n t.cmd(t.CSI.Style, [t.Style.Green, t.Style.Invert]),\n ' Done ',\n t.cmd(t.CSI.Style, t.Style.NoInvert),\n t.Chars.Space,\n 'You are all set and ready to go.\\n',\n ]);\n}\n\nexport function errorMessage(message: string) {\n return t.error([\n '\\n',\n t.cmd(t.CSI.Style, [t.Style.Red, t.Style.Invert]),\n ` ${t.Icons.Warning} Error `,\n t.cmd(t.CSI.Style, t.Style.NoInvert),\n `\\n${message.trim()}\\n`,\n ]);\n}\n","import type ts from 'typescript';\nimport path from 'node:path';\n\nimport type { LoadConfigResult } from '@gql.tada/internal';\nimport {\n loadRef,\n loadConfigs,\n parseConfig,\n validateUniqueOutputLocations,\n} from '@gql.tada/internal';\n\nimport type { ComposeInput } from '../../term';\nimport type { ProjectContext } from '../shared';\nimport { MINIMUM_VERSIONS, semverComply } from '../../utils/semver';\nimport { programFactory } from '../../ts';\nimport { findGraphQLConfig } from './helpers/graphqlConfig';\nimport * as versions from './helpers/versions';\nimport * as vscode from './helpers/vscode';\nimport * as logger from './logger';\n\n// NOTE: Currently, most tasks in this command complete too quickly\n// We slow them down to make the CLI output easier to follow along to\nconst delay = (ms = 700) => {\n if (process.env.CI) {\n return Promise.resolve();\n } else {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n};\n\nconst enum Messages {\n TITLE = 'Doctor',\n DESCRIPTION = 'Detects problems with your setup',\n CHECK_TS_VERSION = 'Checking TypeScript version',\n CHECK_DEPENDENCIES = 'Checking installed dependencies',\n CHECK_TSCONFIG = 'Checking tsconfig.json',\n CHECK_EXTERNAL_FILES = 'Checking external files support',\n CHECK_VSCODE = 'Checking VSCode setup',\n CHECK_SCHEMA = 'Checking schema',\n}\n\nexport async function* run(): AsyncIterable<ComposeInput> {\n yield logger.title(Messages.TITLE, Messages.DESCRIPTION);\n yield logger.runningTask(Messages.CHECK_TS_VERSION);\n await delay();\n\n // Check TypeScript version\n let packageJson: versions.PackageJson;\n try {\n packageJson = await versions.readPackageJson();\n } catch (_error) {\n yield logger.failedTask(Messages.CHECK_TS_VERSION);\n throw logger.errorMessage(\n `A ${logger.code('package.json')} file was not found in the current working directory.\\n` +\n logger.hint('Try running the doctor command in your workspace folder.')\n );\n }\n\n const typeScriptVersion = await versions.getTypeScriptVersion(packageJson);\n if (!typeScriptVersion) {\n yield logger.failedTask(Messages.CHECK_TS_VERSION);\n throw logger.errorMessage(\n `A version of ${logger.code('typescript')} was not found in your dependencies.\\n` +\n logger.hint(`Is ${logger.code('typescript')} installed in this package?`)\n );\n } else if (!semverComply(typeScriptVersion, MINIMUM_VERSIONS.typescript)) {\n // TypeScript version lower than v4.1 which is when they introduced template lits\n yield logger.failedTask(Messages.CHECK_TS_VERSION);\n throw logger.errorMessage(\n `The version of ${logger.code('typescript')} in your dependencies is out of date.\\n` +\n logger.hint(\n `${logger.code('gql.tada')} requires at least ${logger.bold(MINIMUM_VERSIONS.typescript)}`\n )\n );\n }\n\n yield logger.completedTask(Messages.CHECK_TS_VERSION);\n yield logger.runningTask(Messages.CHECK_DEPENDENCIES);\n await delay();\n\n const supportsEmbeddedLsp = semverComply(\n typeScriptVersion,\n MINIMUM_VERSIONS.typescript_embed_lsp\n );\n if (!supportsEmbeddedLsp) {\n const gqlspVersion = await versions.getGraphQLSPVersion(packageJson);\n if (!gqlspVersion) {\n yield logger.failedTask(Messages.CHECK_DEPENDENCIES);\n throw logger.errorMessage(\n `A version of ${logger.code('@0no-co/graphqlsp')} was not found in your dependencies.\\n` +\n logger.hint(`Is ${logger.code('@0no-co/graphqlsp')} installed?`)\n );\n } else if (!semverComply(gqlspVersion, MINIMUM_VERSIONS.lsp)) {\n yield logger.failedTask(Messages.CHECK_DEPENDENCIES);\n throw logger.errorMessage(\n `The version of ${logger.code(\n '@0no-co/graphqlsp'\n )} in your dependencies is out of date.\\n` +\n logger.hint(\n `${logger.code('gql.tada')} requires at least ${logger.bold(MINIMUM_VERSIONS.lsp)}`\n )\n );\n }\n }\n\n const gqlTadaVersion = await versions.getGqlTadaVersion(packageJson);\n if (!gqlTadaVersion) {\n yield logger.failedTask(Messages.CHECK_DEPENDENCIES);\n throw logger.errorMessage(\n `A version of ${logger.code('gql.tada')} was not found in your dependencies.\\n` +\n logger.hint(`Is ${logger.code('gql.tada')} installed?`)\n );\n } else if (!semverComply(gqlTadaVersion, '1.0.0')) {\n yield logger.failedTask(Messages.CHECK_DEPENDENCIES);\n throw logger.errorMessage(\n `The version of ${logger.code('gql.tada')} in your dependencies is out of date.\\n` +\n logger.hint(\n `It's recommended to upgrade ${logger.code('gql.tada')} to at least ${logger.bold(\n MINIMUM_VERSIONS.lsp\n )}`\n )\n );\n }\n\n yield logger.completedTask(Messages.CHECK_DEPENDENCIES);\n yield logger.runningTask(Messages.CHECK_TSCONFIG);\n await delay();\n\n let configResults: LoadConfigResult[];\n try {\n configResults = await loadConfigs();\n } catch (error) {\n yield logger.failedTask(Messages.CHECK_TSCONFIG);\n throw logger.externalError(\n `A ${logger.code('tsconfig.json')} file was not found in the current working directory.`,\n error\n );\n }\n\n const projects: ProjectContext[] = [];\n for (const configResult of configResults) {\n const label =\n path.relative(process.cwd(), configResult.tsconfigPath) || configResult.tsconfigPath;\n try {\n projects.push({\n configResult,\n pluginConfig: parseConfig(configResult.pluginConfig, configResult.rootPath),\n projectPath: path.dirname(configResult.tsconfigPath),\n label,\n });\n } catch (error) {\n yield logger.failedTask(Messages.CHECK_TSCONFIG);\n throw logger.externalError(\n `The plugin configuration for ${logger.code(\n supportsEmbeddedLsp ? '\"gql.tada/ts-plugin\"' : '\"@0no-co/graphqlsp\"'\n )} in ${logger.code(label)} seems to be invalid.`,\n error\n );\n }\n }\n\n try {\n validateUniqueOutputLocations(\n projects.map((project) => ({\n projectPath: project.projectPath,\n config: project.pluginConfig,\n label: project.label,\n }))\n );\n } catch (error) {\n yield logger.failedTask(Messages.CHECK_TSCONFIG);\n throw logger.externalError('The output locations of your configured projects overlap.', error);\n }\n\n yield logger.completedTask(Messages.CHECK_TSCONFIG);\n if (projects.length > 1) {\n yield logger.hintMessage(\n `Found ${projects.length} ${logger.code('gql.tada')} projects through ${logger.code(\n '\"references\"'\n )} in your ${logger.code('tsconfig.json')} files.\\n`\n );\n }\n\n yield* runExternalFilesChecks(projects, packageJson);\n\n yield* runVSCodeChecks();\n\n yield logger.runningTask(Messages.CHECK_SCHEMA);\n await delay();\n\n for (const project of projects) {\n try {\n await loadRef(project.pluginConfig).load({ rootPath: project.projectPath });\n } catch (error) {\n yield logger.failedTask(Messages.CHECK_SCHEMA);\n throw logger.externalError(\n projects.length > 1\n ? `Failed to load schema for project ${logger.code(project.label)}.`\n : 'Failed to load schema.',\n error\n );\n }\n }\n\n yield logger.completedTask(Messages.CHECK_SCHEMA, true);\n await delay();\n\n yield logger.success();\n}\n\nasync function* runVSCodeChecks(): AsyncIterable<ComposeInput> {\n const suggestedExtensions = await vscode.loadSuggestedExtensionsList();\n const isVSCodeInstalled = await vscode.isVSCodeInstalled();\n if (suggestedExtensions.length || isVSCodeInstalled) {\n yield logger.runningTask(Messages.CHECK_VSCODE);\n await delay();\n\n let hasEndedTask = false;\n let userExtensions: readonly string[] = [];\n if (isVSCodeInstalled) {\n userExtensions = await vscode.loadExtensionsList();\n if (!userExtensions.includes('graphql.vscode-graphql-syntax')) {\n if (!hasEndedTask) {\n hasEndedTask = true;\n yield logger.warningTask(Messages.CHECK_VSCODE);\n }\n yield logger.hintMessage(\n `We recommend you to install the ${logger.code(\n '\"GraphQL: Syntax Highlighting\"'\n )} extension for VSCode.\\n` +\n 'See: https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql-syntax\\n'\n );\n }\n }\n\n const hasProblemExtension =\n userExtensions.includes('graphql.vscode-graphql') ||\n suggestedExtensions.includes('graphql.vscode-graphql');\n const graphqlConfig = await findGraphQLConfig();\n if (hasProblemExtension && !!graphqlConfig) {\n if (!hasEndedTask) {\n hasEndedTask = true;\n yield logger.warningTask(Messages.CHECK_VSCODE);\n }\n const fileName = path.basename(graphqlConfig);\n yield logger.hintMessage(\n `The ${logger.code(\n '\"GraphQL: Language Feature Support\"'\n )} VSCode extension can cause problems!\\n` +\n `When enabled it may display invalid diagnostic errors for ${logger.code(\n 'gql.tada'\n )} code.\\n` +\n `Check whether your ${logger.code(fileName)} config only targets ${logger.code(\n '.graphql'\n )} documents.\\n`\n );\n }\n\n if (!hasEndedTask) {\n yield logger.completedTask(Messages.CHECK_VSCODE);\n }\n }\n}\n\nasync function* runExternalFilesChecks(\n projects: readonly ProjectContext[],\n packageJson: versions.PackageJson\n): AsyncIterable<ComposeInput> {\n const externalFiles: ts.SourceFile[] = [];\n for (const project of projects) {\n try {\n const factory = programFactory({\n rootPath: project.configResult.rootPath,\n configPath: project.configResult.tsconfigPath,\n });\n externalFiles.push(...factory.createExternalFiles());\n } catch (_error) {\n // NOTE: If a project fails to load, we currently just ignore this check and move on\n }\n }\n\n if (externalFiles.length) {\n yield logger.runningTask(Messages.CHECK_EXTERNAL_FILES);\n await delay();\n\n const extensions = new Set(\n externalFiles.map((sourceFile) => path.extname(sourceFile.fileName))\n );\n\n if (extensions.has('.svelte') && !(await versions.hasSvelteSupport(packageJson))) {\n yield logger.failedTask(Messages.CHECK_EXTERNAL_FILES);\n throw logger.errorMessage(\n `A version of ${logger.code(\n '@gql.tada/svelte-support'\n )} must be installed for Svelte file support.\\n` +\n logger.hint(`Have you installed ${logger.code('@gql.tada/svelte-support')}?`)\n );\n }\n\n if (extensions.has('.vue') && !(await versions.hasVueSupport(packageJson))) {\n yield logger.failedTask(Messages.CHECK_EXTERNAL_FILES);\n throw logger.errorMessage(\n `A version of ${logger.code(\n '@gql.tada/vue-support'\n )} must be installed for Vue file support.\\n` +\n logger.hint(`Have you installed ${logger.code('@gql.tada/vue-support')}?`)\n );\n }\n\n yield logger.completedTask(Messages.CHECK_EXTERNAL_FILES);\n }\n}\n","import { Command } from 'clipanion';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class DoctorCommand extends Command {\n static paths = [['doctor']];\n\n async execute() {\n const result = await initTTY().start(run());\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n","import * as path from 'node:path';\nimport { Command, Option } from 'clipanion';\n\nexport class InitCommand extends Command {\n static paths = [['init']];\n\n input = Option.String({ name: 'dir' });\n\n async execute() {\n const { run } = await import('./runner');\n const target = path.resolve(process.cwd(), this.input);\n await run(target);\n }\n}\n","import { Cli } from 'clipanion';\nimport * as api from './api';\n\nimport { CheckCommand } from './commands/check/index';\nimport { DoctorCommand } from './commands/doctor/index';\nimport { GenerateOutputCommand } from './commands/generate-output/index';\nimport { GeneratePersisted } from './commands/generate-persisted/index';\nimport { GenerateSchema } from './commands/generate-schema/index';\nimport { InitCommand } from './commands/init/index';\nimport { ScanCommand } from './commands/scan/index';\nimport { TurboCommand } from './commands/turbo/index';\n\nasync function _main() {\n const cli = new Cli({\n binaryVersion: process.env.npm_package_version || '0.0.0',\n binaryLabel: 'gql.tada CLI',\n binaryName: 'gql.tada',\n });\n\n cli.register(CheckCommand);\n cli.register(DoctorCommand);\n cli.register(GenerateOutputCommand);\n cli.register(GeneratePersisted);\n cli.register(GenerateSchema);\n cli.register(InitCommand);\n cli.register(ScanCommand);\n cli.register(TurboCommand);\n\n await cli.runExit(process.argv.slice(2));\n}\n\ntype MainFn = typeof _main & typeof api;\nconst main = Object.assign(_main, api) as MainFn;\n\nexport * from './api';\nexport default main;\n"],"names":["SpecialToken","NodeType","HELP_COMMAND_INDEX","HELP_REGEX","OPTION_REGEX","BATCH_REGEX","BINDING_REGEX","IS_DEBUG","process","env","DEBUG_CLI","UsageError","Error","constructor","message","super","this","clipanion","type","name","UnknownSyntaxError","input","candidates","length","every","candidate","reason","map","usage","join","whileRunning","index","padStart","AmbiguousSyntaxError","usages","filter","token","EndOfInput","EndOfPartialInput","json","JSON","stringify","match","richLine","Array","fill","t","richFormat","header","str","MAX_LINE_LENGTH","slice","bold","error","code","textFormat","formatMarkdownish","text","format","paragraphs","dedent","lines","split","nonEmptyLines","line","indent","reduce","minLength","Math","min","trimStart","Number","MAX_VALUE","trimRight","replace","$0","$1","paragraph","bulletMatch","RegExp","repeat","$2","isOptionSymbol","Symbol","makeCommandOption","spec","rerouteArguments","a","b","isArray","undefined","cleanValidationError","mergeName","path","toLowerCase","formatError","errors","applyValidator","value","validator","coercions","coercion","v","orig","bind","op","Command","help","Usage","catch","validateAndExecute","cascade","schema","isDict","isUnknown","applyCascade","Promise","resolve","then","exitCode","execute","isOption","Default","debug","console","log","basicHelpState","candidateUsage","requiredOptions","errorMessage","ignoreOptions","positionals","options","remainder","selectedIndex","tokens","makeStateMachine","stateMachine","nodes","CustomNode","push","dynamics","shortcuts","statics","injectNode","machine","node","runMachineInternal","partial","branches","InitialNode","state","debugMachine","prefix","StartOfInput","segment","isEOI","segmentIndex","nextBranches","nodeDef","ErrorNode","assert","hasExactMatch","Object","prototype","hasOwnProperty","call","transitions","to","reducer","reducers","hasMatches","keys","startsWith","test","tests","trimSmallerBranches","branch","runMachine","endToken","selectBestState","states","terminalStates","requiredOptionsSetStates","names","some","find","opt","maxPathSize","bestPathBranches","getPositionalCount","extra","statesWithPositionalCount","positionalCount","maxPositionalCount","fixedStates","aggregateHelpStates","notHelps","helps","findCommonPrefix","concat","firstPath","secondPath","rest","from","i","isTerminalNode","SuccessNode","cloneTransition","offset","cloneNode","output","transition","entries","registerDynamic","registerShortcut","registerStatic","store","callback","args","always","isOptionLike","isNotOptionLike","isBatchOption","has","isBoundOption","optionParsing","nameSet","includes","allowBinding","isNegatedOption","isHelp","isUnsupportedOption","isInvalidOption","setCandidateState","candidateState","setSelectedIndex","pushBatch","get","option","pushBound","pushPath","pushPositional","pushExtra","pushExtraNoLimits","NoLimits","pushTrue","pushFalse","pushUndefined","pushStringValue","_a","lastOption","setStringValue","inhibateOptions","useHelp","command","String","setError","setOptionArityError","CommandBuilder","cliIndex","cliOpts","allOptionNames","Map","arity","leading","trailing","proxy","paths","addPath","setArity","assign","addPositional","required","addRest","addProxy","addOption","description","hidden","isInteger","preferredName","longestName","set","setContext","context","detailed","inlineOptions","segments","binaryName","detailedOptionList","definition","compile","firstNode","positionalArgument","lastPathNode","optionPathNode","registerOptions","nextPathNode","helpNode","lastLeadingNode","nextLeadingNode","lastExtraNode","extraShortcutNode","extraNode","nextExtraNode","lastTrailingNode","nextTrailingNode","lastNode","nextNode","CliBuilder","builders","opts","build","cbs","commands","getBuilderByIndex","n","cb","builder","machines","contexts","makeAnyOfMachine","inputs","heads","head","simplifyMachine","visited","Set","add","values","shift","toDef","_loop","_loop2","_transition","otherTest","HelpCommand","stdout","write","cli","commandClass","errorCommandSymbol","Cli","binaryLabel","binaryNameOpt","binaryVersion","enableCapture","enableColors","registrations","commandClasses","resolvedCommandClasses","register","specs","key","contextArg","userContext","defaultContext","record","transformer","run","_b","colored","colorDepth","definitions","subContext","activate","getCaptureActivator","noopCaptureActivator","runExit","getUsageByRegistration","category","details","examples","label","data","isDocumented","isDefault","result","commandsByCategories","categoryCommands","getUsageByIndex","categoryNames","sort","localeCompare","caseFirst","hasLabel","hasVersion","categoryName","trim","doc","toUpperCase","maxDefinitionLength","max","padEnd","example","meta","stack","klass","stdin","stderr","fn","Boolean","descriptor","initialValueBase","optsBase","initialValue","optNames","builer","currentValue","StringOption","tolerateBoolean","usedName","StringPositional","positional","splice","TadaErrorCode","TadaError","isTadaError","parseInt","hasColor","_setColor","color","CSI","EraseLine","Mode","PrivateMode","Style","escapeCSI","cmd","out","SetPrivateMode","SetMode","UnsetPrivateMode","UnsetMode","ansiRegex","stripAnsi","CLIError","exit","toString","argIndex","arg","commit","source","make","observer","last","subscription","pipe","onPush","next","onEnd","endsWith","complete","subscribe","unsubscribe","compose","outputs","reset","Reset","NoInvert","outputs$","fromAsyncIterable","async","convertError","concatMap","fromValue","x","share","output$","merge","never","takeUntil","scan","prev","clear","charCodeAt","PrevLine","DeleteLines","Backward","ToColumn","takeLast","Chars","Box","HeavyBox","SmallTriangle","Icons","dotSpinner","circleSpinner","isGithubCI","GITHUB_ACTIONS","toCommandValue","escapeData","escapeProperty","githubAnnotation","kind","properties","propsOut","initTTY","params","isTTY","TERM","CI","disableTTY","pipeTo","hasColorArg","argv","hasColorEnv","NO_COLOR","_terminate","_restore","setRawMode","ResetPrivateMode","ShowCursor","_signal","signal","inputSource","fromReadStream","stream","onTerminate","onKeypress","event","ctrl","cleanup","removeListener","unref","emitKeypressEvents","setEncoding","resume","addListener","onStart","_start","on","_end","cancelSource","isInteractive","silent","start","toPromise","mode","modes","normalModes","privateModes","Insert","AutomaticNewline","modeOff","Newline","Underline","NoUnderline","Bold","Normal","hint","BrightBlack","BottomLeft","BrightBlue","Info","Blue","projectHeader","Magenta","Right","Foreground","Red","Invert","Warning","externalError","title","experimentMessage","Yellow","loadProjects","projects","loadConfigs","tsconfig","configResult","projectPath","dirname","tsconfigPath","pluginConfig","parseConfig","rootPath","relative","cwd","validateUniqueOutputLocations","project","config","directoryExists","stat","fs","file","isDirectory","isSymbolicLink","realpath","readOutput","target","readFile","writeOutput","contents","reject","targetDirectory","mkdir","recursive","isFile","writeFile","tempTarget","rename","unlink","now","Date","utimes","_error","touchFile","summary","showHint","BrightGreen","Tick","tty","logger","generated","destinations","outputDestinations","destination","runProject","schemas","tadaOutputLocation","location","schemaRef","loadRef","load","current","existing","outputIntrospectionFile","minifyIntrospection","introspection","fileType","forceTSFormat","shouldPreprocess","disablePreprocessing","preamble","extractIntrospectionHeader","schemaName","multi","GenerateOutputCommand","static","Option","generateOutput","CWD","INDENT","warningFile","filePath","relativePath","documentSummary","documentCount","warningSummary","warningCount","Cross","infoSummary","BrightYellow","warningGithub","col","runningPersisted","ofFiles","progress","frame","Ellipsis","interval","totalWarnings","failedProjects","warnings","failed","deferWarnings","runPersisted","require","generator","disableNormalization","configPath","documents","totalFileCount","fileCount","buffer","warning","Tab","tadaPersistedLocation","failOnWarn","item","hashKey","document","schemaConfig","GeneratePersisted","generatePersisted","simpleKeyRegExp","getPrintable","computeKey","_c","p","pushError","makeCoercionFn","previous","isLiteral","expected","makeValidator","isString","delimiter","originalValue","valid","T","isTuple","lengthValidator","hasExactLength","isRecord","keySpec","isArrayValidator","fromEntries","sub","isOneOf","exclusive","matches","errorBuffer","subErrors","subCoercions","makeTrait","matchesRegExp","regExp","followups","resolvedFollowups","subCoercion","reverts","revert","KeyRelationship","origin","headers","url","loader","extname","printSchema","isHeaderEntries","parseHeaders","entry","indexOf","trimEnd","GenerateSchema","generateSchema","reusedLabel","count","cachedCount","cachedLabel","runningTurbo","PREAMBLE_IGNORE","runTurbo","tadaTurboLocation","hintMessage","turboOutputPath","graphqlSources","cachedDocumentCount","sources","isCached","createCacheContents","cache","turboDestination","documentsByKey","argumentKey","compareUtf16","documentHash","documentType","imports","isFilePath","sortedSources","absolutePath","addedImports","importInfo","turboPath","sourceDir","specifier","importClause","TurboCommand","generateTurbo","ModuleGraph","_dependents","edges","_edges","_cwd","importMap","areaOf","modulePath","rel","dir","entryPoints","_entryPoints","targets","tos","dependents","cached","reverse","_reverseGraph","pop","distanceFromEntry","_distance","distance","frontier","depth","reach","modules","areas","reachedEntries","module","_reverse","importers","FragmentGraph","_byId","_idByName","_operationIds","_reachable","id","reachableFragments","definitionId","fragmentSpreads","fragment","operationsReaching","fragmentId","_operationsReaching","operationId","reachableId","hashOf","crypto","createHash","update","digest","collectFragmentSpreads","visit","FragmentSpread","spread","ScanContext","_operations","_fragments","_definitions","_recordByNode","_recordById","_typeInfo","_currentDefinition","_schemas","_warnings","_importGraph","_buildCorpus","_modules","_buildModules","operations","fragments","getSchemas","definitionNodesForSchema","setTypeInfo","typeInfo","trackingVisitor","OperationDefinition","enter","leave","FragmentDefinition","getCurrentDefinition","getParentType","getType","getFieldDef","getInputType","getParentInputType","getEnumValue","getModuleGraph","_moduleGraph","getFragmentGraph","_fragmentGraph","_addWarning","_uniqueId","base","_register","defKind","_node","_defKind","info","anonCount","parse","noLocation","loc","Kind","OPERATION_DEFINITION","operation","variables","variableDefinitions","variable","print","defaultValue","hash","FRAGMENT_DEFINITION","typeCondition","byPath","ensure","resolved","fieldUsage","create","byCoordinate","seen","resetSeen","visitor","Field","parentType","fieldDef","coordinate","typeName","fieldName","fieldType","deprecationReason","directUsages","defId","collect","operationIds","moduleById","graph","hasEntryPoints","size","datapoints","sourceModules","u","reachModules","reachAreas","reachEntries","m","e","ref","weight","deprecated","coordinateOf","d","DEFAULT_RULES","counts","bump","EnumValue","inputType","getNamedType","ObjectField","parentInput","defIds","spreadIds","consumerAreas","spreadCount","byId","definingArea","externalAreas","area","byDef","startDefinition","ownDepth","fields","listFields","spreads","SelectionSet","isListType","getNullableType","depthMemo","effectiveDepth","visiting","metrics","delete","operationDepth","score","fieldCount","Directive","buildOverview","rules","operationsByKind","query","mutation","usedFields","totalFields","allSchemaFields","getTypeMap","isObjectType","isInterfaceType","field","getFields","percent","round","coverage","renderJson","version","overview","moduleNodeId","fieldNodeId","typeNodeId","fragmentKey","renderGraph","buildGraph","addNode","fragmentIdByName","moduleNode","datapoint","site","addDefinition","spreadName","MAX_PER_RULE","MIN_MESSAGE_WIDTH","RULE_DESCRIPTIONS","rule","truncate","renderTerminalReport","width","coverageLine","shown","truncated","forEach","isLast","weightText","locText","locator","locWidth","budget","VerticalRight","runningScan","runScan","quiet","loadSchemas","analyze","instances","instance","TypeInfo","visitInParallel","DOCUMENT","visitWithTypeInfo","results","render","wroteOutput","columns","ScanCommand","diagnosticFile","diagnosticMessage","severity","BrightRed","diagnosticMessageGithub","endLine","endColumn","runningDiagnostics","isMinSeverity","minSeverity","runDiagnostics","warn","warnedAboutExternalFiles","messages","problemsSummary","CheckCommand","Intl","Collator","numeric","compare","MINIMUM_VERSIONS","typescript_embed_lsp","typescript","tada","lsp","semverComply","semiver","bool","spanToFilePosition","span","fileName","lineAndChar","getLineAndCharacterOfPosition","character","notImplemented","methodName","defaultCompilerOptions","ts","getDefaultCompilerOptions","jsx","JsxEmit","React","strict","esModuleInterop","ModuleKind","ESNext","suppressOutputPathCheck","skipLibCheck","skipDefaultLibCheck","moduleResolution","ModuleResolutionKind","NodeJs","createVirtualCompilerHost","sys","compilerOptions","sourceFiles","compilerHost","getCanonicalFileName","getDefaultLibFileName","getDirectories","getNewLine","newLine","getSourceFile","sourceFile","save","createSourceFile","useCaseSensitiveFileNames","updateFile","alreadyExists","createVirtualLanguageServiceHost","rootFiles","customTransformers","fileNames","fileVersions","projectVersion","languageServiceHost","getProjectVersion","getCompilationSettings","getCustomTransformers","getScriptFileNames","getScriptSnapshot","ScriptSnapshot","fromString","getScriptVersion","defineProperty","binarySearch_1","binarySearch","offsets","low","high","mid","floor","midValue","track_1","getStack","track","resetOffsetStack","offsetStack","setTracking","tracking","stackOffset","stacks","Proxy","prop","receiver","unshift","Reflect","items","first","deleteCount","_stackStart","operateIndex","stackStart","originalLength","_deleteCount","compareFn","lastIndexOf","types","__createBinding","o","k","k2","desc","getOwnPropertyDescriptor","__esModule","writable","configurable","enumerable","__exportStar","exports","replaceRange","replaceSourceRange","getLength","require$$0","require$$1","require$$2","s","pattern","replacers","startOffset","endOffset","replacer","replaceAll","allMatch","matchAll","lengthDiff","newLength","newSegments","segmentStart","segmentEnd","inserts","trimSegmentEnd","newSegment","trimSegmentStart","combineStrings","toOffsets","startIndex","endIndex","endSegment","startSegmentStart","endSegmentStart","endSegmentEnd","searchValue","translateOffset_1","translateOffset","fromOffsets","lengths","fromOffset","sourceMap","SourceMap","mappings","getSourceOffset","generatedOffset","mapped","findMatching","getGeneratedOffset","sourceOffset","getSourceOffsets","getGeneratedOffsets","fromRange","toRange","memo","getMemoBasedOnRange","end","skip","mapping","sourceCodeOffsetsMemo","createMemo","generatedCodeOffsetsMemo","offsetsSet","buildMappings_1","buildMappings","chunks","sourceOffsets","generatedOffsets","buildStacks_1","buildStacks","range","require$$3","require$$4","SourceMappedFile","sourceFileId","generatedFileId","getSourceSpan","sourceStart","sourceEnd","maybeBind","that","buildLanguageService","virtualMap","languageService","createLanguageService","documentRegistry","getProgram","mapFileFn","fileFn","fileId","mappedFile","mapFileTextSpanFn","textSpanFn","mapFileTextRangeFn","pos","mapFilePositionFn","positionFn","position","mapFileStartEndFn","program","serviceProgram","projectRoot","isSourceFileFromExternalLibrary","getModeForResolutionAtIndex","getSourceFiles","mapSourceFileFn","getSyntacticDiagnostics","getSemanticDiagnostics","getDeclarationDiagnostics","isSourceFileDefaultLibrary","getModeForUsageLocation","buildProgram","getReferencesAtPosition","findReferences","getDefinitionAtPosition","getDefinitionAndBoundSpan","getTypeDefinitionAtPosition","getImplementationAtPosition","getCompletionsAtPosition","getCompletionEntryDetails","getCompletionEntrySymbol","getQuickInfoAtPosition","getBreakpointStatementAtPosition","getSignatureHelpItems","getRenameInfo","getSmartSelectionRange","getDocumentHighlights","prepareCallHierarchy","provideCallHierarchyIncomingCalls","provideCallHierarchyOutgoingCalls","getBraceMatchingAtPosition","getIndentationAtPosition","getFormattingEditsAfterKeystroke","getDocCommentTemplateAtPosition","isValidBraceCompletionAtPosition","getJsxClosingTagAtPosition","getLinkedEditingRangeAtPosition","getSpanOfEnclosingComment","getSyntacticClassifications","getSemanticClassifications","getEncodedSyntacticClassifications","getEncodedSemanticClassifications","provideInlayHints","getNameOrDottedNameSpan","getFormattingEditsForRange","getCodeFixesAtPosition","getFileReferences","getNavigationBarItems","getNavigationTree","getOutliningSpans","getTodoComments","getFormattingEditsForDocument","getEditsForRefactor","getEmitOutput","getSuggestionDiagnostics","getSupportedCodeFixes","toggleLineComment","toggleMultilineComment","commentSelection","uncommentSelection","buildPluginInfo","getLanguageService","system","rootNames","getProjectName","projectService","serverHost","setImmediate","clearImmediate","_svelte","_vue","transformExtensions","transform","import","SVELTE_SUPPORT","transformSvelte","VUE_SUPPORT","check","checkVue","transformVue","UNKNOWN_EXTERNAL_FILE","programFactory","vfsMap","createFSBackedSystem","files","_projectRoot","tsLibDirectory","root","nodeSys","tsLib","directory","createDirectory","fileExists","tsLibName","getCurrentDirectory","getExecutingFilePath","readDirectory","libs","resolvePath","resolveDefaultLibsPath","resolveConfig","getDefaultLibFilePath","noCheck","orignallyNodeNext","NodeNext","Node16","Bundler","host","createDocumentRegistry","factory","wasOriginallyNodeNext","projectDirectories","directories","rootName","rootFileNames","scriptKind","sourceText","getText","ScriptTarget","ScriptKind","TSX","createExternalFiles","exts","External","addSourceFile","addMappedFile","sourceMappedFile","addVirtualFiles","virtualFileId","virtualCode","snapshot","resolveModulePath","importSpecifier","fromPath","resolveModuleName","resolvedModule","resolvedFileName","toPath","fromDir","toDir","absoluteImportPath","relativeImportPath","bumpStackTraceLimit","stackTraceLimit","init","service","serviceHost","pluginInfo","getLanguageServiceHost","createProgram","getSourceMappedFile","getSourcePosition","buildContainer","createRequire","request","parseResult","parseConfigFileTextToJson","messageText","parseJsonConfigFileContent","FileType","File","Directory","configFileRe","findGraphQLConfig","readdir","configFile","workspaceRoot","targetPath","packageJsonPath","workspaces","findWorkspaceRoot","graphql","loadPnpmWorkspaceCatalogs","startPath","currentPath","workspaceFile","access","findPnpmWorkspaceroot","content","currentSection","currentCatalog","trimmed","packages","catalog","catalogs","colonIndex","parseYaml","loadBunWorkspaceCatalogs","packageJsonFile","packageJson","findBunWorkspaceRoot","loadWorkspaceCatalogs","pnpmCatalogs","bunCatalogs","resolveCatalogVersion","catalogRef","catalogName","getVersionFromCatalog","packageName","getPackageVersion","devVersion","devDependencies","resolvedVersion","depVersion","dependencies","hasPackageSupport","__dirname","hasSvelteSupport","hasVueSupport","jsonParse","parseJsonText","convertToObject","isVSCodeInstalled","HOME","vscodeFolder","loadSuggestedExtensionsList","recommendations","loadExtensionsList","identifier","emptyLine","Vertical","completedTask","Green","TickSwoosh","failedTask","CrossSwoosh","warningTask","runningTask","delay","ms","setTimeout","Messages","TopLeft","TITLE","DESCRIPTION","CHECK_TS_VERSION","versions","typeScriptVersion","pkg","catalogVersion","CHECK_DEPENDENCIES","supportsEmbeddedLsp","gqlspVersion","gqlTadaVersion","CHECK_TSCONFIG","configResults","runExternalFilesChecks","externalFiles","CHECK_EXTERNAL_FILES","extensions","runVSCodeChecks","suggestedExtensions","vscode","CHECK_VSCODE","hasEndedTask","userExtensions","hasProblemExtension","graphqlConfig","basename","CHECK_SCHEMA","success","Space","DoctorCommand","InitCommand","main","_main","npm_package_version","api"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAIA;;CACJ,SAAWA;EACPA,EAA2B,eAAI;EAC/BA,EAAyB,aAAI;EAC7BA,EAAgC,oBAAI;AACvC,CAJD,CAIGA,MAAiBA,IAAe,CAAE;;AACrC,IAAIC;;CACJ,SAAWA;EACPA,EAASA,EAAsB,cAAI,KAAK;EACxCA,EAASA,EAAsB,cAAI,KAAK;EACxCA,EAASA,EAAoB,YAAI,KAAK;EACtCA,EAASA,EAAqB,aAAI,KAAK;AAC1C,CALD,CAKGA,MAAaA,IAAW,CAAE;;AAC7B,IAAMC,KAAsB;;AAC5B,IAAMC,IAAa;;AACnB,IAAMC,IAAe;;AACrB,IAAMC,IAAc;;AACpB,IAAMC,IAAgB;;AACtB,IAAMC,IAAqC,QAA1BC,QAAQC,IAAIC;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