@ahoo-wang/wow-generator 10.0.0-alpha.7 → 10.0.0-beta.1
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.
- package/README.md +5 -3
- package/README.zh-CN.md +4 -2
- package/dist/cli.cjs +1 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +2 -2
- package/dist/{codeGenerator-C0dKAKl6.cjs → codeGenerator-CADTvm2G.cjs} +19 -19
- package/dist/codeGenerator-CADTvm2G.cjs.map +1 -0
- package/dist/{codeGenerator-Bouc_Ad8.js → codeGenerator-Cxlr_VOh.js} +588 -580
- package/dist/codeGenerator-Cxlr_VOh.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/manifest/analyze.d.cts +11 -1
- package/dist/manifest/analyze.d.ts +11 -1
- package/package.json +11 -3
- package/dist/codeGenerator-Bouc_Ad8.js.map +0 -1
- package/dist/codeGenerator-C0dKAKl6.cjs.map +0 -1
package/README.md
CHANGED
|
@@ -22,9 +22,11 @@ pnpm exec wow-generator generate \
|
|
|
22
22
|
|
|
23
23
|
For each bounded context it writes `types.ts` (the command, event and state
|
|
24
24
|
types of the Manifest's schemas), `contract.ts` (`<Context>Contract`: its name,
|
|
25
|
-
error codes and aggregates, and its wait hops)
|
|
26
|
-
(`<Context>
|
|
27
|
-
aggregate
|
|
25
|
+
error codes and aggregates, and its wait hops), `manifest.ts`
|
|
26
|
+
(`<Context>Manifest`: the routes its clients send by, so they fetch no Manifest),
|
|
27
|
+
`client.ts` (`<Context>Client`: its `CommandClient` and every aggregate's
|
|
28
|
+
clients), and, for a context with routes of its own, `routes.ts`
|
|
29
|
+
(`<Context>Routes`); and for each aggregate:
|
|
28
30
|
|
|
29
31
|
- `aggregate.ts`: the aggregate's descriptor, its state fields and its event
|
|
30
32
|
union;
|
package/README.zh-CN.md
CHANGED
|
@@ -19,8 +19,10 @@ pnpm exec wow-generator generate \
|
|
|
19
19
|
```
|
|
20
20
|
|
|
21
21
|
每个限界上下文写出 `types.ts`(Manifest 中 schema 对应的命令、事件与状态类型)、
|
|
22
|
-
`contract.ts`(`<Context>Contract
|
|
23
|
-
`
|
|
22
|
+
`contract.ts`(`<Context>Contract`:上下文名、错误码与各聚合,以及等待节点)、
|
|
23
|
+
`manifest.ts`(`<Context>Manifest`:客户端发送所按的路由,所以它们不拉取 Manifest)、
|
|
24
|
+
`client.ts`(`<Context>Client`:它的 `CommandClient` 与每个聚合的客户端),对有自己路由的
|
|
25
|
+
上下文还有 `routes.ts`(`<Context>Routes`);每个聚合写出:
|
|
24
26
|
|
|
25
27
|
- `aggregate.ts`:聚合的描述、状态字段与事件联合类型;
|
|
26
28
|
- `commandClient.ts`:`<Aggregate>CommandClient`,每条命令一个方法,另有按等待的每个节点逐个返回结果的 `…Stream` 方法;
|
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./codeGenerator-
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./codeGenerator-CADTvm2G.cjs");let t=require("path"),n=require("commander");var r=`10.0.0-beta.1`;function i(e){if(!e)return!1;let t;try{t=new URL(e)}catch{return!0}return/^[a-z]:$/i.test(t.protocol)?!0:t.protocol===`http:`||t.protocol===`https:`}function a(t=[]){let n={};for(let r of t){let t=r.indexOf(`:`),i=t>0?r.slice(0,t).trim():``;if(!i)throw new e.s(`input`,`Invalid --header "${r}": expected "Name: value".`);n[i]=r.slice(t+1).trim()}return n}function o(t){if(t===void 0)return;let n=Number(t);if(!Number.isInteger(n)||n<=0)throw new e.s(`input`,`Invalid --timeout "${t}": expected a positive number of milliseconds.`);return n}function s(t){if(t===void 0||t===`summary`)return`summary`;if(t===`full`)return`full`;throw new e.s(`input`,`Invalid --schema-docs "${t}": expected "summary" or "full".`)}function c(e){return e.verbose?`verbose`:e.quiet?`quiet`:`normal`}function l(t,n,r){if(n instanceof e.s)return t.error(n.message),r&&n.cause!==void 0&&t.error(`Caused by:`,n.cause),n.exitCode;let i=n instanceof Error?n.message:String(n);return t.error(`Code generation failed: ${i}`),r?t.error(``,n):t.error(`Rerun with --verbose for the stack trace, and report it at https://github.com/Ahoo-Wang/Wow/issues if the input is valid.`),e.o.internal}async function u(n,u=new e.i({level:c(n)}),d={}){if(!i(n.input))return u.error(`Invalid input "${n.input}": expected a file path or an http(s) URL.`),e.o.input;try{u.debug(`wow-generator v${r}`);let i={...d,inputPath:n.input,outputDir:n.output,configPath:n.config,tsConfigFilePath:n.tsConfigFilePath,headers:a(n.header),timeoutMs:o(n.timeout),schemaDocs:s(n.schemaDocs),logger:u},c=await new e.t(i).generate(),l=c.warnings?`, ${c.warnings} warning${c.warnings===1?``:`s`}`:``,f=c.configPath?` with ${(0,t.relative)(process.cwd(),c.configPath)||c.configPath}`:``;return u.info(`Generated ${c.files.length} files into ${n.output}${f}${l}`),n.strict&&c.warnings>0?(u.error(`--strict: the run logged ${c.warnings} warning${c.warnings===1?``:`s`}.`),e.o.specification):e.o.success}catch(t){return d[e.n]?.aborted?e.o.interrupted:l(u,t,!!n.verbose)}}async function d(t){let n=new AbortController;process.once(`SIGINT`,()=>{console.error(`Generation interrupted by user`),n.abort()}),process.exitCode=await u(t,void 0,{[e.n]:n.signal})}var f=`
|
|
3
3
|
Exit codes:
|
|
4
4
|
${e.o.success} generated; or --help, help or --version printed
|
|
5
5
|
${e.o.internal} internal error; rerun with --verbose for the stack trace
|
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.cjs","names":["GeneratorError","EXIT_CODES","ConsoleLogger","CodeGenerator","relative","SIGNAL_SEAM","EXIT_CODES","program","DEFAULT_CONFIG_PATH","DEFAULT_HTTP_TIMEOUT_MS","CommanderError","require_codeGenerator","path","commander","VERSION","validateInput","input","url","parseHeaders","parsed","header","headers","separator","name","parseTimeout","timeout","value","parseSchemaDocs","schemaDocs","logLevel","options","reportFailure","error","logger","verbose","message","runGenerate","generatorOptions","seams","result","warnings","config","generateAction","interruption","EXIT_CODE_HELP","collect","previous","setupCLI","target","commanderExitCode","runCLI","args"],"sources":["../src/version.ts","../src/cli/runGenerate.ts","../src/cli/program.ts","../src/cli.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Replaced at build time with the `version` of this package's package.json\n// (`define` in vite.config.ts, which Vitest shares), so only the version string\n// reaches dist, not the manifest with its dependencies and workspace ranges.\ndeclare const __WOW_GENERATOR_VERSION__: string;\n\n/** The version of this package, as its package.json named it at build time. */\nexport const VERSION: string = __WOW_GENERATOR_VERSION__;\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { relative } from 'path';\nimport { VERSION } from '../version';\nimport { EXIT_CODES, GeneratorError } from '../api/errors';\nimport { CodeGenerator } from '../pipeline/codeGenerator';\nimport type { Logger, LogLevel } from '../api/logger';\nimport { ConsoleLogger } from '../api/logger';\nimport type { SchemaDocs } from '../api/options';\nimport type { SeamOptions, Seams } from '../pipeline/seams';\nimport { SIGNAL_SEAM } from '../pipeline/seams';\n\n/**\n * Options of the `generate` command, as commander parses them.\n */\nexport interface GenerateCommandOptions {\n input: string;\n output: string;\n config?: string;\n tsConfigFilePath?: string;\n /** `Name: value` request headers for an http(s) input or configuration. */\n header?: string[];\n /** Milliseconds, as typed on the command line. */\n timeout?: string;\n /** `summary` or `full`. */\n schemaDocs?: string;\n /** Exit with a non-zero code when the run logged a warning. */\n strict?: boolean;\n verbose?: boolean;\n quiet?: boolean;\n}\n\n/**\n * Validates the input path or URL.\n *\n * Any file path is accepted here and checked when it is read. A URL must use\n * http or https; its host is not restricted, because the generator runs on\n * the developer's own machine against a document they chose, and fetching an\n * intranet service's `/v3/api-docs` is the common case.\n *\n * @param input - Input path or URL\n * @returns true if valid\n */\nexport function validateInput(input: string): boolean {\n if (!input) return false;\n let url: URL;\n try {\n url = new URL(input);\n } catch {\n // Not a URL: a file path, which parseOpenAPI reads.\n return true;\n }\n // A Windows path such as C:\\spec.json parses as a URL with scheme \"c:\".\n if (/^[a-z]:$/i.test(url.protocol)) return true;\n return url.protocol === 'http:' || url.protocol === 'https:';\n}\n\n/**\n * Parses `Name: value` header arguments.\n *\n * @param headers - The raw `--header` values\n * @returns The headers by name\n * @throws GeneratorError of kind `input` for a value without a name\n */\nexport function parseHeaders(\n headers: readonly string[] = [],\n): Record<string, string> {\n const parsed: Record<string, string> = {};\n for (const header of headers) {\n const separator = header.indexOf(':');\n const name = separator > 0 ? header.slice(0, separator).trim() : '';\n if (!name) {\n throw new GeneratorError(\n 'input',\n `Invalid --header \"${header}\": expected \"Name: value\".`,\n );\n }\n parsed[name] = header.slice(separator + 1).trim();\n }\n return parsed;\n}\n\nfunction parseTimeout(timeout: string | undefined): number | undefined {\n if (timeout === undefined) return undefined;\n const value = Number(timeout);\n if (!Number.isInteger(value) || value <= 0) {\n throw new GeneratorError(\n 'input',\n `Invalid --timeout \"${timeout}\": expected a positive number of milliseconds.`,\n );\n }\n return value;\n}\n\nfunction parseSchemaDocs(schemaDocs: string | undefined): SchemaDocs {\n if (schemaDocs === undefined || schemaDocs === 'summary') return 'summary';\n if (schemaDocs === 'full') return 'full';\n throw new GeneratorError(\n 'input',\n `Invalid --schema-docs \"${schemaDocs}\": expected \"summary\" or \"full\".`,\n );\n}\n\nfunction logLevel(options: GenerateCommandOptions): LogLevel {\n if (options.verbose) return 'verbose';\n if (options.quiet) return 'quiet';\n return 'normal';\n}\n\n/**\n * Reports a failure as one actionable line; the stack and the causes only\n * with `--verbose`.\n *\n * @returns The exit code the failure maps to\n */\nfunction reportFailure(\n logger: Logger,\n error: unknown,\n verbose: boolean,\n): number {\n if (error instanceof GeneratorError) {\n logger.error(error.message);\n if (verbose && error.cause !== undefined) {\n logger.error('Caused by:', error.cause);\n }\n return error.exitCode;\n }\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Code generation failed: ${message}`);\n if (verbose) {\n logger.error('', error);\n } else {\n logger.error(\n 'Rerun with --verbose for the stack trace, and report it at https://github.com/Ahoo-Wang/Wow/issues if the input is valid.',\n );\n }\n return EXIT_CODES.internal;\n}\n\n/**\n * Runs the `generate` command.\n *\n * @param options - The parsed command options\n * @param logger - Where to report; a console logger at the level the options ask for by default\n * @param seams - What the package hands the generator beyond the options;\n * a run stopped by the {@link SIGNAL_SEAM} exits with\n * {@link EXIT_CODES.interrupted}\n * @returns The exit code: see {@link EXIT_CODES}\n */\nexport async function runGenerate(\n options: GenerateCommandOptions,\n logger: Logger = new ConsoleLogger({ level: logLevel(options) }),\n seams: Seams = {},\n): Promise<number> {\n if (!validateInput(options.input)) {\n logger.error(\n `Invalid input \"${options.input}\": expected a file path or an http(s) URL.`,\n );\n return EXIT_CODES.input;\n }\n try {\n logger.debug(`wow-generator v${VERSION}`);\n const generatorOptions: SeamOptions = {\n ...seams,\n inputPath: options.input,\n outputDir: options.output,\n configPath: options.config,\n tsConfigFilePath: options.tsConfigFilePath,\n headers: parseHeaders(options.header),\n timeoutMs: parseTimeout(options.timeout),\n schemaDocs: parseSchemaDocs(options.schemaDocs),\n logger,\n };\n const result = await new CodeGenerator(generatorOptions).generate();\n const warnings = result.warnings\n ? `, ${result.warnings} warning${result.warnings === 1 ? '' : 's'}`\n : '';\n const config = result.configPath\n ? ` with ${relative(process.cwd(), result.configPath) || result.configPath}`\n : '';\n logger.info(\n `Generated ${result.files.length} files into ${options.output}${config}${warnings}`,\n );\n if (options.strict && result.warnings > 0) {\n logger.error(\n `--strict: the run logged ${result.warnings} warning${result.warnings === 1 ? '' : 's'}.`,\n );\n return EXIT_CODES.specification;\n }\n return EXIT_CODES.success;\n } catch (error) {\n if (seams[SIGNAL_SEAM]?.aborted) return EXIT_CODES.interrupted;\n return reportFailure(logger, error, !!options.verbose);\n }\n}\n\n/**\n * Action handler for the generate command: runs it and sets the process exit\n * code.\n *\n * Ctrl-C stops the run at its next step and exits with\n * {@link EXIT_CODES.interrupted}. A run that has begun writing finishes\n * writing its files, then stops: it removes no stale file and leaves the\n * manifest as the last complete run wrote it, so the manifest never records\n * a run that did not finish. A second Ctrl-C ends the process at once.\n *\n * @param options - Command options\n */\nexport async function generateAction(options: GenerateCommandOptions) {\n const interruption = new AbortController();\n process.once('SIGINT', () => {\n console.error('Generation interrupted by user');\n interruption.abort();\n });\n process.exitCode = await runGenerate(options, undefined, {\n [SIGNAL_SEAM]: interruption.signal,\n });\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Command } from 'commander';\nimport { CommanderError, program } from 'commander';\nimport { VERSION } from '../version';\nimport { DEFAULT_CONFIG_PATH } from '../api/configuration';\nimport { EXIT_CODES } from '../api/errors';\nimport { DEFAULT_HTTP_TIMEOUT_MS } from '../input/resources';\nimport { generateAction } from './runGenerate';\n\n/** The exit codes `generate --help` lists, as the README's table does. */\nexport const EXIT_CODE_HELP = `\nExit codes:\n ${EXIT_CODES.success} generated; or --help, help or --version printed\n ${EXIT_CODES.internal} internal error; rerun with --verbose for the stack trace\n ${EXIT_CODES.input} input or usage: unreadable, unfetchable or not OpenAPI 3.x; an invalid option\n ${EXIT_CODES.configuration} configuration: cannot be read, parsed or validated\n ${EXIT_CODES.specification} specification: cannot be generated, or --strict and the run had warnings\n ${EXIT_CODES.output} output: the manifest, a path outside the output, or a failed write\n ${EXIT_CODES.interrupted} interrupted (Ctrl-C)`;\n\n/** Collects the values of an option given more than once, such as `--header`. */\nexport function collect(value: string, previous: string[] = []): string[] {\n return [...previous, value];\n}\n\n/**\n * Sets up the CLI program with all commands and options.\n *\n * Commander does not exit the process: a usage error (a missing required\n * option, an unknown option or command, a missing argument, no command at\n * all) is thrown as a `CommanderError`, which {@link runCLI} maps to an exit\n * code.\n *\n * @param target - The program to set up; commander's global one by default.\n * Settings made on it before this call, such as `configureOutput`, reach the\n * `generate` command too.\n * @returns The configured commander program instance\n */\nexport function setupCLI(target: Command = program): Command {\n // Before `command()`: a subcommand copies the exit override when it is\n // created.\n target.exitOverride();\n target\n .name('wow-generator')\n .description(\n 'TypeScript client generator for Wow: from a Wow Manifest or an OpenAPI 3 document',\n )\n .version(VERSION, '-v, --version');\n\n target\n .command('generate')\n .description(\n 'Generate TypeScript code from a Wow Manifest or an OpenAPI 3 document',\n )\n .requiredOption(\n '-i, --input <file>',\n 'Input OpenAPI specification or Wow Manifest (GET /wow/manifest) file path or URL (http/https)',\n )\n .option('-o, --output <path>', 'Output directory path', 'src/generated')\n // No commander default: an omitted -c falls back to DEFAULT_CONFIG_PATH,\n // which may be absent, while a path the user named has to exist.\n .option(\n '-c, --config <file>',\n `Configuration file path (default: ${DEFAULT_CONFIG_PATH})`,\n )\n .option(\n '-t, --ts-config-file-path <file>',\n 'TypeScript configuration file path',\n )\n .option(\n '-H, --header <header>',\n 'Request header for an http(s) input or configuration, as \"Name: value\"; repeatable',\n collect,\n )\n .option(\n '--timeout <ms>',\n `Milliseconds before fetching an http(s) input is abandoned (default: ${DEFAULT_HTTP_TIMEOUT_MS})`,\n )\n .option(\n '--schema-docs <mode>',\n 'What model doc comments carry: \"summary\" (title, description, constraints) or \"full\" (also the JSON schema)',\n 'summary',\n )\n .option('--strict', 'Exit with code 4 when the run logs a warning')\n .option('--verbose', 'Log every step, and the stack trace of a failure')\n .option('--quiet', 'Log only warnings and errors')\n .addHelpText('after', EXIT_CODE_HELP)\n .action(generateAction);\n\n return target;\n}\n\n/**\n * The exit code of a command line commander stopped at: 0 for `--help`,\n * `help` and `--version`; {@link EXIT_CODES.input} for a usage error, which\n * commander has already reported. A usage error is an invalid command line,\n * the same category as an invalid option value such as `--timeout abc`.\n */\nexport function commanderExitCode(error: CommanderError): number {\n return error.exitCode === 0 ? EXIT_CODES.success : EXIT_CODES.input;\n}\n\n/**\n * Parses the command line and runs the command it names. The `generate`\n * command sets the process exit code itself; a command line commander stops\n * at sets it to {@link commanderExitCode}.\n *\n * @param args - The arguments after the executable and script;\n * `process.argv` by default\n * @param target - The program to run; {@link setupCLI} on commander's global\n * one by default\n */\nexport async function runCLI(\n args?: readonly string[],\n target: Command = setupCLI(),\n): Promise<void> {\n try {\n if (args === undefined) {\n await target.parseAsync();\n } else {\n await target.parseAsync(args, { from: 'user' });\n }\n } catch (error) {\n if (!(error instanceof CommanderError)) throw error;\n process.exitCode = commanderExitCode(error);\n }\n}\n","#!/usr/bin/env node\n\n/**\n * CLI entry point of wow-generator: runs the program `cli/program.ts` sets\n * up on the process's command line.\n */\n\nimport { runCLI } from './cli/program';\n\nexport { collect, runCLI, setupCLI } from './cli/program';\n\nvoid runCLI();\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"cli.cjs","names":["GeneratorError","EXIT_CODES","ConsoleLogger","CodeGenerator","relative","SIGNAL_SEAM","EXIT_CODES","program","DEFAULT_CONFIG_PATH","DEFAULT_HTTP_TIMEOUT_MS","CommanderError","require_codeGenerator","path","commander","VERSION","validateInput","input","url","parseHeaders","parsed","header","headers","separator","name","parseTimeout","timeout","value","parseSchemaDocs","schemaDocs","logLevel","options","reportFailure","error","logger","verbose","message","runGenerate","generatorOptions","seams","result","warnings","config","generateAction","interruption","EXIT_CODE_HELP","collect","previous","setupCLI","target","commanderExitCode","runCLI","args"],"sources":["../src/version.ts","../src/cli/runGenerate.ts","../src/cli/program.ts","../src/cli.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Replaced at build time with the `version` of this package's package.json\n// (`define` in vite.config.ts, which Vitest shares), so only the version string\n// reaches dist, not the manifest with its dependencies and workspace ranges.\ndeclare const __WOW_GENERATOR_VERSION__: string;\n\n/** The version of this package, as its package.json named it at build time. */\nexport const VERSION: string = __WOW_GENERATOR_VERSION__;\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { relative } from 'path';\nimport { VERSION } from '../version';\nimport { EXIT_CODES, GeneratorError } from '../api/errors';\nimport { CodeGenerator } from '../pipeline/codeGenerator';\nimport type { Logger, LogLevel } from '../api/logger';\nimport { ConsoleLogger } from '../api/logger';\nimport type { SchemaDocs } from '../api/options';\nimport type { SeamOptions, Seams } from '../pipeline/seams';\nimport { SIGNAL_SEAM } from '../pipeline/seams';\n\n/**\n * Options of the `generate` command, as commander parses them.\n */\nexport interface GenerateCommandOptions {\n input: string;\n output: string;\n config?: string;\n tsConfigFilePath?: string;\n /** `Name: value` request headers for an http(s) input or configuration. */\n header?: string[];\n /** Milliseconds, as typed on the command line. */\n timeout?: string;\n /** `summary` or `full`. */\n schemaDocs?: string;\n /** Exit with a non-zero code when the run logged a warning. */\n strict?: boolean;\n verbose?: boolean;\n quiet?: boolean;\n}\n\n/**\n * Validates the input path or URL.\n *\n * Any file path is accepted here and checked when it is read. A URL must use\n * http or https; its host is not restricted, because the generator runs on\n * the developer's own machine against a document they chose, and fetching an\n * intranet service's `/v3/api-docs` is the common case.\n *\n * @param input - Input path or URL\n * @returns true if valid\n */\nexport function validateInput(input: string): boolean {\n if (!input) return false;\n let url: URL;\n try {\n url = new URL(input);\n } catch {\n // Not a URL: a file path, which parseOpenAPI reads.\n return true;\n }\n // A Windows path such as C:\\spec.json parses as a URL with scheme \"c:\".\n if (/^[a-z]:$/i.test(url.protocol)) return true;\n return url.protocol === 'http:' || url.protocol === 'https:';\n}\n\n/**\n * Parses `Name: value` header arguments.\n *\n * @param headers - The raw `--header` values\n * @returns The headers by name\n * @throws GeneratorError of kind `input` for a value without a name\n */\nexport function parseHeaders(\n headers: readonly string[] = [],\n): Record<string, string> {\n const parsed: Record<string, string> = {};\n for (const header of headers) {\n const separator = header.indexOf(':');\n const name = separator > 0 ? header.slice(0, separator).trim() : '';\n if (!name) {\n throw new GeneratorError(\n 'input',\n `Invalid --header \"${header}\": expected \"Name: value\".`,\n );\n }\n parsed[name] = header.slice(separator + 1).trim();\n }\n return parsed;\n}\n\nfunction parseTimeout(timeout: string | undefined): number | undefined {\n if (timeout === undefined) return undefined;\n const value = Number(timeout);\n if (!Number.isInteger(value) || value <= 0) {\n throw new GeneratorError(\n 'input',\n `Invalid --timeout \"${timeout}\": expected a positive number of milliseconds.`,\n );\n }\n return value;\n}\n\nfunction parseSchemaDocs(schemaDocs: string | undefined): SchemaDocs {\n if (schemaDocs === undefined || schemaDocs === 'summary') return 'summary';\n if (schemaDocs === 'full') return 'full';\n throw new GeneratorError(\n 'input',\n `Invalid --schema-docs \"${schemaDocs}\": expected \"summary\" or \"full\".`,\n );\n}\n\nfunction logLevel(options: GenerateCommandOptions): LogLevel {\n if (options.verbose) return 'verbose';\n if (options.quiet) return 'quiet';\n return 'normal';\n}\n\n/**\n * Reports a failure as one actionable line; the stack and the causes only\n * with `--verbose`.\n *\n * @returns The exit code the failure maps to\n */\nfunction reportFailure(\n logger: Logger,\n error: unknown,\n verbose: boolean,\n): number {\n if (error instanceof GeneratorError) {\n logger.error(error.message);\n if (verbose && error.cause !== undefined) {\n logger.error('Caused by:', error.cause);\n }\n return error.exitCode;\n }\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Code generation failed: ${message}`);\n if (verbose) {\n logger.error('', error);\n } else {\n logger.error(\n 'Rerun with --verbose for the stack trace, and report it at https://github.com/Ahoo-Wang/Wow/issues if the input is valid.',\n );\n }\n return EXIT_CODES.internal;\n}\n\n/**\n * Runs the `generate` command.\n *\n * @param options - The parsed command options\n * @param logger - Where to report; a console logger at the level the options ask for by default\n * @param seams - What the package hands the generator beyond the options;\n * a run stopped by the {@link SIGNAL_SEAM} exits with\n * {@link EXIT_CODES.interrupted}\n * @returns The exit code: see {@link EXIT_CODES}\n */\nexport async function runGenerate(\n options: GenerateCommandOptions,\n logger: Logger = new ConsoleLogger({ level: logLevel(options) }),\n seams: Seams = {},\n): Promise<number> {\n if (!validateInput(options.input)) {\n logger.error(\n `Invalid input \"${options.input}\": expected a file path or an http(s) URL.`,\n );\n return EXIT_CODES.input;\n }\n try {\n logger.debug(`wow-generator v${VERSION}`);\n const generatorOptions: SeamOptions = {\n ...seams,\n inputPath: options.input,\n outputDir: options.output,\n configPath: options.config,\n tsConfigFilePath: options.tsConfigFilePath,\n headers: parseHeaders(options.header),\n timeoutMs: parseTimeout(options.timeout),\n schemaDocs: parseSchemaDocs(options.schemaDocs),\n logger,\n };\n const result = await new CodeGenerator(generatorOptions).generate();\n const warnings = result.warnings\n ? `, ${result.warnings} warning${result.warnings === 1 ? '' : 's'}`\n : '';\n const config = result.configPath\n ? ` with ${relative(process.cwd(), result.configPath) || result.configPath}`\n : '';\n logger.info(\n `Generated ${result.files.length} files into ${options.output}${config}${warnings}`,\n );\n if (options.strict && result.warnings > 0) {\n logger.error(\n `--strict: the run logged ${result.warnings} warning${result.warnings === 1 ? '' : 's'}.`,\n );\n return EXIT_CODES.specification;\n }\n return EXIT_CODES.success;\n } catch (error) {\n if (seams[SIGNAL_SEAM]?.aborted) return EXIT_CODES.interrupted;\n return reportFailure(logger, error, !!options.verbose);\n }\n}\n\n/**\n * Action handler for the generate command: runs it and sets the process exit\n * code.\n *\n * Ctrl-C stops the run at its next step and exits with\n * {@link EXIT_CODES.interrupted}. A run that has begun writing finishes\n * writing its files, then stops: it removes no stale file and leaves the\n * manifest as the last complete run wrote it, so the manifest never records\n * a run that did not finish. A second Ctrl-C ends the process at once.\n *\n * @param options - Command options\n */\nexport async function generateAction(options: GenerateCommandOptions) {\n const interruption = new AbortController();\n process.once('SIGINT', () => {\n console.error('Generation interrupted by user');\n interruption.abort();\n });\n process.exitCode = await runGenerate(options, undefined, {\n [SIGNAL_SEAM]: interruption.signal,\n });\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Command } from 'commander';\nimport { CommanderError, program } from 'commander';\nimport { VERSION } from '../version';\nimport { DEFAULT_CONFIG_PATH } from '../api/configuration';\nimport { EXIT_CODES } from '../api/errors';\nimport { DEFAULT_HTTP_TIMEOUT_MS } from '../input/resources';\nimport { generateAction } from './runGenerate';\n\n/** The exit codes `generate --help` lists, as the README's table does. */\nexport const EXIT_CODE_HELP = `\nExit codes:\n ${EXIT_CODES.success} generated; or --help, help or --version printed\n ${EXIT_CODES.internal} internal error; rerun with --verbose for the stack trace\n ${EXIT_CODES.input} input or usage: unreadable, unfetchable or not OpenAPI 3.x; an invalid option\n ${EXIT_CODES.configuration} configuration: cannot be read, parsed or validated\n ${EXIT_CODES.specification} specification: cannot be generated, or --strict and the run had warnings\n ${EXIT_CODES.output} output: the manifest, a path outside the output, or a failed write\n ${EXIT_CODES.interrupted} interrupted (Ctrl-C)`;\n\n/** Collects the values of an option given more than once, such as `--header`. */\nexport function collect(value: string, previous: string[] = []): string[] {\n return [...previous, value];\n}\n\n/**\n * Sets up the CLI program with all commands and options.\n *\n * Commander does not exit the process: a usage error (a missing required\n * option, an unknown option or command, a missing argument, no command at\n * all) is thrown as a `CommanderError`, which {@link runCLI} maps to an exit\n * code.\n *\n * @param target - The program to set up; commander's global one by default.\n * Settings made on it before this call, such as `configureOutput`, reach the\n * `generate` command too.\n * @returns The configured commander program instance\n */\nexport function setupCLI(target: Command = program): Command {\n // Before `command()`: a subcommand copies the exit override when it is\n // created.\n target.exitOverride();\n target\n .name('wow-generator')\n .description(\n 'TypeScript client generator for Wow: from a Wow Manifest or an OpenAPI 3 document',\n )\n .version(VERSION, '-v, --version');\n\n target\n .command('generate')\n .description(\n 'Generate TypeScript code from a Wow Manifest or an OpenAPI 3 document',\n )\n .requiredOption(\n '-i, --input <file>',\n 'Input OpenAPI specification or Wow Manifest (GET /wow/manifest) file path or URL (http/https)',\n )\n .option('-o, --output <path>', 'Output directory path', 'src/generated')\n // No commander default: an omitted -c falls back to DEFAULT_CONFIG_PATH,\n // which may be absent, while a path the user named has to exist.\n .option(\n '-c, --config <file>',\n `Configuration file path (default: ${DEFAULT_CONFIG_PATH})`,\n )\n .option(\n '-t, --ts-config-file-path <file>',\n 'TypeScript configuration file path',\n )\n .option(\n '-H, --header <header>',\n 'Request header for an http(s) input or configuration, as \"Name: value\"; repeatable',\n collect,\n )\n .option(\n '--timeout <ms>',\n `Milliseconds before fetching an http(s) input is abandoned (default: ${DEFAULT_HTTP_TIMEOUT_MS})`,\n )\n .option(\n '--schema-docs <mode>',\n 'What model doc comments carry: \"summary\" (title, description, constraints) or \"full\" (also the JSON schema)',\n 'summary',\n )\n .option('--strict', 'Exit with code 4 when the run logs a warning')\n .option('--verbose', 'Log every step, and the stack trace of a failure')\n .option('--quiet', 'Log only warnings and errors')\n .addHelpText('after', EXIT_CODE_HELP)\n .action(generateAction);\n\n return target;\n}\n\n/**\n * The exit code of a command line commander stopped at: 0 for `--help`,\n * `help` and `--version`; {@link EXIT_CODES.input} for a usage error, which\n * commander has already reported. A usage error is an invalid command line,\n * the same category as an invalid option value such as `--timeout abc`.\n */\nexport function commanderExitCode(error: CommanderError): number {\n return error.exitCode === 0 ? EXIT_CODES.success : EXIT_CODES.input;\n}\n\n/**\n * Parses the command line and runs the command it names. The `generate`\n * command sets the process exit code itself; a command line commander stops\n * at sets it to {@link commanderExitCode}.\n *\n * @param args - The arguments after the executable and script;\n * `process.argv` by default\n * @param target - The program to run; {@link setupCLI} on commander's global\n * one by default\n */\nexport async function runCLI(\n args?: readonly string[],\n target: Command = setupCLI(),\n): Promise<void> {\n try {\n if (args === undefined) {\n await target.parseAsync();\n } else {\n await target.parseAsync(args, { from: 'user' });\n }\n } catch (error) {\n if (!(error instanceof CommanderError)) throw error;\n process.exitCode = commanderExitCode(error);\n }\n}\n","#!/usr/bin/env node\n\n/**\n * CLI entry point of wow-generator: runs the program `cli/program.ts` sets\n * up on the process's command line.\n */\n\nimport { runCLI } from './cli/program';\n\nexport { collect, runCLI, setupCLI } from './cli/program';\n\nvoid runCLI();\n"],"mappings":"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"}
|
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { c as e, i as t, n, o as r, r as i, s as a, t as o } from "./codeGenerator-
|
|
2
|
+
import { c as e, i as t, n, o as r, r as i, s as a, t as o } from "./codeGenerator-Cxlr_VOh.js";
|
|
3
3
|
import { relative as s } from "path";
|
|
4
4
|
import { CommanderError as c, program as l } from "commander";
|
|
5
5
|
// src/version.ts
|
|
6
|
-
var u = "10.0.0-
|
|
6
|
+
var u = "10.0.0-beta.1";
|
|
7
7
|
// src/cli/runGenerate.ts
|
|
8
8
|
function d(e) {
|
|
9
9
|
if (!e) return !1;
|
|
@@ -1,37 +1,37 @@
|
|
|
1
|
-
let e=require("ts-morph"),t=require("path"),n=require("yaml"),r=require("fs"),i=require("node:path");var a=`./wow-generator.config.json`,o={success:0,internal:1,input:2,configuration:3,specification:4,output:5,interrupted:130},s=class extends Error{kind;constructor(e,t,n){super(t,n),this.kind=e,this.name=`GeneratorError`}get exitCode(){return o[this.kind]}};function c(e){return e instanceof Error?e.message:String(e)}function l(){return!!process.stdout?.isTTY&&!process.env.NO_COLOR}var u=class{level;decorate;constructor(e={}){this.level=e.level??`normal`,this.decorate=e.decorate??l()}format(e,t,n){let r=this.decorate?`${e} `:t?`${t}: `:``;return`${this.level===`verbose`?`[${new Date().toTimeString().slice(0,8)}] `:``}${r}${n}`}debug(e,...t){this.level===`verbose`&&console.log(this.format(`ℹ️ `,``,e),...t)}info(e,...t){this.level!==`quiet`&&console.log(this.format(`✅`,``,e),...t)}warn(e,...t){console.warn(this.format(`⚠️ `,`warning`,e),...t)}error(e,...t){console.error(this.format(`❌`,`error`,e),...t)}},d=class{debug(){}info(){}warn(){}error(){}};function f(e,t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:t?`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`:e}var p=`types.ts`;function m(e){return f(e.path,p)}function h(e){return!!(e&&typeof e==`object`&&`$ref`in e)}function g(e,t){let n=t.slice(1);try{n=decodeURIComponent(n)}catch{}if(n===``)return e;let r=e;for(let e of n.slice(1).split(`/`)){if(typeof r!=`object`||!r)return;let t=e.replace(/~1/g,`/`).replace(/~0/g,`~`);if(!Object.hasOwn(r,t))return;r=r[t]}return r}function ee(e){let t=[],n=new Set,r=(i,a)=>{if(typeof i!=`object`||!i||n.has(i))return;if(n.add(i),Array.isArray(i)){i.forEach((e,t)=>r(e,`${a}/${t}`));return}let o=i.$ref;typeof o==`string`&&o.startsWith(`#/components/`)&&g(e,o)===void 0&&t.push({ref:o,location:a||`/`});for(let[e,t]of Object.entries(i))r(t,`${a}/${e.replace(/~/g,`~0`).replace(/\//g,`~1`)}`)};return r(e,``),t}var _=`#/components/`,te=`${_}parameters/`,ne=`${_}requestBodies/`,re=`${_}responses/`,ie=`${_}schemas/`;function ae(e){return e.$ref.split(`/`).pop()}function v(e,t,n){let r=new Set,i=e;for(;h(i);){if(!i.$ref.startsWith(n))return;if(r.has(i.$ref))throw new s(`specification`,`Cyclic component reference: ${i.$ref}`);r.add(i.$ref),i=t?.[i.$ref.slice(n.length)]}return i}function y(e,t){return v(e,t.schemas,ie)}function oe(e,t){return v(e,t.responses,re)}function se(e,t){return v(e,t.requestBodies,ne)}function ce(e,t){return v(e,t.parameters,te)}var le=new Intl.Collator(`en-US`);function b(e,t){return le.compare(e,t)}var ue=`application/json`,de=`text/event-stream`;function fe(e){return e.split(`;`)[0].trim().toLowerCase()}function pe(e){let t=fe(e);return t===`application/json`||/^application\/[^/]+\+json$/.test(t)}function me(e){let t=fe(e);return t.startsWith(`text/`)&&t!==`text/event-stream`}function x(e,t,n=e=>fe(e)===t){if(!e)return;if(e[t])return e[t];let r=Object.keys(e).find(n);return r===void 0?void 0:e[r]}function he(e,t){if(t&&!h(t))return x(t.content,e)?.schema}function ge(e){if(e&&!h(e))return x(e.content,ue,pe)?.schema}function _e(e){return he(de,e)}function ve(e){return he(`*/*`,e)}function ye(e){return!e||h(e)?!1:Object.keys(e.content??{}).some(me)}function S(e){return Array.isArray(e.enum)&&e.enum.length>0}var be=`x-enum-text`;function xe(e){return e[be]}function Se(e){return e.type===`object`&&!!e.properties}function Ce(e){return e.type===`array`&&!!e.items}function we(e){return Array.isArray(e.anyOf)&&e.anyOf.length>0}function Te(e){return Array.isArray(e.oneOf)&&e.oneOf.length>0}function Ee(e){return Array.isArray(e.allOf)&&e.allOf.length>0}function C(e){return we(e)||Te(e)||Ee(e)}function De(e){return e.includes(`|`)||e.includes(`&`)?`(${e})[]`:`${e}[]`}function Oe(e){return e.type===`object`&&!e.properties&&e.additionalProperties!==void 0}var ke=`x-map-key-schema`;function Ae(e){return e[ke]}function je(e){return e.readOnly===!0}function Me(e){if(Array.isArray(e))return e.map(e=>Me(e)).join(` | `);switch(e){case`string`:return`string`;case`number`:case`integer`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;default:return`any`}}function Ne(e,t){let n=[],r=new Set,i=new Set,a=!1,o=e=>{if(!(!e||i.has(e)||a)){if(i.add(e),h(e))o(t&&y(e,t));else if(e.nullable||Array.isArray(e.type))a=!0;else{for(let t of e.required??[])r.add(t);for(let t of Object.keys(e.properties??{}))n.includes(t)||n.push(t);e.allOf?.forEach(o)}}};return o(e),a?[]:n.filter(e=>!r.has(e))}function Pe(e,t){return e.operation.operationId&&t.operation.operationId?b(e.operation.operationId,t.operation.operationId):e.path&&t.path?b(e.path,t.path):e.method&&t.method?b(e.method,t.method):0}function Fe(e,t,n){let r=new Map;for(let i of[...e,...t]){let e=h(i)?n&&ce(i,n):i,t=e?`${e.in}:${e.name}`:i.$ref;r.set(t,i)}return[...r.values()]}function Ie(e,t){let n=[];for(let[r,i]of Object.entries(e))Le(i).forEach(e=>{n.push({method:e.method,operation:i.parameters?.length?{...e.operation,parameters:Fe(i.parameters,e.operation.parameters??[],t)}:e.operation,path:r})});return n.sort(Pe)}function Le(e){return[{method:`get`,operation:e.get},{method:`put`,operation:e.put},{method:`post`,operation:e.post},{method:`delete`,operation:e.delete},{method:`options`,operation:e.options},{method:`head`,operation:e.head},{method:`patch`,operation:e.patch},{method:`trace`,operation:e.trace}].filter(({operation:e})=>e!==void 0)}function Re(e){let t=Object.keys(e.responses??{});if(t.includes(`200`))return`200`;let n=t.filter(e=>/^2\d\d$/.test(e)).sort();return n.length>0?n[0]:t.find(e=>e.toUpperCase()===`2XX`)}function ze(e,t){let n=Re(e),r=n?e.responses[n]:void 0;return t&&h(r)?oe(r,t):r}function Be(e,t){return(e.parameters??[]).map(e=>h(e)?ce(e,t):e).filter(e=>e!==void 0)}function Ve(e,t){let n=t=>{let n=e.indexOf(`{${t.name}}`);return n<0?2**53-1:n};return[...t].sort((e,t)=>n(e)-n(t))}var He=/[^\p{L}\p{N}$]+/u,Ue=new Set(`arguments.await.break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.eval.export.extends.false.finally.for.function.if.implements.import.in.instanceof.interface.let.new.null.package.private.protected.public.return.static.super.switch.this.throw.true.try.typeof.var.void.while.with.yield`.split(`.`));function w(e){return/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u.test(e)&&!Ue.has(e)}function We(e){return/^\p{N}/u.test(e)?`_${e}`:e}function T(e){if(w(e))return e;let t=We(O(e)||`_`);return Ue.has(t)?`${t}_`:t}function Ge(e){return/^\p{Lu}[\p{L}\p{N}$]*$/u.test(e)&&w(e)}function E(e){return We((Array.isArray(e)?e:[e]).map(e=>Ge(e)?e:D(e)).join(``)||`_`)}function Ke(e){return e.split(He)}function qe(e){return Array.isArray(e)?e.flatMap(e=>Je(Ke(e))):Je(Ke(e))}function Je(e){return e.flatMap(e=>{if(e.length===0)return[];let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=/[A-Z]/.test(i),o=r>0&&/[a-z]/.test(e[r-1]);a&&o&&n?(t.push(n),n=i):n+=i}return n&&t.push(n),t})}function D(e){return e===``||e.length===0?``:qe(e).filter(e=>e.length>0).map(e=>{let t=e.charAt(0),n=e.slice(1);return(/[a-zA-Z]/.test(t)?t.toUpperCase():t)+n.toLowerCase()}).join(``)}function O(e){let t=D(e);return t.charAt(0).toLowerCase()+t.slice(1)}function k(e){return e===``||Array.isArray(e)&&e.length===0?``:qe(e).filter(e=>e.length>0).map(e=>e.toUpperCase()).join(`_`)}function A(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:j(e)}function Ye(e){return/^\d+$/.test(e)?`NUM_${e}`:k(e)||e}function j(e){return`'${JSON.stringify(e).slice(1,-1).replace(/\\"/g,`"`).replace(/'/g,`\\'`)}'`}var Xe=`x-fetcher-method`;function Ze(e,t){let n=t??e[`x-fetcher-method`];if(n!==void 0){if(typeof n!=`string`||!Qe(n))throw new s(`specification`,`${Xe} of ${e.operationId??`an operation`} is ${JSON.stringify(n)}, which is not a valid method name.`);return n}if(!e.operationId)return;let r=O(e.operationId.split(`.`).pop())||`_`;return/^\p{N}/u.test(r)?`_${r}`:r}function Qe(e){return w(e)||/^[a-z]+$/.test(e)}function $e(e,t){let n=T(e),r=n;for(let e=2;t.has(r);e++)r=`${n}${e}`;return t.add(r),r}function M(e){if(!e)return{name:``,path:`/`};let t=e.split(`.`),n=-1;for(let e=0;e<t.length;e++)if(t[e]&&/^[A-Z]/.test(t[e])){n=e;break}let r=t.slice(0,n),i=r.length>0?`/${r.join(`/`)}`:`/`;return{name:E(t.slice(n)),path:i}}function et(e,t){if(!e.$ref.startsWith(`#/components/schemas/`))throw new s(`specification`,`Unsupported schema reference: ${e.$ref}. Bundle or inline external schemas before generation.`);return t&&y(e,t),M(ae(e))}var tt=[`httpRequest`,`attributes`];function nt(e,t,n){return new rt(e,t,n).clients()}var rt=class{document;config;warnings;constructor(e,t,n){this.document=e,this.config=t,this.warnings=n}clients(){let e=this.tags(),t=this.groupOperations(),n=new Map;return[...t.keys()].sort().map(r=>{let i=M(r),a=i;for(let e=2;n.has(N(a));e++)a={...i,name:`${i.name}${e}`};return a!==i&&this.warnings.push(`Tags ${n.get(N(i))} and ${r} both name the API client ${i.name}ApiClient; ${r} generates ${a.name}ApiClient.`),n.set(N(a),r),this.client(e.get(r),a,[...t.get(r)])})}client(e,t,n){let r=`${t.name}ApiClient`,i=f(t.path,it(r)),a=new Map;return{tagName:e.name,className:r,file:i,description:e.description,methods:n.map(t=>this.method(e,r,t,a))}}method(e,t,n,r){let{operation:i}=n,a=this.methodName(e,t,n,r),o=new Set(tt),s=this.parameters(e,n,o),c=this.body(i,o),l=[...s.filter(({parameter:e})=>e.required),...s.filter(({parameter:e})=>!e.required)].filter(({description:e})=>e);return{name:a,httpMethod:n.method,path:n.path,parameters:s.map(({parameter:e})=>e),body:c,returns:this.returns(i),docs:[i.summary,i.description,`- operationId: \`${i.operationId}\``,`- path: \`${n.path}\``,...l.map(({parameter:e,description:t})=>`@param ${e.name} - ${t.replace(/\s*\n\s*/g,` `)}`)]}}methodName(e,t,n,r){let i=n.operation.operationId,a=Ze(n.operation,this.config.apiClients?.[e.name]?.methodNames?.[i]),o=r.get(a);if(o!==void 0)throw new s(`specification`,`Operations ${o} and ${i} of tag ${e.name} both generate the method ${t}.${a}(). Name one of them with apiClients["${e.name}"].methodNames in the generator configuration, or with the x-fetcher-method extension.`);return r.set(a,i),a}parameters(e,t,n){let r=Be(t.operation,this.document.components??{}),i=[];for(let a of[`path`,`query`,`header`]){let o=r.filter(e=>e.in===a);for(let r of a===`path`?Ve(t.path,o):o)a===`path`&&this.ignoresPathParameter(e.name,r.name)||i.push({parameter:{name:$e(r.name,n),location:a,parameterName:r.name,schema:r.schema,required:a===`path`||r.required===!0},description:r.description})}let a=r.filter(e=>e.in===`cookie`);return a.length>0&&this.warnings.push(`${t.method.toUpperCase()} ${t.path} leaves out its cookie parameter(s) ${a.map(e=>e.name).join(`, `)}: the browser sends cookies, and fetch cannot set them.`),i}ignoresPathParameter(e,t){return(this.config.apiClients?.[e]?.ignorePathParameters)?.includes(t)??!1}body(e,t){if(!e.requestBody)return;let n=h(e.requestBody)?se(e.requestBody,this.document.components):e.requestBody;if(!n)return;let r=n.required===!0,i=n.content??{},a=x(i,ue,pe),o=$e(`body`,t);return a?.schema?{name:o,required:r,content:{kind:`json`,schema:a.schema,optionalFields:Ne(a.schema,this.document.components)}}:x(i,`multipart/form-data`)?{name:o,required:r,content:{kind:`formData`}}:x(i,`application/x-www-form-urlencoded`)?{name:o,required:r,content:{kind:`urlEncoded`}}:Object.keys(i).some(me)?{name:o,required:r,content:{kind:`text`}}:{name:o,required:r,content:{kind:`binary`}}}returns(e){let t=ze(e,this.document.components);if(!t)return{kind:`response`};let n=ge(t),r=n||ve(t);if(r)return{kind:`json`,schema:r,wildcard:!n};let i=_e(t);if(i){if(h(i)){let e=y(i,this.document.components);if(Ce(e)&&h(e.items)){let t=et(e.items,this.document.components);return{kind:`eventStream`,items:e.items,serverSentEvent:t.name.includes(`ServerSentEvent`)}}}return{kind:`eventStream`,serverSentEvent:!1}}return ye(t)?{kind:`text`}:{kind:`response`}}groupOperations(){let e=new Map;for(let t of this.document.endpoints){let n=`${t.method.toUpperCase()} ${t.path}`,r=t.operation.tags??[];if(r.length===0)this.warnings.push(`Skipping ${n}: it has no tag, and the tag names its API client.`);else if(!t.operation.operationId)this.warnings.push(`Skipping ${n}: it has no operationId, and the operationId names its method.`);else for(let n of r)e.has(n)||e.set(n,new Set),e.get(n).add(t)}return e}tags(){let e=new Map;for(let{operation:t}of this.document.endpoints)t.tags?.forEach(t=>{e.has(t)||e.set(t,{name:t,description:``})});return this.document.openAPI.tags?.forEach(t=>e.set(t.name,t)),e}};function it(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}.ts`}function N(e){return`${e.path}/${e.name}`.toLowerCase()}function at(e){let t=e.components?.schemas;if(!t)return[];let n=Object.keys(t);return ot(n),n.map(e=>{let n=t[e],r=M(e);return{key:e,info:r,file:m(r),schema:n}})}function ot(e){let t=new Map;for(let n of e){let e=M(n),r=`${e.path===`/`?``:e.path}/${e.name}`;t.set(r,[...t.get(r)??[],n])}let n=[...t].filter(([,e])=>e.length>1);if(n.length!==0)throw new s(`specification`,`Schemas generate the same model: ${n.map(([e,t])=>`${t.join(`, `)} → ${e}`).join(`; `)}. Rename all but one of them in the document.`)}function st(e,t){let n=[];return{model:{models:at(e),apiClients:nt(e,t,n)},warnings:n}}var ct=class{declarations=new Map;add(e,t){let n=this.declarations.get(e);n||(n=[],this.declarations.set(e,n));for(let e of t)n.some(t=>t.name===e)||n.push({name:e});return n}apply(e){for(let{moduleSpecifier:t,name:n,alias:r}of e){let e=this.add(t,[n]).find(e=>e.name===n);r!==void 0&&(e.alias=r)}}entries(){return[...this.declarations].flatMap(([e,t])=>t.map(({name:t,alias:n})=>n===void 0?{moduleSpecifier:e,name:t}:{moduleSpecifier:e,name:t,alias:n}))}localNames(e){return[...this.declarations.values()].flat().filter(t=>t!==e).map(e=>e.alias??e.name)}structures(){return[...this.declarations].map(([e,t])=>({moduleSpecifier:e,namedImports:t.map(({name:e,alias:t})=>t===void 0?e:{name:e,alias:t})}))}},lt=class{sourceFile;imports=new ct;statements=[];constructor(e){this.sourceFile=e}get directoryPath(){return this.sourceFile.getDirectoryPath()}add(e){return this.statements.push(e),e}build(){let t=[],n;for(let r of this.imports.structures())n={...r,kind:e.StructureKind.ImportDeclaration},t.push(n);for(let e of this.statements)n&&ft(n,e)&&t.push(dt),t.push(e),n=e;return t.length>0&&this.sourceFile.addStatements(t),this.sourceFile}},ut=class{open;modules=new Map;constructor(e){this.open=e}module(e){let t=this.open(e),n=t.getFilePath(),r=this.modules.get(n);return r||(r=new lt(t),this.modules.set(n,r)),r}build(){for(let e of this.modules.values())e.build();this.modules.clear()}},dt=e=>{e.blankLineIfLastNot()};function ft(t,n){if(typeof n==`string`)return!1;switch(n.kind){case e.StructureKind.TypeAlias:case e.StructureKind.VariableStatement:return typeof t==`string`||t.kind!==n.kind;default:return!0}}function pt(e,t){return{name:`[key: string]`,type:e,docs:t}}var mt=`@`;function P(e,t,n){return e.imports.add(t,n)}function ht(e,n,r){return r.path.startsWith(mt)?r.path:F(e.directoryPath,(0,t.join)(n,r.path,p))}function F(e,n){let r=(0,t.relative)(e,n).split(t.sep).join(`/`);return r=r.endsWith(`.ts`)?r.replace(/\.ts$/,`.js`):`${r}/index.js`,r.startsWith(`.`)?r:`./${r}`}function gt(e,t=`
|
|
2
|
-
`){if(!Array.isArray(e))return;let n=e.filter(e=>typeof e==`string`&&e.length>0).map(
|
|
1
|
+
let e=require("ts-morph"),t=require("path"),n=require("yaml"),r=require("fs"),i=require("node:path");var a=`./wow-generator.config.json`,o={success:0,internal:1,input:2,configuration:3,specification:4,output:5,interrupted:130},s=class extends Error{kind;constructor(e,t,n){super(t,n),this.kind=e,this.name=`GeneratorError`}get exitCode(){return o[this.kind]}};function c(e){return e instanceof Error?e.message:String(e)}function l(){return!!process.stdout?.isTTY&&!process.env.NO_COLOR}var u=class{level;decorate;constructor(e={}){this.level=e.level??`normal`,this.decorate=e.decorate??l()}format(e,t,n){let r=this.decorate?`${e} `:t?`${t}: `:``;return`${this.level===`verbose`?`[${new Date().toTimeString().slice(0,8)}] `:``}${r}${n}`}debug(e,...t){this.level===`verbose`&&console.log(this.format(`ℹ️ `,``,e),...t)}info(e,...t){this.level!==`quiet`&&console.log(this.format(`✅`,``,e),...t)}warn(e,...t){console.warn(this.format(`⚠️ `,`warning`,e),...t)}error(e,...t){console.error(this.format(`❌`,`error`,e),...t)}},d=class{debug(){}info(){}warn(){}error(){}};function f(e,t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:t?`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`:e}var p=`types.ts`;function m(e){return f(e.path,p)}function h(e){return!!(e&&typeof e==`object`&&`$ref`in e)}function g(e,t){let n=t.slice(1);try{n=decodeURIComponent(n)}catch{}if(n===``)return e;let r=e;for(let e of n.slice(1).split(`/`)){if(typeof r!=`object`||!r)return;let t=e.replace(/~1/g,`/`).replace(/~0/g,`~`);if(!Object.hasOwn(r,t))return;r=r[t]}return r}function ee(e){let t=[],n=new Set,r=(i,a)=>{if(typeof i!=`object`||!i||n.has(i))return;if(n.add(i),Array.isArray(i)){i.forEach((e,t)=>r(e,`${a}/${t}`));return}let o=i.$ref;typeof o==`string`&&o.startsWith(`#/components/`)&&g(e,o)===void 0&&t.push({ref:o,location:a||`/`});for(let[e,t]of Object.entries(i))r(t,`${a}/${e.replace(/~/g,`~0`).replace(/\//g,`~1`)}`)};return r(e,``),t}var _=`#/components/`,te=`${_}parameters/`,ne=`${_}requestBodies/`,re=`${_}responses/`,ie=`${_}schemas/`;function ae(e){return e.$ref.split(`/`).pop()}function v(e,t,n){let r=new Set,i=e;for(;h(i);){if(!i.$ref.startsWith(n))return;if(r.has(i.$ref))throw new s(`specification`,`Cyclic component reference: ${i.$ref}`);r.add(i.$ref),i=t?.[i.$ref.slice(n.length)]}return i}function y(e,t){return v(e,t.schemas,ie)}function oe(e,t){return v(e,t.responses,re)}function se(e,t){return v(e,t.requestBodies,ne)}function ce(e,t){return v(e,t.parameters,te)}var le=new Intl.Collator(`en-US`);function b(e,t){return le.compare(e,t)}var ue=`application/json`,de=`text/event-stream`;function fe(e){return e.split(`;`)[0].trim().toLowerCase()}function pe(e){let t=fe(e);return t===`application/json`||/^application\/[^/]+\+json$/.test(t)}function me(e){let t=fe(e);return t.startsWith(`text/`)&&t!==`text/event-stream`}function x(e,t,n=e=>fe(e)===t){if(!e)return;if(e[t])return e[t];let r=Object.keys(e).find(n);return r===void 0?void 0:e[r]}function he(e,t){if(t&&!h(t))return x(t.content,e)?.schema}function ge(e){if(e&&!h(e))return x(e.content,ue,pe)?.schema}function _e(e){return he(de,e)}function ve(e){return he(`*/*`,e)}function ye(e){return!e||h(e)?!1:Object.keys(e.content??{}).some(me)}function S(e){return Array.isArray(e.enum)&&e.enum.length>0}var be=`x-enum-text`;function xe(e){return e[be]}function Se(e){return e.type===`object`&&!!e.properties}function Ce(e){return e.type===`array`&&!!e.items}function we(e){return Array.isArray(e.anyOf)&&e.anyOf.length>0}function Te(e){return Array.isArray(e.oneOf)&&e.oneOf.length>0}function Ee(e){return Array.isArray(e.allOf)&&e.allOf.length>0}function C(e){return we(e)||Te(e)||Ee(e)}function De(e){return e.includes(`|`)||e.includes(`&`)?`(${e})[]`:`${e}[]`}function Oe(e){return e.type===`object`&&!e.properties&&e.additionalProperties!==void 0}var ke=`x-map-key-schema`;function Ae(e){return e[ke]}function je(e){return e.readOnly===!0}function Me(e){if(Array.isArray(e))return e.map(e=>Me(e)).join(` | `);switch(e){case`string`:return`string`;case`number`:case`integer`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;default:return`any`}}function Ne(e,t){let n=[],r=new Set,i=new Set,a=!1,o=e=>{if(!(!e||i.has(e)||a)){if(i.add(e),h(e))o(t&&y(e,t));else if(e.nullable||Array.isArray(e.type))a=!0;else{for(let t of e.required??[])r.add(t);for(let t of Object.keys(e.properties??{}))n.includes(t)||n.push(t);e.allOf?.forEach(o)}}};return o(e),a?[]:n.filter(e=>!r.has(e))}function Pe(e,t){return e.operation.operationId&&t.operation.operationId?b(e.operation.operationId,t.operation.operationId):e.path&&t.path?b(e.path,t.path):e.method&&t.method?b(e.method,t.method):0}function Fe(e,t,n){let r=new Map;for(let i of[...e,...t]){let e=h(i)?n&&ce(i,n):i,t=e?`${e.in}:${e.name}`:i.$ref;r.set(t,i)}return[...r.values()]}function Ie(e,t){let n=[];for(let[r,i]of Object.entries(e))Le(i).forEach(e=>{n.push({method:e.method,operation:i.parameters?.length?{...e.operation,parameters:Fe(i.parameters,e.operation.parameters??[],t)}:e.operation,path:r})});return n.sort(Pe)}function Le(e){return[{method:`get`,operation:e.get},{method:`put`,operation:e.put},{method:`post`,operation:e.post},{method:`delete`,operation:e.delete},{method:`options`,operation:e.options},{method:`head`,operation:e.head},{method:`patch`,operation:e.patch},{method:`trace`,operation:e.trace}].filter(({operation:e})=>e!==void 0)}function Re(e){let t=Object.keys(e.responses??{});if(t.includes(`200`))return`200`;let n=t.filter(e=>/^2\d\d$/.test(e)).sort();return n.length>0?n[0]:t.find(e=>e.toUpperCase()===`2XX`)}function ze(e,t){let n=Re(e),r=n?e.responses[n]:void 0;return t&&h(r)?oe(r,t):r}function Be(e,t){return(e.parameters??[]).map(e=>h(e)?ce(e,t):e).filter(e=>e!==void 0)}function Ve(e,t){let n=t=>{let n=e.indexOf(`{${t.name}}`);return n<0?2**53-1:n};return[...t].sort((e,t)=>n(e)-n(t))}var He=/[^\p{L}\p{N}$]+/u,Ue=new Set(`arguments.await.break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.eval.export.extends.false.finally.for.function.if.implements.import.in.instanceof.interface.let.new.null.package.private.protected.public.return.static.super.switch.this.throw.true.try.typeof.var.void.while.with.yield`.split(`.`));function w(e){return/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u.test(e)&&!Ue.has(e)}function We(e){return/^\p{N}/u.test(e)?`_${e}`:e}function T(e){if(w(e))return e;let t=We(O(e)||`_`);return Ue.has(t)?`${t}_`:t}function Ge(e){return/^\p{Lu}[\p{L}\p{N}$]*$/u.test(e)&&w(e)}function E(e){return We((Array.isArray(e)?e:[e]).map(e=>Ge(e)?e:D(e)).join(``)||`_`)}function Ke(e){return e.split(He)}function qe(e){return Array.isArray(e)?e.flatMap(e=>Je(Ke(e))):Je(Ke(e))}function Je(e){return e.flatMap(e=>{if(e.length===0)return[];let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=/[A-Z]/.test(i),o=r>0&&/[a-z]/.test(e[r-1]);a&&o&&n?(t.push(n),n=i):n+=i}return n&&t.push(n),t})}function D(e){return e===``||e.length===0?``:qe(e).filter(e=>e.length>0).map(e=>{let t=e.charAt(0),n=e.slice(1);return(/[a-zA-Z]/.test(t)?t.toUpperCase():t)+n.toLowerCase()}).join(``)}function O(e){let t=D(e);return t.charAt(0).toLowerCase()+t.slice(1)}function k(e){return e===``||Array.isArray(e)&&e.length===0?``:qe(e).filter(e=>e.length>0).map(e=>e.toUpperCase()).join(`_`)}function A(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:j(e)}function Ye(e){return/^\d+$/.test(e)?`NUM_${e}`:k(e)||e}function j(e){return`'${JSON.stringify(e).slice(1,-1).replace(/\\"/g,`"`).replace(/'/g,`\\'`)}'`}var Xe=`x-fetcher-method`;function Ze(e,t){let n=t??e[`x-fetcher-method`];if(n!==void 0){if(typeof n!=`string`||!Qe(n))throw new s(`specification`,`${Xe} of ${e.operationId??`an operation`} is ${JSON.stringify(n)}, which is not a valid method name.`);return n}if(!e.operationId)return;let r=O(e.operationId.split(`.`).pop())||`_`;return/^\p{N}/u.test(r)?`_${r}`:r}function Qe(e){return w(e)||/^[a-z]+$/.test(e)}function $e(e,t){let n=T(e),r=n;for(let e=2;t.has(r);e++)r=`${n}${e}`;return t.add(r),r}function M(e){if(!e)return{name:``,path:`/`};let t=e.split(`.`),n=-1;for(let e=0;e<t.length;e++)if(t[e]&&/^[A-Z]/.test(t[e])){n=e;break}let r=t.slice(0,n),i=r.length>0?`/${r.join(`/`)}`:`/`;return{name:E(t.slice(n)),path:i}}function et(e,t){if(!e.$ref.startsWith(`#/components/schemas/`))throw new s(`specification`,`Unsupported schema reference: ${e.$ref}. Bundle or inline external schemas before generation.`);return t&&y(e,t),M(ae(e))}var tt=[`httpRequest`,`attributes`];function nt(e,t,n){return new rt(e,t,n).clients()}var rt=class{document;config;warnings;constructor(e,t,n){this.document=e,this.config=t,this.warnings=n}clients(){let e=this.tags(),t=this.groupOperations(),n=new Map;return[...t.keys()].sort().map(r=>{let i=M(r),a=i;for(let e=2;n.has(at(a));e++)a={...i,name:`${i.name}${e}`};return a!==i&&this.warnings.push(`Tags ${n.get(at(i))} and ${r} both name the API client ${i.name}ApiClient; ${r} generates ${a.name}ApiClient.`),n.set(at(a),r),this.client(e.get(r),a,[...t.get(r)])})}client(e,t,n){let r=`${t.name}ApiClient`,i=f(t.path,it(r)),a=new Map;return{tagName:e.name,className:r,file:i,description:e.description,methods:n.map(t=>this.method(e,r,t,a))}}method(e,t,n,r){let{operation:i}=n,a=this.methodName(e,t,n,r),o=new Set(tt),s=this.parameters(e,n,o),c=this.body(i,o),l=[...s.filter(({parameter:e})=>e.required),...s.filter(({parameter:e})=>!e.required)].filter(({description:e})=>e);return{name:a,httpMethod:n.method,path:n.path,parameters:s.map(({parameter:e})=>e),body:c,returns:this.returns(i),docs:[i.summary,i.description,`- operationId: \`${i.operationId}\``,`- path: \`${n.path}\``,...l.map(({parameter:e,description:t})=>`@param ${e.name} - ${t.replace(/\s*\n\s*/g,` `)}`)]}}methodName(e,t,n,r){let i=n.operation.operationId,a=Ze(n.operation,this.config.apiClients?.[e.name]?.methodNames?.[i]),o=r.get(a);if(o!==void 0)throw new s(`specification`,`Operations ${o} and ${i} of tag ${e.name} both generate the method ${t}.${a}(). Name one of them with apiClients["${e.name}"].methodNames in the generator configuration, or with the x-fetcher-method extension.`);return r.set(a,i),a}parameters(e,t,n){let r=Be(t.operation,this.document.components??{}),i=[];for(let a of[`path`,`query`,`header`]){let o=r.filter(e=>e.in===a);for(let r of a===`path`?Ve(t.path,o):o)a===`path`&&this.ignoresPathParameter(e.name,r.name)||i.push({parameter:{name:$e(r.name,n),location:a,parameterName:r.name,schema:r.schema,required:a===`path`||r.required===!0},description:r.description})}let a=r.filter(e=>e.in===`cookie`);return a.length>0&&this.warnings.push(`${t.method.toUpperCase()} ${t.path} leaves out its cookie parameter(s) ${a.map(e=>e.name).join(`, `)}: the browser sends cookies, and fetch cannot set them.`),i}ignoresPathParameter(e,t){return(this.config.apiClients?.[e]?.ignorePathParameters)?.includes(t)??!1}body(e,t){if(!e.requestBody)return;let n=h(e.requestBody)?se(e.requestBody,this.document.components):e.requestBody;if(!n)return;let r=n.required===!0,i=n.content??{},a=x(i,ue,pe),o=$e(`body`,t);return a?.schema?{name:o,required:r,content:{kind:`json`,schema:a.schema,optionalFields:Ne(a.schema,this.document.components)}}:x(i,`multipart/form-data`)?{name:o,required:r,content:{kind:`formData`}}:x(i,`application/x-www-form-urlencoded`)?{name:o,required:r,content:{kind:`urlEncoded`}}:Object.keys(i).some(me)?{name:o,required:r,content:{kind:`text`}}:{name:o,required:r,content:{kind:`binary`}}}returns(e){let t=ze(e,this.document.components);if(!t)return{kind:`response`};let n=ge(t),r=n||ve(t);if(r)return{kind:`json`,schema:r,wildcard:!n};let i=_e(t);if(i){if(h(i)){let e=y(i,this.document.components);if(Ce(e)&&h(e.items)){let t=et(e.items,this.document.components);return{kind:`eventStream`,items:e.items,serverSentEvent:t.name.includes(`ServerSentEvent`)}}}return{kind:`eventStream`,serverSentEvent:!1}}return ye(t)?{kind:`text`}:{kind:`response`}}groupOperations(){let e=new Map;for(let t of this.document.endpoints){let n=`${t.method.toUpperCase()} ${t.path}`,r=t.operation.tags??[];if(r.length===0)this.warnings.push(`Skipping ${n}: it has no tag, and the tag names its API client.`);else if(!t.operation.operationId)this.warnings.push(`Skipping ${n}: it has no operationId, and the operationId names its method.`);else for(let n of r)e.has(n)||e.set(n,new Set),e.get(n).add(t)}return e}tags(){let e=new Map;for(let{operation:t}of this.document.endpoints)t.tags?.forEach(t=>{e.has(t)||e.set(t,{name:t,description:``})});return this.document.openAPI.tags?.forEach(t=>e.set(t.name,t)),e}};function it(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}.ts`}function at(e){return`${e.path}/${e.name}`.toLowerCase()}function ot(e){let t=e.components?.schemas;if(!t)return[];let n=Object.keys(t);return st(n),n.map(e=>{let n=t[e],r=M(e);return{key:e,info:r,file:m(r),schema:n}})}function st(e){let t=new Map;for(let n of e){let e=M(n),r=`${e.path===`/`?``:e.path}/${e.name}`;t.set(r,[...t.get(r)??[],n])}let n=[...t].filter(([,e])=>e.length>1);if(n.length!==0)throw new s(`specification`,`Schemas generate the same model: ${n.map(([e,t])=>`${t.join(`, `)} → ${e}`).join(`; `)}. Rename all but one of them in the document.`)}function ct(e,t){let n=[];return{model:{models:ot(e),apiClients:nt(e,t,n)},warnings:n}}var lt=class{declarations=new Map;add(e,t){let n=this.declarations.get(e);n||(n=[],this.declarations.set(e,n));for(let e of t)n.some(t=>t.name===e)||n.push({name:e});return n}apply(e){for(let{moduleSpecifier:t,name:n,alias:r}of e){let e=this.add(t,[n]).find(e=>e.name===n);r!==void 0&&(e.alias=r)}}entries(){return[...this.declarations].flatMap(([e,t])=>t.map(({name:t,alias:n})=>n===void 0?{moduleSpecifier:e,name:t}:{moduleSpecifier:e,name:t,alias:n}))}localNames(e){return[...this.declarations.values()].flat().filter(t=>t!==e).map(e=>e.alias??e.name)}structures(){return[...this.declarations].map(([e,t])=>({moduleSpecifier:e,namedImports:t.map(({name:e,alias:t})=>t===void 0?e:{name:e,alias:t})}))}},ut=class{sourceFile;imports=new lt;statements=[];constructor(e){this.sourceFile=e}get directoryPath(){return this.sourceFile.getDirectoryPath()}add(e){return this.statements.push(e),e}build(){let t=[],n;for(let r of this.imports.structures())n={...r,kind:e.StructureKind.ImportDeclaration},t.push(n);for(let e of this.statements)n&&pt(n,e)&&t.push(ft),t.push(e),n=e;return t.length>0&&this.sourceFile.addStatements(t),this.sourceFile}},dt=class{open;modules=new Map;constructor(e){this.open=e}module(e){let t=this.open(e),n=t.getFilePath(),r=this.modules.get(n);return r||(r=new ut(t),this.modules.set(n,r)),r}build(){for(let e of this.modules.values())e.build();this.modules.clear()}},ft=e=>{e.blankLineIfLastNot()};function pt(t,n){if(typeof n==`string`)return!1;switch(n.kind){case e.StructureKind.TypeAlias:case e.StructureKind.VariableStatement:return typeof t==`string`||t.kind!==n.kind;default:return!0}}function mt(e,t){return{name:`[key: string]`,type:e,docs:t}}var ht=`@`;function N(e,t,n){return e.imports.add(t,n)}function gt(e,n,r){return r.path.startsWith(ht)?r.path:P(e.directoryPath,(0,t.join)(n,r.path,p))}function P(e,n){let r=(0,t.relative)(e,n).split(t.sep).join(`/`);return r=r.endsWith(`.ts`)?r.replace(/\.ts$/,`.js`):`${r}/index.js`,r.startsWith(`.`)?r:`./${r}`}function _t(e,t=`
|
|
2
|
+
`){if(!Array.isArray(e))return;let n=e.filter(e=>typeof e==`string`&&e.length>0).map(vt);return n.length>0?n.join(t):void 0}function vt(e){return e.replace(/\*\//g,`*\\/`)}function F(e,t){let n=_t(t);n&&(e.docs=[...e.docs??[],n])}function I(e,t,n=!1){e=xt(e);let r=[e.title,e.description];return t&&r.push(`- key: ${t}`),n&&St(r,e),e.format&&r.push(e.format===`int64`?`- format: int64 (a value beyond Number.MAX_SAFE_INTEGER loses precision)`:`- format: ${e.format}`),Ct(r,e,`default`),Ct(r,e,`example`),Tt(r,e),Et(r,e),Dt(r,e),r}function yt(e,t,n){F(e,I(t,n))}function bt(e,t,n,r=!1){let i=I(t,n,!0);r&&wt(i,`schema`,t),F(e,i)}function xt(e){for(let t of[`anyOf`,`oneOf`]){let n=e[t];if(!Array.isArray(n)||n.length<2)continue;let r=n.filter(e=>`$ref`in e||e.type!==`null`),[i]=r;if(r.length!==1||`$ref`in i)continue;let a={...i};for(let[n,r]of Object.entries(e))n!==t&&r!==void 0&&(a[n]=r);return a}return e}function St(e,t){let n=t.required??[];(n.length||Object.keys(t.properties??{}).length)&&e.push(`- required: ${n.length?n.join(`, `):`(none)`}`)}function Ct(e,t,n){let r=t[n];r&&(typeof r==`object`?wt(e,n,r):e.push(`- ${n}: \`${r}\``))}function wt(e,t,n){e.push(`- ${t}: `),e.push("```json"),e.push(JSON.stringify(n,null,2)),e.push("```")}function Tt(e,t){let n=[`- Numeric Constraints`];t.minimum!==void 0&&n.push(` - minimum: ${t.minimum}`),t.maximum!==void 0&&n.push(` - maximum: ${t.maximum}`),t.exclusiveMinimum!==void 0&&n.push(` - exclusiveMinimum: ${t.exclusiveMinimum}`),t.exclusiveMaximum!==void 0&&n.push(` - exclusiveMaximum: ${t.exclusiveMaximum}`),t.multipleOf!==void 0&&n.push(` - multipleOf: ${t.multipleOf}`),n.length!==1&&e.push(...n)}function Et(e,t){let n=[`- String Constraints`];t.minLength!==void 0&&n.push(` - minLength: ${t.minLength}`),t.maxLength!==void 0&&n.push(` - maxLength: ${t.maxLength}`),t.pattern!==void 0&&n.push(` - pattern: ${t.pattern}`),n.length!==1&&e.push(...n)}function Dt(e,t){let n=[`- Array Constraints`];t.minItems!==void 0&&n.push(` - minItems: ${t.minItems}`),t.maxItems!==void 0&&n.push(` - maxItems: ${t.maxItems}`),t.uniqueItems!==void 0&&n.push(` - uniqueItems: ${t.uniqueItems}`),n.length!==1&&e.push(...n)}function Ot(e,t){let n;return{components:e,modelOf:n=>t.ofReference(n,e),namesAt(r){if(!n){n=new Map;for(let r of Object.keys(e?.schemas??{})){let e=t.ofKey(r),i=n.get(e.path);i||(i=[],n.set(e.path,i)),i.push(e.name,`${e.name}EnumText`)}}return n.get(r)??[]}}}var kt=[`Array`,`Blob`,`Exclude`,`FormData`,`Partial`,`Promise`,`ReadonlyArray`,`Record`,`Response`,`Symbol`,`URLSearchParams`],At=new Set([`string`,`number`,`boolean`]),jt=new Set([`$comment`,`$schema`,`default`,`deprecated`,`description`,`example`,`examples`,`externalDocs`,`readOnly`,`title`,`writeOnly`,`xml`]);function Mt(e,t){return e===void 0?!1:typeof e==`string`||typeof t==`string`?e===t:e.primitive===t.primitive}function L(e,t,n=new Set){if(h(e)){if(!t||n.has(e.$ref))return;n.add(e.$ref);let r=y(e,t);return r?L(r,t,n):void 0}if(!(e.nullable||Array.isArray(e.type))){if(Ee(e)&&e.type===void 0){let r=e.allOf.map(e=>L(e,t,n)),[i]=r;return i!==void 0&&r.every(e=>Mt(e,i))?i:void 0}if(!(C(e)||e.const!==void 0||e.type===void 0))return e.type===`object`?`object`:e.type===`array`?`array`:{primitive:Me(e.type)}}}function Nt(e,t,n){let r=L(t,n);if(typeof r!=`object`)return!1;let i=L(e,n);return i===void 0||typeof i==`string`||i.primitive!==r.primitive}function Pt(e,t){let n=e.additionalProperties;return typeof n==`object`&&Object.values(e.properties??{}).some(e=>Nt(e,n,t))}function Ft(e){return e.nullable!==!0||S(e)||!C(e)?!1:[e.allOf,e.oneOf,e.anyOf].every(e=>e===void 0||e.every(h))}function It(e,t){return t.type===void 0||e===null&&t.nullable?!0:[t.type].flat().some(t=>t===`null`?e===null:t===`array`?Array.isArray(e):t===`object`?typeof e==`object`&&!!e&&!Array.isArray(e):t===`integer`?typeof e==`number`&&Number.isInteger(e):typeof e===t)}function R(t){if(typeof t==`string`)return new e.CodeBlockWriter({useSingleQuote:!0}).quote(t).toString();if(Array.isArray(t))return`[${t.map(e=>R(e)).join(`, `)}]`;if(typeof t==`object`&&t){let e=Object.entries(t).map(([e,t])=>`${A(e)}: ${R(t)}`);return e.length?`{ ${e.join(`; `)}; readonly [globalThis.Symbol.iterator]?: never }`:`globalThis.Record<string, never>`}return JSON.stringify(t)??`never`}var Lt=class{scope;entries;requested=[];constructor(e){this.scope=e,this.entries=e.imports.entries().map(e=>({...e}))}get components(){return this.scope.context.components}imports(){return this.requested.map(({moduleSpecifier:e,name:t,alias:n})=>n===void 0?{moduleSpecifier:e,name:t}:{moduleSpecifier:e,name:t,alias:n})}request(e){this.requested.includes(e)||this.requested.push(e)}reference(e){let t=this.scope.context.modelOf(e),{owner:n}=this.scope;if(n.path===t.path)return t.name;let r=this.scope.specifierOf(t),i=this.entries.find(e=>e.moduleSpecifier===r&&e.name===t.name);if(i||(i={moduleSpecifier:r,name:t.name},this.entries.push(i)),this.request(i),i.alias)return i.alias;let a=new Set([...kt,n.name,...n.path===void 0?[]:this.scope.context.namesAt(n.path),...this.entries.filter(e=>e!==i).map(e=>e.alias??e.name)]);if(!a.has(t.name))return t.name;let o=`_${t.name}`;for(;a.has(o);)o=`_${o}`;return i.alias=o,o}additionalProperties(e){return e.additionalProperties===!1||e.additionalProperties===void 0&&!e.required?.some(t=>!Object.hasOwn(e.properties??{},t))?``:e.additionalProperties===!0||e.additionalProperties===void 0?`[key: string]: any`:`[key: string]: ${this.additionalPropertyType(e)}`}additionalPropertyType(e){return this.type(typeof e.additionalProperties==`object`?e.additionalProperties:{})}requiredAdditionalPropertyType(e){return e.additionalProperties===!1?`never`:typeof e.additionalProperties==`object`?this.type(e.additionalProperties):`null | string | number | boolean | globalThis.Record<string, unknown> | readonly unknown[]`}propertyDefinitions(e){let{properties:t}=e;return Object.entries(t).map(([e,t])=>{let n=this.type(t),r=(je(t)?`readonly `:``)+A(e);if(!h(t)){let e=_t(I(t),`
|
|
3
3
|
* `);if(e)return`
|
|
4
4
|
/**
|
|
5
5
|
* ${e}
|
|
6
6
|
*/
|
|
7
7
|
${r}: ${n}
|
|
8
|
-
`}return`${r}: ${n}`})}objectType(e){let t=[];Se(e)&&t.push(...this.propertyDefinitions(e));for(let n of e.required??[])Object.hasOwn(e.properties??{},n)||t.push(`${A(n)}: ${this.requiredAdditionalPropertyType(e)}`);let n=Oe(e)&&Ae(e)?this.mapType(e):
|
|
9
|
-
`)}; \n}`;return n?`(${i} & ${n})`:i}mapValueType(e){return e.additionalProperties===void 0||e.additionalProperties===!1||e.additionalProperties===!0?`any`:this.type(e.additionalProperties)}mapKeyType(e){let t=Ae(e);return t?this.type(t):`string`}mapType(e){return`globalThis.Record<${this.mapKeyType(e)},${this.mapValueType(e)}>`}objectConstrained(e){let t=e=>h(e)?this.components&&y(e,this.components):e,n=t(e),r=new Map,i=new Set,a=n?[n]:[];for(let e of a){if(r.has(e))continue;let n=[e.allOf,e.oneOf,e.anyOf].map(e=>e?.map(t)??[]);r.set(e,n);for(let e of n)for(let t of e)t&&!r.has(t)&&a.push(t);(e.type===`object`||e.type===`null`||Array.isArray(e.type)&&e.type.length>0&&e.type.every(e=>e===`object`||e===`null`))&&i.add(e)}let o=!0;for(;o;){o=!1;for(let[e,[t,n,a]]of r){if(i.has(e))continue;let r=e=>e!==void 0&&i.has(e);(t.some(r)||[n,a].some(e=>e.length>0&&e.every(r)))&&(i.add(e),o=!0)}}return n!==void 0&&i.has(n)}type(e){if(h(e))return this.reference(e);if(Array.isArray(e.type))return e.type.map(t=>{let n=this.type({...e,type:t});return/[|&]/.test(n)?`(${n})`:n}).join(` | `);if(
|
|
8
|
+
`}return`${r}: ${n}`})}objectType(e){let t=[];Se(e)&&t.push(...this.propertyDefinitions(e));for(let n of e.required??[])Object.hasOwn(e.properties??{},n)||t.push(`${A(n)}: ${this.requiredAdditionalPropertyType(e)}`);let n=Oe(e)&&Ae(e)?this.mapType(e):Pt(e,this.components)?`globalThis.Record<string, ${this.additionalPropertyType(e)}>`:void 0,r=n?``:this.additionalProperties(e);if(r&&t.push(r),t.length===0)return`globalThis.Record<string, any>`;let i=`{\n ${t.join(`;
|
|
9
|
+
`)}; \n}`;return n?`(${i} & ${n})`:i}mapValueType(e){return e.additionalProperties===void 0||e.additionalProperties===!1||e.additionalProperties===!0?`any`:this.type(e.additionalProperties)}mapKeyType(e){let t=Ae(e);return t?this.type(t):`string`}mapType(e){return`globalThis.Record<${this.mapKeyType(e)},${this.mapValueType(e)}>`}objectConstrained(e){let t=e=>h(e)?this.components&&y(e,this.components):e,n=t(e),r=new Map,i=new Set,a=n?[n]:[];for(let e of a){if(r.has(e))continue;let n=[e.allOf,e.oneOf,e.anyOf].map(e=>e?.map(t)??[]);r.set(e,n);for(let e of n)for(let t of e)t&&!r.has(t)&&a.push(t);(e.type===`object`||e.type===`null`||Array.isArray(e.type)&&e.type.length>0&&e.type.every(e=>e===`object`||e===`null`))&&i.add(e)}let o=!0;for(;o;){o=!1;for(let[e,[t,n,a]]of r){if(i.has(e))continue;let r=e=>e!==void 0&&i.has(e);(t.some(r)||[n,a].some(e=>e.length>0&&e.every(r)))&&(i.add(e),o=!0)}}return n!==void 0&&i.has(n)}type(e){if(h(e))return this.reference(e);if(Array.isArray(e.type))return e.type.map(t=>{let n=this.type({...e,type:t});return/[|&]/.test(n)?`(${n})`:n}).join(` | `);if(Ft(e))return`(${this.type({...e,nullable:!1})}) | null`;if(C(e)){let t=this.simpleComposition(e);if(t!==void 0)return t;let n=[`allOf`,`oneOf`,`anyOf`].flatMap(t=>{let n=e[t];return n?.length?[`(${n.map(n=>{let r=this.memberType(e,t,n);return r===`any`?`unknown`:/[|&]/.test(r)?`(${r})`:r}).join(t===`allOf`?` & `:` | `)})`]:[]}),r=n.length===1?n[0]:`(${n.join(` & `)})`,i={...e,oneOf:void 0,anyOf:void 0,allOf:void 0},a=this.type(i),o=a===`any`?r:`(${r} & (${a}))`;return this.objectConstrained(e)?`globalThis.Exclude<${o}, string | number | boolean | readonly unknown[]> & ({ readonly [globalThis.Symbol.iterator]?: never } | null)`:o}if(e.const!==void 0){if(!It(e.const,e))return`never`;let t=R(e.const),n=this.type({...e,const:void 0});return n===`any`?t:`(${t}) & (${n})`}if(e.nullable&&e.type&&!S(e))return`(${this.type({...e,nullable:!1})}) | null`;if(S(e)){let t=e.enum.filter(t=>It(t,e)).map(e=>R(e)).join(` | `)||`never`,n=this.type({...e,enum:void 0});return n===`any`||At.has(n)?t:`(${t}) & (${n})`}return Oe(e)&&!e.required?.length?this.mapType(e):e.type===`array`?De(this.type(e.items??{})):e.type===`object`?this.objectType(e):e.type?Me(e.type):e.required?.length||Object.keys(e.properties??{}).length>0?`(${this.objectType({...e,type:`object`,additionalProperties:e.additionalProperties??!0})} | null | string | number | boolean | readonly unknown[])`:`any`}simpleComposition(e){let t=[`allOf`,`oneOf`,`anyOf`].filter(t=>e[t]?.length);if(t.length!==1)return;let[n]=t;if(Object.keys(e).filter(e=>e!==n&&e!==`discriminator`&&!e.startsWith(`x-`)&&!jt.has(e)).length>0)return;let r=e[n],i=e=>n!==`allOf`&&[e.type].flat().every(e=>e===`null`)&&e.type!==void 0&&Object.keys(e).every(e=>e===`type`||jt.has(e));if(!r.every(e=>h(e)||i(e)))return;let a=r.map(t=>h(t)?this.memberType(e,n,t):`null`);return[...new Set(a)].join(n===`allOf`?` & `:` | `)}memberType(e,t,n){let r=this.type(n),i=e.discriminator;if(t===`allOf`||!i?.propertyName||!h(n))return r;let a=ae(n),o=Object.entries(i.mapping??{}).filter(([,e])=>e===n.$ref||e===a).map(([e])=>e),s=(o.length>0?o:[a]).map(e=>j(e)).join(` | `);return`(${r} & { ${A(i.propertyName)}: ${s} })`}};function z(e,t){let n=new Lt(e);return{text:t(n),imports:n.imports()}}function Rt(e,t){return z(t,t=>t.type(e))}function zt(e,t){return z(t,t=>t.additionalProperties(e))}function Bt(e,t){return z(t,t=>t.additionalPropertyType(e))}function Vt(e,t){return z(t,t=>t.requiredAdditionalPropertyType(e))}function Ht(e,t){return z(t,t=>t.mapValueType(e))}var Ut=`@ahoo-wang/fetcher`,Wt=[`ContentTypeValues`,`ResultExtractors`],Gt=`@ahoo-wang/fetcher-decorator`,Kt=[`ApiMetadata`,`ApiMetadataCapable`,`ParameterRequest`,`api`,`get`,`post`,`put`,`patch`,`del`,`request`,`attribute`,`path`,`query`,`header`,`body`,`autoGeneratedError`],qt={type:`Promise<Response>`,metadata:`{resultExtractor: ResultExtractors.Response }`},Jt={type:`Promise<string>`,metadata:`{resultExtractor: ResultExtractors.Text }`},Yt=`{
|
|
10
10
|
headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },
|
|
11
11
|
resultExtractor: JsonEventStreamResultExtractor,
|
|
12
|
-
}`;function
|
|
13
|
-
`)}`)}var
|
|
12
|
+
}`;function Xt(e){N(e,Ut,Wt)}function Zt(e){N(e,Gt,Kt)}function Qt(t,n,r=[],i=[],a){return n.add({kind:e.StructureKind.Class,name:t,isExported:!0,typeParameters:i,extends:a,decorators:[{name:`api`,arguments:r}]})}function $t(t){t.implements=[...[t.implements??[]].flat(),`ApiMetadataCapable`],t.ctors??=[],t.ctors.push({parameters:[{name:`apiMetadata`,type:`ApiMetadata`,hasQuestionToken:!0,scope:e.Scope.Public,isReadonly:!0}]})}function en(e){return e===`delete`?`del`:e}var tn=`@ahoo-wang/fetcher-eventstream`;function nn(e){N(e,tn,[`JsonEventStreamResultExtractor`,`JsonServerSentEventStream`])}function rn(e,t){let n=t.modules.module(e.file);Xt(n),Zt(n),nn(n);let r=Qt(e.className,n);F(r,[e.description]),$t(r);let i=an(e.className,n,t);for(let t of e.methods)(r.methods??=[]).push(on(t,i))}function an(e,t,n){let r={context:n.types,owner:{name:e},specifierOf:e=>gt(t,n.outputDir,e),imports:t.imports};return{module:t,resolveType(e){let n=Rt(e,r);return t.imports.apply(n.imports),n.text}}}function on(e,t){let n=[],r=[];for(let i of e.parameters)(i.required?n:r).push({name:i.name,type:i.schema?t.resolveType(i.schema):`string`,hasQuestionToken:!i.required,decorators:[{name:i.location,arguments:[j(i.parameterName)]}]});e.body&&(e.body.required?n:r).push({name:e.body.name,type:sn(e.body,t),hasQuestionToken:!e.body.required,decorators:[{name:`body`,arguments:[]}]});let i=[...n,...r,{name:`httpRequest`,hasQuestionToken:!0,type:`ParameterRequest`,decorators:[{name:`request`,arguments:[]}]},{name:`attributes`,hasQuestionToken:!0,type:`Record<string, unknown>`,decorators:[{name:`attribute`,arguments:[]}]}],a=cn(e.returns,t),o=j(e.path),s={name:e.name,decorators:[{name:en(e.httpMethod),arguments:a.metadata?[o,a.metadata]:[o]}],parameters:i,returnType:a.type,statements:[`throw autoGeneratedError(${i.map(e=>e.name).join(`,`)});`]};return F(s,[...e.docs]),s}function sn(e,t){let{content:n}=e;switch(n.kind){case`json`:{let e=t.resolveType(n.schema),r=n.optionalFields;return r.length===0||/[|&]/.test(e)||e===`any`?e:(N(t.module,Ut,[`PartialBy`]),`PartialBy<${e}, ${r.map(j).join(` | `)}>`)}case`formData`:return`FormData`;case`urlEncoded`:return`URLSearchParams`;case`text`:return`string`;case`binary`:return`BodyInit`}}function cn(e,t){switch(e.kind){case`json`:{let n=t.resolveType(e.schema);return e.wildcard&&n===`string`?Jt:{type:`Promise<${n}>`}}case`eventStream`:{if(!e.items)return{type:`Promise<JsonServerSentEventStream<any>>`,metadata:Yt};let n=t.resolveType(e.items);return{type:`Promise<JsonServerSentEventStream<${e.serverSentEvent?`${n}['data']`:n}>>`,metadata:Yt}}case`text`:return Jt;case`response`:return qt}}function ln(e){return Ot(e,{ofKey:e=>M(e),ofReference:et})}function un(e,t){new fn(e,t.modules.module(e.file),t).write()}function dn(e){let t=new Set,n=new Map;for(let r of e){let e=Ye(r),i=[e];/^\d/.test(r)||i.push(r);let a=i.find(e=>!t.has(e));for(let n=2;a===void 0;n++)t.has(`${e}_${n}`)||(a=`${e}_${n}`);t.add(a),n.set(r,A(a))}return n}var fn=class{model;module;target;modelInfo;components;constructor(e,t,n){this.model=e,this.module=t,this.target=n,this.modelInfo=e.info,this.components=n.types.components,this.scope={context:n.types,owner:e.info,specifierOf:e=>gt(t,n.outputDir,e),imports:t.imports}}write(){let e=this.process();e&&bt(e,this.model.schema,this.model.key,this.target.schemaDocs===`full`)}process(){let{schema:e}=this.model;return h(e)?this.processTypeAlias(e):S(e)?this.processEnum(e):e.const!==void 0||e.nullable&&e.type||C(e)&&(e.type||e.properties||e.required)?this.processTypeAlias(e):Se(e)?this.processInterface(e):Oe(e)&&typeof e.additionalProperties==`object`&&!Ae(e)&&!e.required?.length?this.processIndexSignature(e):Ce(e)?this.processArray(e):C(e)?this.processComposition(e):this.processTypeAlias(e)}scope;emit(e){return this.module.imports.apply(e.imports),e.text}resolveType(e){return this.emit(Rt(e,this.scope))}processEnum(t){let n=xe(t);if(n){let t=dn(Object.keys(n));this.module.add({kind:e.StructureKind.Enum,name:this.modelInfo.name+`EnumText`,isExported:!0,members:[...t].map(([e,t])=>({name:t,initializer:R(n[e])}))})}let r=[...new Set(t.enum.filter(e=>typeof e==`string`))],i=dn(r);return C(t)||t.const!==void 0||t.type!==void 0&&t.type!==`string`||t.enum.some(e=>typeof e!=`string`)?(r.length&&this.module.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,isExported:!0,declarations:[{name:this.modelInfo.name,initializer:e=>{e.inlineBlock(()=>{for(let t of r)e.write(`${i.get(t)}: `).quote(t).write(`,`).newLine()}),e.write(` as const`)}}]}),this.processTypeAlias(t)):this.module.add({kind:e.StructureKind.Enum,name:this.modelInfo.name,isExported:!0,members:r.map(e=>({name:i.get(e),initializer:R(e)}))})}addPropertyToInterface(e,t,n){let r={name:A(t),type:this.resolveType(n),isReadonly:je(n)};(e.properties??=[]).push(r),yt(r,n)}processInterface(t){if(Pt(t,this.components))return this.processTypeAlias(t);let n=[],r=this.module.add({kind:e.StructureKind.Interface,name:this.modelInfo.name,isExported:!0,properties:n}),i=t.properties||{};Object.entries(i).forEach(([e,t])=>{this.addPropertyToInterface(r,e,t)});for(let e of t.required??[])Object.hasOwn(i,e)||n.push({name:A(e),type:this.emit(Vt(t,this.scope))});return this.emit(zt(t,this.scope))&&n.push(mt(this.emit(Bt(t,this.scope)),[`Additional properties`])),r}processArray(t){let n=this.resolveType(t.items);return this.module.add({kind:e.StructureKind.TypeAlias,name:this.modelInfo.name,type:De(n),isExported:!0})}processIndexSignature(t){return this.module.add({kind:e.StructureKind.Interface,name:this.modelInfo.name,isExported:!0,properties:[mt(this.emit(Ht(t,this.scope)))]})}processComposition(t){return this.module.add({kind:e.StructureKind.TypeAlias,name:this.modelInfo.name,type:this.resolveType(t),isExported:!0})}processTypeAlias(t){return this.module.add({kind:e.StructureKind.TypeAlias,name:this.modelInfo.name,type:this.resolveType(t),isExported:!0})}};function pn(e,t){e.models.forEach(e=>un(e,t)),e.apiClients.forEach(e=>rn(e,t))}function mn(e,t){let n=[];return hn(e,t,n),n}function hn(e,t,n){let r=[];for(let t of e.getSourceFiles()){let e=t.getBaseName();e.endsWith(`.ts`)&&e!==`index.ts`&&r.push({specifier:`./${t.getBaseNameWithoutExtension()}.js`,exports:_n(t)})}for(let i of e.getDirectories()){let e=hn(i,t,n);e&&r.push({specifier:`./${i.getBaseName()}/index.js`,exports:e})}let i=e.getPath();return r.length===0?e.getProject().getSourceFile(`${i}/index.ts`)?new Map:void 0:gn(i,r,t,n)}function gn(e,t,n,r){let i=new Map;for(let e of t)for(let t of e.exports.keys())i.set(t,[...i.get(t)??[],e.specifier]);let a=[...i].filter(([,e])=>e.length>1).map(([e])=>e).sort();for(let t of a)r.push(`${t} is exported by both ${i.get(t).join(` and `)} in ${e}; its index leaves it out, so import it from its own module.`);let o=n(e);o.removeText();let s=new Map;for(let e of t){let t=[...e.exports].filter(([e])=>!a.includes(e)).sort(([e],[t])=>b(e,t));t.forEach(([e,t])=>s.set(e,t)),t.length===e.exports.size?o.addExportDeclaration({moduleSpecifier:e.specifier}):t.length>0&&o.addExportDeclaration({moduleSpecifier:e.specifier,namedExports:t.map(([e,t])=>({name:e,isTypeOnly:t}))})}return o.getStatements().length===0&&o.addStatements(`export {};`),s}function _n(t){let n=new Map;for(let[r,i]of t.getExportedDeclarations())n.set(r,i.every(t=>e.Node.isInterfaceDeclaration(t)||e.Node.isTypeAliasDeclaration(t)));return n}function vn(t){let n=t;for(let t=n.getParent();t;n=t,t=t.getParent())if(e.Node.isQualifiedName(t)){if(t.getLeft()!==n)return!1}else if(e.Node.isPropertyAccessExpression(t)){if(t.getExpression()!==n)return!1}else{if(e.Node.isExpressionWithTypeArguments(t)){let n=t.getParent(),r=n?.getParent();return!(e.Node.isHeritageClause(n)&&n.getToken()===e.SyntaxKind.ExtendsKeyword&&(e.Node.isClassDeclaration(r)||e.Node.isClassExpression(r)))}return e.Node.isTypeNode(t)}return!1}function yn(t){let n=t.getImportDeclarations().filter(e=>!e.getDefaultImport()&&!e.getNamespaceImport()&&e.getNamedImports().length>0);if(n.length===0)return[];let r=new Set(n.flatMap(e=>e.getNamedImports().map(e=>(e.getAliasNode()??e.getNameNode()).getText()))),i=new Set;return t.forEachDescendant((t,n)=>{if(e.Node.isImportDeclaration(t))n.skip();else if(e.Node.isIdentifier(t)&&r.has(t.getText())&&!vn(t)){let e=t.getSymbol();e&&i.add(e.compilerSymbol)}}),n.map(e=>bn(e,e=>{let t=e.getSymbol();return!!t&&!i.has(t.compilerSymbol)}))}function bn(e,t){let n=e.getNamedImports(),r=n.map(t),i=r.every(Boolean);return()=>{n.forEach((e,t)=>{let n=!i&&r[t];e.isTypeOnly()!==n&&e.setIsTypeOnly(n)}),e.isTypeOnly()!==i&&e.setIsTypeOnly(i)}}function xn(e){let t=e.flatMap(yn);for(let e of t)e()}var Sn=new Set([2300,2304,2308,2393,2451,2456,2503,2552]);function Cn(t){let n=[];for(let r of t)for(let t of r.getPreEmitDiagnostics()){if(!Sn.has(t.getCode())||t.getSourceFile()!==r)continue;let i=e.ts.flattenDiagnosticMessageText(t.compilerObject.messageText,` `);n.push(`${r.getFilePath()}:${t.getLineNumber()??0} TS${t.getCode()} ${i}`)}if(n.length>0)throw Error(`The generated code does not compile; nothing was written. This is a wow-generator bug:\n${n.join(`
|
|
13
|
+
`)}`)}var wn=`// Code generated by wow-generator. DO NOT EDIT.
|
|
14
14
|
|
|
15
|
-
`,wn={indentSize:2,tabSize:2,convertTabsToSpaces:!0,semicolons:`insert`,insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces:!0};function Tn(e,t){e.forEach((n,r)=>{t.debug(`Optimizing file [${n.getFilePath()}] - ${r+1}/${e.length}`),n.formatText(wn),n.organizeImports(wn)}),bn(e),Sn(e);for(let t of e)t.insertText(0,Cn)}var En=3e4;function Dn(e){return/^https?:\/\//i.test(e)}function On(e,t={}){return Dn(e)?kn(e,t):jn(e)}async function kn(e,t={}){let n=t.timeoutMs??3e4,r;try{let i=AbortSignal.timeout(n);r=await fetch(e,{headers:t.headers,signal:t.signal?AbortSignal.any([t.signal,i]):i})}catch(e){let t=e instanceof Error&&e.name===`TimeoutError`?`no response within ${n} ms`:An(e);throw Error(t,{cause:e})}if(!r.ok){let e=[r.status,r.statusText].filter(Boolean).join(` `);throw Error(`HTTP ${e}`)}return await r.text()}function An(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error&&t.message?`${e.message} (${t.message})`:e.message}function jn(e){return new Promise((t,n)=>{(0,r.readFile)(e,`utf-8`,(e,r)=>{e?n(e):t(r)})})}async function Mn(e,t){let n;try{n=await On(e,t)}catch(t){throw new s(`input`,`Cannot read the OpenAPI document ${e}: ${c(t)}`,{cause:t})}try{return Pn(n)}catch(t){throw new s(`input`,`Cannot parse the OpenAPI document ${e}: ${c(t)}`,{cause:t})}}function Nn(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new s(`input`,`${t} is not an OpenAPI document: expected an object at the top level.`);let n=e;if(n.swagger!==void 0)throw new s(`input`,`${t} is a Swagger ${String(n.swagger)} document; wow-generator reads OpenAPI 3.x only. Convert it first, for example with swagger2openapi.`);if(typeof n.openapi!=`string`||!/^3\.\d+/.test(n.openapi))throw new s(`input`,`${t} is not an OpenAPI 3.x document: its "openapi" field is ${n.openapi===void 0?`missing`:JSON.stringify(n.openapi)}.`);if(typeof n.info!=`object`||n.info===null||Array.isArray(n.info))throw new s(`input`,`${t} is not a valid OpenAPI document: its "info" object is missing.`);return{...n,paths:n.paths??{}}}function Pn(e){switch(Fn(e)){case`json`:return JSON.parse(e);case`yaml`:return(0,n.parse)(e)}}function Fn(e){let t=e.trimStart();if(t.startsWith(`{`)||t.startsWith(`[`))return`json`;if(t.startsWith(`-`)||t.startsWith(`%YAML`))return`yaml`;try{return JSON.parse(t),`json`}catch{if(t.length>0)return`yaml`}throw Error(`Unable to infer file format`)}async function In(e,t,n){if(e!==void 0)return{...await zn({path:e,explicit:!0},t,n),origin:V(e)};let r=await zn({path:a,explicit:!1},t,n);return r===void 0?(t.debug(`No configuration file found, generating with defaults`),{config:{},warnings:[]}):{...r,origin:V(a)}}var Ln=[`apiClients`],Rn=[`ignorePathParameters`,`methodNames`];async function zn(e,t,n){let r=V(e.path);t.debug(`Reading configuration: ${r}`);let i;try{i=await On(e.path,n)}catch(n){if(!e.explicit&&Bn(n)){t.debug(`No configuration file at ${r}`);return}throw new s(`configuration`,`Cannot read configuration ${r}: ${c(n)}`,{cause:n})}if(!i.trim())return{config:{},warnings:[`Configuration ${r} is empty, generating with defaults`]};let a;try{a=Pn(i)}catch(e){throw new s(`configuration`,`Cannot parse configuration ${r}: ${c(e)}`,{cause:e})}let o=Hn(a,r);return t.debug(`Configuration loaded from ${r}: ${Wn(o.config)}`),o}function V(e){return Dn(e)||(0,t.isAbsolute)(e)?e:(0,t.resolve)(e)}function Bn(e){return typeof e==`object`&&!!e&&e.code===`ENOENT`}function H(e){return e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`}function U(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vn(e,t,n,r,i){let a=Object.keys(r).filter(e=>!i.includes(e));a.length&&e.push(`Ignoring unknown ${n} option(s) in ${t}: ${a.join(`, `)}. Known option(s): ${i.join(`, `)}`)}function Hn(e,t){if(!U(e))throw new s(`configuration`,`Configuration ${t} must be a JSON or YAML object, found ${H(e)}`);let n=[];return Vn(n,t,`configuration`,e,Ln),Un(e.apiClients,t,n),{config:e,warnings:n}}function Un(e,t,n){if(e!==void 0){if(!U(e))throw new s(`configuration`,`apiClients in ${t} must be an object keyed by tag name, found ${H(e)}`);for(let[r,i]of Object.entries(e)){if(!U(i))throw new s(`configuration`,`apiClients["${r}"] in ${t} must be an object, found ${H(i)}`);Vn(n,t,`apiClients["${r}"]`,i,Rn);let{ignorePathParameters:e}=i;if(e!==void 0&&!(Array.isArray(e)&&e.every(e=>typeof e==`string`)))throw new s(`configuration`,`apiClients["${r}"].ignorePathParameters in ${t} must be an array of strings, found ${H(e)}`);let{methodNames:a}=i;if(a!==void 0){if(!U(a))throw new s(`configuration`,`apiClients["${r}"].methodNames in ${t} must be an object mapping operationIds to method names, found ${H(a)}`);for(let[e,n]of Object.entries(a))if(typeof n!=`string`||!w(n))throw new s(`configuration`,`apiClients["${r}"].methodNames["${e}"] in ${t} must be a valid method name, found ${JSON.stringify(n)}`)}}}}function Wn(e){let t=Object.keys(e.apiClients??{});return`apiClients=${t.length?t.join(`, `):`none`}`}var Gn=new Set,Kn=`#/$defs/`;function W(e){return e.startsWith(Kn)?e.slice(8):void 0}function qn(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.openapi===void 0&&t.swagger===void 0&&typeof t.format==`number`&&Array.isArray(t.contexts)}function G(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jn(e,t){let n=e;if(n.format!==1)throw new s(`input`,`${t} is a Wow Manifest of format ${n.format}; wow-generator reads format 1.`);let r=(n.requires??[]).filter(e=>!Gn.has(e));if(r.length>0)throw new s(`input`,`${t} requires ${r.join(`, `)}, which this wow-generator does not understand: generate with a newer one.`);let i=[];if(n.contexts.forEach((e,t)=>{!G(e)||typeof e.name!=`string`?i.push(`contexts[${t}] has no name`):(e.aggregates??[]).forEach((t,n)=>{let r=`${e.name}.aggregates[${n}]`;!G(t)||typeof t.name!=`string`?i.push(`${r} has no name`):!G(t.state)||typeof t.state.schema!=`string`?i.push(`${e.name}.${t.name} has no state schema`):((t.commands??[]).forEach(n=>{(typeof n?.name!=`string`||typeof n.schema!=`string`)&&i.push(`a command of ${e.name}.${t.name} has no name or schema`)}),(t.events??[]).forEach(n=>{(typeof n?.name!=`string`||typeof n.schema!=`string`)&&i.push(`an event of ${e.name}.${t.name} has no name or schema`)}))})}),n.$defs!==void 0&&!G(n.$defs)&&i.push(`$defs is not an object`),i.length>0)throw new s(`specification`,`${t} is not a Manifest wow-generator can read: ${i.join(`; `)}.`);return n}var Yn=new Set([`int64`,`bigint`,`decimal`]),Xn={"wow.lifecycle.TransferOwner":`TransferOwner`,"wow.lifecycle.TransferSpace":`TransferSpace`,"wow.lifecycle.ApplyTags":`ApplyTags`},Zn=new Set([`wow.lifecycle.DeleteAggregate`,`wow.lifecycle.RestoreAggregate`,`wow.lifecycle.TransferOwner`,`wow.lifecycle.TransferSpace`,`wow.lifecycle.ApplyTags`]),Qn=4;function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q(e){let t=e.type;return typeof t==`string`?[t]:Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function $n(e,t){let n=[...new Set(e)];return n.length===1?n[0]:n.map(e=>/ [|&] /.test(e)&&!e.startsWith(`{`)?`(${e})`:e).join(t)}function er(e){return typeof e==`string`?j(e):JSON.stringify(e)}var tr=class{defs;names=new Map;warnings=[];constructor(e){this.defs=e}inlined(e){return e.includes(`(`)}name(e){let t=new Set(e);for(let e=0;t.size>0;e++){let n=new Map;for(let r of t.keys()){let t=r.split(`.`),i=t[t.length-1].split(`$`),a=E([...t.slice(Math.max(0,t.length-1-e),t.length-1),...i].map(e=>/^[a-z]/.test(e)?D(e):e));n.set(a,[...n.get(a)??[],r])}let r=new Set(this.names.values());for(let[i,a]of n){let n=a.filter(t=>t.split(`.`).length-1<=e),o=a.length===1&&!r.has(i)?a:n;for(let e of o){let n=i;for(let e=2;r.has(n);e++)n=`${i}${e}`;r.add(n),this.names.set(e,n),t.delete(e)}}}}schemaOf(e){let t=this.defs[e];return K(t)?t:void 0}resolve(e,t=new Set){let n=e.$ref;if(typeof n!=`string`)return e;let r=W(n);if(r===void 0||t.has(r))return e;let i=this.schemaOf(r);return i?this.resolve(i,new Set([...t,r])):e}references(e,t=new Set){if(Array.isArray(e))e.forEach(e=>this.references(e,t));else if(K(e))for(let[n,r]of Object.entries(e))if(n===`$ref`&&typeof r==`string`){let e=W(r);e!==void 0&&t.add(e)}else n!==`enum`&&n!==`const`&&this.references(r,t);return t}namedReferences(e){let t=new Set;for(let n of this.references(e)){let e=this.schemaOf(n);e!==void 0&&this.inlined(n)?this.namedReferences(e).forEach(e=>t.add(e)):t.add(n)}return t}closure(e){let t=new Set,n=[...e];for(;n.length>0;){let e=n.pop();if(t.has(e))continue;t.add(e);let r=this.schemaOf(e);r&&n.push(...this.references(r))}return[...t]}refType(e,t){let n=this.schemaOf(e);if(n!==void 0&&this.inlined(e))return this.type(n,t);let r=this.names.get(e);return r!==void 0&&this.schemaOf(e)?r:(this.warnings.push(`${t} refers to the schema ${e}, which the Manifest's $defs does not hold; it is typed as unknown.`),`unknown`)}type(e,t){if(e===!0||e===void 0)return`unknown`;if(e===!1)return`never`;if(!K(e))return`unknown`;if(typeof e.$ref==`string`){let n=W(e.$ref);return n===void 0?`unknown`:this.refType(n,t)}if(`const`in e)return er(e.const);if(Array.isArray(e.enum))return e.enum.length===0?`never`:$n(e.enum.map(er),` | `);for(let[n,r]of[[`oneOf`,` | `],[`anyOf`,` | `],[`allOf`,` & `]]){let i=e[n];if(Array.isArray(i)&&i.length>0)return $n(i.map(e=>this.type(e,t)),r)}let n=q(e);return n.length===0?K(e.properties)?this.objectType(e,t):`unknown`:$n(n.map(n=>this.primitive(n,e,t)),` | `)}primitive(e,t,n){switch(e){case`string`:return`string`;case`integer`:case`number`:return typeof t.format==`string`&&Yn.has(t.format)?`string`:`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:{let e=t.items===void 0?`unknown`:this.type(t.items,n);return/ [|&] /.test(e)?`(${e})[]`:`${e}[]`}case`object`:return this.objectType(t,n);default:return`unknown`}}objectType(e,t){let n=this.properties(e,t),r=this.additional(e,t);if(n.length===0)return`Record<string, ${r??`unknown`}>`;let i=n.map(e=>`${e.name}${e.optional?`?`:``}: ${e.type}`);return r!==void 0&&i.push(`[key: string]: unknown`),`{ ${i.join(`; `)} }`}properties(e,t){if(!K(e.properties))return[];let n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([e,r])=>{let i=K(r)?r.description:void 0;return{name:A(e),type:this.type(r,`${t}.${e}`),optional:!n.has(e),...typeof i==`string`?{description:i}:{}}})}additional(e,t){let n=e.additionalProperties;if(n!==void 0&&n!==!1)return this.type(n,t)}isInterface(e){let t=q(e);return K(e.properties)&&(t.length===0||t.length===1&&t[0]===`object`)&&e.$ref===void 0&&e.allOf===void 0&&e.oneOf===void 0&&e.anyOf===void 0}textNumbers(e,t=new Set){if(!K(e))return;let n=typeof e.$ref==`string`?W(e.$ref):void 0;if(n!==void 0){let e=this.schemaOf(n);return t.has(n)||e===void 0?void 0:this.textNumbers(e,new Set([...t,n]))}let r=[`oneOf`,`anyOf`,`allOf`].flatMap(t=>Array.isArray(e[t])?e[t]:[]).map(e=>this.textNumbers(e,t)).filter(e=>e!==void 0),i=q(e);(i.includes(`integer`)||i.includes(`number`))&&typeof e.format==`string`&&Yn.has(e.format)&&r.push(!0);let a={};if(K(e.properties))for(let[n,r]of Object.entries(e.properties)){let e=this.textNumbers(r,t);e!==void 0&&(a[n]=e)}let o=this.textNumbers(e.items,t)??this.textNumbers(e.additionalProperties,t);return o!==void 0&&(a[`*`]=o),Object.keys(a).length>0&&r.push(a),nr(r)}fields(e,t,n=1,r=new Set){let i=this.resolve(e),a=typeof e.$ref==`string`?W(e.$ref):void 0;if(a!==void 0&&r.has(a))return[];let o=a===void 0?r:new Set([...r,a]);if(!K(i.properties))return[];let s=[];for(let[e,r]of Object.entries(i.properties)){let i=`${t}.${e}`;s.push(i),n<Qn&&K(r)&&(q(this.resolve(r)).includes(`array`)||s.push(...this.fields(r,i,n+1,o)))}return s}};function nr(e){if(e.length===0)return;let t=e.filter(e=>e!==!0);if(t.length===0)return!0;let n={};for(let e of t)for(let[t,r]of Object.entries(e))(n[t]??=[]).push(r);return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,nr(t)]))}function rr(e,t){if(t===void 0)return!0;let n=e.resolve(t);return!Array.isArray(n.required)||n.required.length===0}function ir(e){return(e.commands??[]).filter(e=>e.system!==!0)}function ar(e){return(e.commands??[]).filter(e=>e.system===!0&&e.name.startsWith(`wow.lifecycle.`))}function or(e,t){return[t.state.schema,...ir(t).map(e=>e.schema),...(t.events??[]).map(e=>e.schema)].map(W).filter(e=>e!==void 0).concat(sr(e,t))}function sr(e,t){return ar(t).map(e=>e.name).filter(t=>Xn[t]!==void 0&&e.schemaOf(t))}function cr(e){let t=new tr(e.$defs??{}),n=e.contexts,r=new Map;for(let e of n){let n=[...(e.aggregates??[]).flatMap(e=>or(t,e)),...(e.routes??[]).flatMap(e=>[...t.references(e.request),...t.references(e.response)])];for(let i of t.closure(n).sort(b))r.has(i)||r.set(i,e.name)}let i=[...r.keys()].filter(e=>t.schemaOf(e)&&!t.inlined(e));t.name([...i].sort(b));let a=i.map(e=>lr(t,e,`${r.get(e)}/types.ts`)).sort((e,t)=>b(e.file,t.file)||b(e.name,t.name)),o=n.map(e=>ur(t,e));return{model:{...e.service?.name?{service:e.service.name}:{},types:a,contexts:o},warnings:[...new Set(t.warnings)]}}function lr(e,t,n){let r=e.schemaOf(t),i=e.names.get(t),a=typeof r.description==`string`?r.description:void 0,o=[...e.namedReferences(r)].map(t=>e.names.get(t)).filter(e=>e!==void 0&&e!==i),s={key:t,name:i,file:n,...a===void 0?{}:{description:a},references:[...new Set(o)].sort(b)};if(e.isInterface(r)){let n=e.additional(r,t);return{...s,properties:e.properties(r,t),...n===void 0?{}:{type:`unknown`}}}return{...s,type:e.type(r,t)}}function ur(e,t){return{name:t.name,...t.description?{description:t.description}:{},typeName:E(D(t.name)),constantName:k(t.name),directory:t.name,errors:(t.errors??[]).map(e=>({code:e.code,status:e.status,...e.description?{description:e.description}:{}})),subscriptions:[...new Set((t.subscriptions??[]).map(e=>e.name))].sort(b),aggregates:(t.aggregates??[]).map(n=>pr(e,t,n)),routes:(t.routes??[]).map(n=>{let r=`${t.name} route ${n.name}`;return{name:n.name,method:n.route.method,path:n.route.path,...n.description?{description:n.description}:{},deprecated:n.deprecated===!0,parameters:(n.parameters??[]).map(t=>({name:t.name,location:t.in===`path`?`path`:`query`,type:e.type(t.schema,`${r} ${t.name}`),required:t.required})),...n.request===void 0?{}:{requestType:e.type(n.request,`${r} body`)},...n.response===void 0?{}:{responseType:e.type(n.response,`${r} answer`)}}})}}function dr(e){return(e.routes??[]).map(e=>({method:e.method,path:e.path}))}function fr(e,t,n){let r=W(t);return r===void 0?`unknown`:e.refType(r,n)}function pr(e,t,n){let r=`${t.name}.${n.name}`,i=E(D(n.name)),a=n.idSource??`assigned`,o=a===`owner`,s=new Set(sr(e,n)),c=ar(n).filter(e=>Zn.has(e.name)).map(t=>{let n=t.name,i=n.split(`.`).pop(),a=e.schemaOf(n)?.description,c=T(O(i)),l=o&&(t.routes??[]).some(e=>!e.path.includes(`{id}`));return{name:n,member:k(i),method:c,routes:dr(t),...l?{ownMethod:`${c}Own`}:{},...s.has(n)?{bodyType:e.refType(n,r),bodyGenerated:!0}:Xn[n]?{bodyType:Xn[n]}:{},...typeof a==`string`?{description:a}:{}}}),l=new Set(c.flatMap(e=>[e.method,e.ownMethod??e.method])),u=ir(n).map(t=>{let n=T(O(t.name));(l.has(n)||n===`gateway`)&&(n=`${n}Command`),l.add(n);let i=(t.routes??[]).filter(e=>e.method===`POST`),a=i.find(e=>e.path.includes(`{id}`)),s=i.find(e=>!e.path.includes(`{id}`)),c;o&&a&&s&&!(t.mounted??!1)&&(c=`${n}Own`,l.has(c)&&(c=`${c}Command`),l.add(c));let u=W(t.schema);return{name:t.name,method:n,routes:dr(t),...a?{byIdPath:{path:a.path}}:{},...s?{unaddressedPath:{path:s.path}}:{},...c===void 0?{}:{ownMethod:c},bodyType:fr(e,t.schema,`${r}.${t.name}`),bodyOptional:rr(e,u===void 0?void 0:e.schemaOf(u)),creation:t.creation??`none`,mounted:t.mounted??!1,produces:t.produces??[],...t.description?{description:t.description}:{},...e.textNumbers({$ref:t.schema})===void 0?{}:{bodyNumbers:!0}}}),d=e.textNumbers({$ref:n.state.schema}),f=Object.fromEntries((n.events??[]).flatMap(r=>{let i=e.textNumbers({$ref:r.schema});return i===void 0?[]:[[mr(t,n,r.name),i]]})),p=Object.fromEntries(ir(n).flatMap(t=>{let n=e.textNumbers({$ref:t.schema});return n===void 0?[]:[[t.name,n]]})),m={...d===void 0?{}:{state:d},...Object.keys(f).length===0?{}:{events:f},...Object.keys(p).length===0?{}:{commands:p}},h=W(n.state.schema),g=h===void 0?void 0:e.schemaOf(h);return{context:t.name,name:n.name,...n.description?{description:n.description}:{},typeName:i,directory:`${t.name}/${n.name}`,ownership:n.ownership??`owner`,idSource:a,snapshot:n.snapshot?.enabled??!0,stateType:fr(e,n.state.schema,`${r} state`),stateFields:g===void 0?[]:e.fields({$ref:n.state.schema},`state`),commands:u,events:(n.events??[]).map(i=>({name:i.name,wireName:mr(t,n,i.name),revision:i.revision??1,type:fr(e,i.schema,`${r}.${i.name}`)})),lifecycle:c,queryModels:(n.queries??[]).map(e=>e.model),...Object.keys(m).length===0?{}:{textNumbers:m}}}function mr(e,t,n){return n.includes(`.`)?n:`${e.name}.${t.name}.${n}`}var J=`@ahoo-wang/wow-client`,hr=`@ahoo-wang/wow-client/routes`;function Y(e,t=``){let n=e.filter(e=>typeof e==`string`&&e!==``).flatMap(e=>_t(e).split(`
|
|
15
|
+
`,Tn={indentSize:2,tabSize:2,convertTabsToSpaces:!0,semicolons:`insert`,insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces:!0};function En(e,t){e.forEach((n,r)=>{t.debug(`Optimizing file [${n.getFilePath()}] - ${r+1}/${e.length}`),n.formatText(Tn),n.organizeImports(Tn)}),xn(e),Cn(e);for(let t of e)t.insertText(0,wn)}var Dn=3e4;function On(e){return/^https?:\/\//i.test(e)}function kn(e,t={}){return On(e)?An(e,t):Mn(e)}async function An(e,t={}){let n=t.timeoutMs??3e4,r;try{let i=AbortSignal.timeout(n);r=await fetch(e,{headers:t.headers,signal:t.signal?AbortSignal.any([t.signal,i]):i})}catch(e){let t=e instanceof Error&&e.name===`TimeoutError`?`no response within ${n} ms`:jn(e);throw Error(t,{cause:e})}if(!r.ok){let e=[r.status,r.statusText].filter(Boolean).join(` `);throw Error(`HTTP ${e}`)}return await r.text()}function jn(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error&&t.message?`${e.message} (${t.message})`:e.message}function Mn(e){return new Promise((t,n)=>{(0,r.readFile)(e,`utf-8`,(e,r)=>{e?n(e):t(r)})})}async function Nn(e,t){let n;try{n=await kn(e,t)}catch(t){throw new s(`input`,`Cannot read the OpenAPI document ${e}: ${c(t)}`,{cause:t})}try{return Fn(n)}catch(t){throw new s(`input`,`Cannot parse the OpenAPI document ${e}: ${c(t)}`,{cause:t})}}function Pn(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new s(`input`,`${t} is not an OpenAPI document: expected an object at the top level.`);let n=e;if(n.swagger!==void 0)throw new s(`input`,`${t} is a Swagger ${String(n.swagger)} document; wow-generator reads OpenAPI 3.x only. Convert it first, for example with swagger2openapi.`);if(typeof n.openapi!=`string`||!/^3\.\d+/.test(n.openapi))throw new s(`input`,`${t} is not an OpenAPI 3.x document: its "openapi" field is ${n.openapi===void 0?`missing`:JSON.stringify(n.openapi)}.`);if(typeof n.info!=`object`||n.info===null||Array.isArray(n.info))throw new s(`input`,`${t} is not a valid OpenAPI document: its "info" object is missing.`);return{...n,paths:n.paths??{}}}function Fn(e){switch(In(e)){case`json`:return JSON.parse(e);case`yaml`:return(0,n.parse)(e)}}function In(e){let t=e.trimStart();if(t.startsWith(`{`)||t.startsWith(`[`))return`json`;if(t.startsWith(`-`)||t.startsWith(`%YAML`))return`yaml`;try{return JSON.parse(t),`json`}catch{if(t.length>0)return`yaml`}throw Error(`Unable to infer file format`)}async function Ln(e,t,n){if(e!==void 0)return{...await Bn({path:e,explicit:!0},t,n),origin:B(e)};let r=await Bn({path:a,explicit:!1},t,n);return r===void 0?(t.debug(`No configuration file found, generating with defaults`),{config:{},warnings:[]}):{...r,origin:B(a)}}var Rn=[`apiClients`],zn=[`ignorePathParameters`,`methodNames`];async function Bn(e,t,n){let r=B(e.path);t.debug(`Reading configuration: ${r}`);let i;try{i=await kn(e.path,n)}catch(n){if(!e.explicit&&Vn(n)){t.debug(`No configuration file at ${r}`);return}throw new s(`configuration`,`Cannot read configuration ${r}: ${c(n)}`,{cause:n})}if(!i.trim())return{config:{},warnings:[`Configuration ${r} is empty, generating with defaults`]};let a;try{a=Fn(i)}catch(e){throw new s(`configuration`,`Cannot parse configuration ${r}: ${c(e)}`,{cause:e})}let o=Un(a,r);return t.debug(`Configuration loaded from ${r}: ${Gn(o.config)}`),o}function B(e){return On(e)||(0,t.isAbsolute)(e)?e:(0,t.resolve)(e)}function Vn(e){return typeof e==`object`&&!!e&&e.code===`ENOENT`}function V(e){return e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`}function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Hn(e,t,n,r,i){let a=Object.keys(r).filter(e=>!i.includes(e));a.length&&e.push(`Ignoring unknown ${n} option(s) in ${t}: ${a.join(`, `)}. Known option(s): ${i.join(`, `)}`)}function Un(e,t){if(!H(e))throw new s(`configuration`,`Configuration ${t} must be a JSON or YAML object, found ${V(e)}`);let n=[];return Hn(n,t,`configuration`,e,Rn),Wn(e.apiClients,t,n),{config:e,warnings:n}}function Wn(e,t,n){if(e!==void 0){if(!H(e))throw new s(`configuration`,`apiClients in ${t} must be an object keyed by tag name, found ${V(e)}`);for(let[r,i]of Object.entries(e)){if(!H(i))throw new s(`configuration`,`apiClients["${r}"] in ${t} must be an object, found ${V(i)}`);Hn(n,t,`apiClients["${r}"]`,i,zn);let{ignorePathParameters:e}=i;if(e!==void 0&&!(Array.isArray(e)&&e.every(e=>typeof e==`string`)))throw new s(`configuration`,`apiClients["${r}"].ignorePathParameters in ${t} must be an array of strings, found ${V(e)}`);let{methodNames:a}=i;if(a!==void 0){if(!H(a))throw new s(`configuration`,`apiClients["${r}"].methodNames in ${t} must be an object mapping operationIds to method names, found ${V(a)}`);for(let[e,n]of Object.entries(a))if(typeof n!=`string`||!w(n))throw new s(`configuration`,`apiClients["${r}"].methodNames["${e}"] in ${t} must be a valid method name, found ${JSON.stringify(n)}`)}}}}function Gn(e){let t=Object.keys(e.apiClients??{});return`apiClients=${t.length?t.join(`, `):`none`}`}var Kn=new Set,qn=`#/$defs/`;function U(e){return e.startsWith(qn)?e.slice(8):void 0}function Jn(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.openapi===void 0&&t.swagger===void 0&&typeof t.format==`number`&&Array.isArray(t.contexts)}function W(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yn(e,t){let n=e;if(n.format!==1)throw new s(`input`,`${t} is a Wow Manifest of format ${n.format}; wow-generator reads format 1.`);let r=(n.requires??[]).filter(e=>!Kn.has(e));if(r.length>0)throw new s(`input`,`${t} requires ${r.join(`, `)}, which this wow-generator does not understand: generate with a newer one.`);let i=[];if(n.contexts.forEach((e,t)=>{!W(e)||typeof e.name!=`string`?i.push(`contexts[${t}] has no name`):(e.aggregates??[]).forEach((t,n)=>{let r=`${e.name}.aggregates[${n}]`;!W(t)||typeof t.name!=`string`?i.push(`${r} has no name`):!W(t.state)||typeof t.state.schema!=`string`?i.push(`${e.name}.${t.name} has no state schema`):((t.commands??[]).forEach(n=>{(typeof n?.name!=`string`||typeof n.schema!=`string`)&&i.push(`a command of ${e.name}.${t.name} has no name or schema`)}),(t.events??[]).forEach(n=>{(typeof n?.name!=`string`||typeof n.schema!=`string`)&&i.push(`an event of ${e.name}.${t.name} has no name or schema`)}))})}),n.$defs!==void 0&&!W(n.$defs)&&i.push(`$defs is not an object`),i.length>0)throw new s(`specification`,`${t} is not a Manifest wow-generator can read: ${i.join(`; `)}.`);return n}var Xn=new Set([`int64`,`bigint`,`decimal`]),Zn={"wow.lifecycle.TransferOwner":`TransferOwner`,"wow.lifecycle.TransferSpace":`TransferSpace`,"wow.lifecycle.ApplyTags":`ApplyTags`},Qn=new Set([`wow.lifecycle.DeleteAggregate`,`wow.lifecycle.RestoreAggregate`,`wow.lifecycle.TransferOwner`,`wow.lifecycle.TransferSpace`,`wow.lifecycle.ApplyTags`]),$n=4;function G(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function K(e){let t=e.type;return typeof t==`string`?[t]:Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function q(e,t){let n=[...new Set(e)];return n.length===1?n[0]:n.map(e=>/ [|&] /.test(e)&&!e.startsWith(`{`)?`(${e})`:e).join(t)}function er(e){return typeof e==`string`?j(e):JSON.stringify(e)}var tr=class{defs;names=new Map;warnings=[];constructor(e){this.defs=e}inlined(e){return e.includes(`(`)}name(e){let t=new Set(e);for(let e=0;t.size>0;e++){let n=new Map;for(let r of t.keys()){let t=r.split(`.`),i=t[t.length-1].split(`$`),a=E([...t.slice(Math.max(0,t.length-1-e),t.length-1),...i].map(e=>/^[a-z]/.test(e)?D(e):e));n.set(a,[...n.get(a)??[],r])}let r=new Set(this.names.values());for(let[i,a]of n){let n=a.filter(t=>t.split(`.`).length-1<=e),o=a.length===1&&!r.has(i)?a:n;for(let e of o){let n=i;for(let e=2;r.has(n);e++)n=`${i}${e}`;r.add(n),this.names.set(e,n),t.delete(e)}}}}schemaOf(e){let t=this.defs[e];return G(t)?t:void 0}resolve(e,t=new Set){let n=e.$ref;if(typeof n!=`string`)return e;let r=U(n);if(r===void 0||t.has(r))return e;let i=this.schemaOf(r);return i?this.resolve(i,new Set([...t,r])):e}references(e,t=new Set){if(Array.isArray(e))e.forEach(e=>this.references(e,t));else if(G(e))for(let[n,r]of Object.entries(e))if(n===`$ref`&&typeof r==`string`){let e=U(r);e!==void 0&&t.add(e)}else n!==`enum`&&n!==`const`&&this.references(r,t);return t}namedReferences(e){let t=new Set;for(let n of this.references(e)){let e=this.schemaOf(n);e!==void 0&&this.inlined(n)?this.namedReferences(e).forEach(e=>t.add(e)):t.add(n)}return t}closure(e){let t=new Set,n=[...e];for(;n.length>0;){let e=n.pop();if(t.has(e))continue;t.add(e);let r=this.schemaOf(e);r&&n.push(...this.references(r))}return[...t]}refType(e,t){let n=this.schemaOf(e);if(n!==void 0&&this.inlined(e))return this.type(n,t);let r=this.names.get(e);return r!==void 0&&this.schemaOf(e)?r:(this.warnings.push(`${t} refers to the schema ${e}, which the Manifest's $defs does not hold; it is typed as unknown.`),`unknown`)}type(e,t){if(e===!0||e===void 0)return`unknown`;if(e===!1)return`never`;if(!G(e))return`unknown`;if(typeof e.$ref==`string`){let n=U(e.$ref);return n===void 0?`unknown`:this.refType(n,t)}if(`const`in e)return er(e.const);if(Array.isArray(e.enum))return e.enum.length===0?`never`:q(e.enum.map(er),` | `);for(let[n,r]of[[`oneOf`,` | `],[`anyOf`,` | `],[`allOf`,` & `]]){let i=e[n];if(Array.isArray(i)&&i.length>0)return q(i.map(e=>this.type(e,t)),r)}let n=K(e);return n.length===0?G(e.properties)?this.objectType(e,t):`unknown`:q(n.map(n=>this.primitive(n,e,t)),` | `)}primitive(e,t,n){switch(e){case`string`:return`string`;case`integer`:case`number`:return typeof t.format==`string`&&Xn.has(t.format)?`string`:`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:{let e=t.items===void 0?`unknown`:this.type(t.items,n);return/ [|&] /.test(e)?`(${e})[]`:`${e}[]`}case`object`:return this.objectType(t,n);default:return`unknown`}}objectType(e,t){let n=this.properties(e,t),r=this.additional(e,t);if(n.length===0)return`Record<string, ${r??`unknown`}>`;let i=n.map(e=>`${e.name}${e.optional?`?`:``}: ${e.type}`);return r!==void 0&&i.push(`[key: string]: unknown`),`{ ${i.join(`; `)} }`}properties(e,t){if(!G(e.properties))return[];let n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([e,r])=>{let i=G(r)?r.description:void 0;return{name:A(e),type:this.type(r,`${t}.${e}`),optional:!n.has(e),...typeof i==`string`?{description:i}:{}}})}additional(e,t){let n=e.additionalProperties;if(n!==void 0&&n!==!1)return this.type(n,t)}isInterface(e){let t=K(e);return G(e.properties)&&(t.length===0||t.length===1&&t[0]===`object`)&&e.$ref===void 0&&e.allOf===void 0&&e.oneOf===void 0&&e.anyOf===void 0}textNumbers(e,t=new Set){if(!G(e))return;let n=typeof e.$ref==`string`?U(e.$ref):void 0;if(n!==void 0){let e=this.schemaOf(n);return t.has(n)||e===void 0?void 0:this.textNumbers(e,new Set([...t,n]))}let r=[`oneOf`,`anyOf`,`allOf`].flatMap(t=>Array.isArray(e[t])?e[t]:[]).map(e=>this.textNumbers(e,t)).filter(e=>e!==void 0),i=K(e);(i.includes(`integer`)||i.includes(`number`))&&typeof e.format==`string`&&Xn.has(e.format)&&r.push(!0);let a={};if(G(e.properties))for(let[n,r]of Object.entries(e.properties)){let e=this.textNumbers(r,t);e!==void 0&&(a[n]=e)}let o=this.textNumbers(e.items,t)??this.textNumbers(e.additionalProperties,t);return o!==void 0&&(a[`*`]=o),Object.keys(a).length>0&&r.push(a),nr(r)}fields(e,t,n=1,r=new Set){let i=this.resolve(e),a=typeof e.$ref==`string`?U(e.$ref):void 0;if(a!==void 0&&r.has(a))return[];let o=a===void 0?r:new Set([...r,a]);if(!G(i.properties))return[];let s=[];for(let[e,r]of Object.entries(i.properties)){let i=`${t}.${e}`;s.push(i),n<$n&&G(r)&&(K(this.resolve(r)).includes(`array`)||s.push(...this.fields(r,i,n+1,o)))}return s}};function nr(e){if(e.length===0)return;let t=e.filter(e=>e!==!0);if(t.length===0)return!0;let n={};for(let e of t)for(let[t,r]of Object.entries(e))(n[t]??=[]).push(r);return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,nr(t)]))}function rr(e,t,n){if(t===void 0)return!0;let r=e.resolve(t);return!Array.isArray(r.required)||r.required.every(e=>e===n)}function ir(e,t,n){if(t===void 0)return!1;let r=e.resolve(t).properties,i=G(r)?r[n]:void 0;return G(i)&&i.readOnly===!0}function ar(e){return(e.commands??[]).filter(e=>e.system!==!0)}function or(e){return(e.commands??[]).filter(e=>e.system===!0&&e.name.startsWith(`wow.lifecycle.`))}function sr(e,t){return[t.state.schema,...ar(t).map(e=>e.schema),...(t.events??[]).map(e=>e.schema)].map(U).filter(e=>e!==void 0).concat(cr(e,t))}function cr(e,t){return or(t).map(e=>e.name).filter(t=>Zn[t]!==void 0&&e.schemaOf(t))}function lr(e){let t=new tr(e.$defs??{}),n=e.contexts,r=new Map;for(let e of n){let n=[...(e.aggregates??[]).flatMap(e=>sr(t,e)),...(e.routes??[]).flatMap(e=>[...t.references(e.request),...t.references(e.response)])];for(let i of t.closure(n).sort(b))r.has(i)||r.set(i,e.name)}let i=[...r.keys()].filter(e=>t.schemaOf(e)&&!t.inlined(e));t.name([...i].sort(b));let a=i.map(e=>ur(t,e,`${r.get(e)}/types.ts`)).sort((e,t)=>b(e.file,t.file)||b(e.name,t.name)),o=n.map(e=>dr(t,e));return{model:{...e.service?.name?{service:e.service.name}:{},types:a,contexts:o},warnings:[...new Set(t.warnings)]}}function ur(e,t,n){let r=e.schemaOf(t),i=e.names.get(t),a=typeof r.description==`string`?r.description:void 0,o=[...e.namedReferences(r)].map(t=>e.names.get(t)).filter(e=>e!==void 0&&e!==i),s={key:t,name:i,file:n,...a===void 0?{}:{description:a},references:[...new Set(o)].sort(b)};if(e.isInterface(r)){let n=e.additional(r,t);return{...s,properties:e.properties(r,t),...n===void 0?{}:{type:`unknown`}}}return{...s,type:e.type(r,t)}}function dr(e,t){return{name:t.name,...t.description?{description:t.description}:{},typeName:E(D(t.name)),constantName:k(t.name),directory:t.name,errors:(t.errors??[]).map(e=>({code:e.code,status:e.status,...e.description?{description:e.description}:{}})),subscriptions:[...new Set((t.subscriptions??[]).map(e=>e.name))].sort(b),aggregates:(t.aggregates??[]).map(n=>mr(e,t,n)),routes:(t.routes??[]).map(n=>{let r=`${t.name} route ${n.name}`;return{name:n.name,method:n.route.method,path:n.route.path,...n.description?{description:n.description}:{},deprecated:n.deprecated===!0,parameters:(n.parameters??[]).map(t=>({name:t.name,location:t.in===`path`?`path`:`query`,type:e.type(t.schema,`${r} ${t.name}`),required:t.required})),...n.request===void 0?{}:{requestType:e.type(n.request,`${r} body`)},...n.response===void 0?{}:{responseType:e.type(n.response,`${r} answer`)}}})}}function fr(e){return(e.routes??[]).map(e=>({method:e.method,path:e.path}))}function pr(e,t,n){let r=U(t);return r===void 0?`unknown`:e.refType(r,n)}function mr(e,t,n){let r=`${t.name}.${n.name}`,i=E(D(n.name)),a=n.idSource??`assigned`,o=a===`owner`,s=new Set(cr(e,n)),c=or(n).filter(e=>Qn.has(e.name)).map(t=>{let n=t.name,i=n.split(`.`).pop(),a=e.schemaOf(n)?.description,c=T(O(i)),l=o&&(t.routes??[]).some(e=>!e.path.includes(`{id}`));return{name:n,member:k(i),method:c,routes:fr(t),...l?{ownMethod:`${c}Own`}:{},...s.has(n)?{bodyType:e.refType(n,r),bodyGenerated:!0}:Zn[n]?{bodyType:Zn[n]}:{},...typeof a==`string`?{description:a}:{}}}),l=new Set(c.flatMap(e=>[e.method,e.ownMethod??e.method])),u=ar(n).map(t=>{let n=T(O(t.name));(l.has(n)||n===`gateway`)&&(n=`${n}Command`),l.add(n);let i=(t.routes??[]).filter(e=>e.method===`POST`),a=i.find(e=>e.path.includes(`{id}`)),s=i.find(e=>!e.path.includes(`{id}`)),c;o&&a&&s&&!(t.mounted??!1)&&(c=`${n}Own`,l.has(c)&&(c=`${c}Command`),l.add(c));let u=U(t.schema),d=u===void 0?void 0:e.schemaOf(u),f=t.idProperty,p=f!==void 0&&ir(e,d,f);return{name:t.name,method:n,routes:fr(t),...a?{byIdPath:{path:a.path}}:{},...s?{unaddressedPath:{path:s.path}}:{},...c===void 0?{}:{ownMethod:c},bodyType:pr(e,t.schema,`${r}.${t.name}`),bodyOptional:rr(e,d,p?f:void 0),...f===void 0?{}:{idProperty:f},...p?{idComputed:p}:{},creation:t.creation??`none`,mounted:t.mounted??!1,produces:t.produces??[],...t.description?{description:t.description}:{},...e.textNumbers({$ref:t.schema})===void 0?{}:{bodyNumbers:!0}}}),d=e.textNumbers({$ref:n.state.schema}),f=Object.fromEntries((n.events??[]).flatMap(r=>{let i=e.textNumbers({$ref:r.schema});return i===void 0?[]:[[hr(t,n,r.name),i]]})),p=Object.fromEntries(ar(n).flatMap(t=>{let n=e.textNumbers({$ref:t.schema});return n===void 0?[]:[[t.name,n]]})),m={...d===void 0?{}:{state:d},...Object.keys(f).length===0?{}:{events:f},...Object.keys(p).length===0?{}:{commands:p}},h=U(n.state.schema),g=h===void 0?void 0:e.schemaOf(h);return{context:t.name,name:n.name,...n.description?{description:n.description}:{},typeName:i,directory:`${t.name}/${n.name}`,ownership:n.ownership??`owner`,idSource:a,snapshot:n.snapshot?.enabled??!0,stateType:pr(e,n.state.schema,`${r} state`),stateFields:g===void 0?[]:e.fields({$ref:n.state.schema},`state`),commands:u,events:(n.events??[]).map(i=>({name:i.name,wireName:hr(t,n,i.name),revision:i.revision??1,type:pr(e,i.schema,`${r}.${i.name}`)})),lifecycle:c,queryModels:(n.queries??[]).map(e=>e.model),...Object.keys(m).length===0?{}:{textNumbers:m}}}function hr(e,t,n){return n.includes(`.`)?n:`${e.name}.${t.name}.${n}`}var J=`@ahoo-wang/wow-client`,gr=`@ahoo-wang/wow-client/routes`;function Y(e,t=``){let n=e.filter(e=>typeof e==`string`&&e!==``).flatMap(e=>vt(e).split(`
|
|
16
16
|
`));return n.length===0?``:n.length===1?`${t}/** ${n[0]} */\n`:`${t}/**\n${n.map(e=>`${t} * ${e}`.trimEnd()).join(`
|
|
17
|
-
`)}\n${t} */\n`}function X(e,t){e.add(`\n${t}`)}function Z(e){return e.length===0?`never`:e.join(` | `)}function Q(e,t,n,r,a){let o=new Map;for(let e of new Set(r)){let t=n.get(e);t!==void 0&&t!==a&&o.set(t,[...o.get(t)??[],e])}for(let[n,r]of o)e.imports.add(
|
|
18
|
-
`)}\n}`)}function
|
|
19
|
-
`)}\n${t}},\n`}function
|
|
20
|
-
`)}\n} as const;`)}function
|
|
17
|
+
`)}\n${t} */\n`}function X(e,t){e.add(`\n${t}`)}function Z(e){return e.length===0?`never`:e.join(` | `)}function Q(e,t,n,r,a){let o=new Map;for(let e of new Set(r)){let t=n.get(e);t!==void 0&&t!==a&&o.set(t,[...o.get(t)??[],e])}for(let[n,r]of o)e.imports.add(P(e.directoryPath,(0,i.join)(t,n)),r)}function _r(e,t,n){let r=new Map(e.types.map(e=>[e.name,e.file]));for(let i of e.types)vr(t.module(i.file),i,r,n);for(let i of e.contexts){xr(i,t,n);for(let e of i.aggregates)Or(e,i,t,r,n),Mr(e,i,t,r,n),Nr(e,t,r,n);Sr(i,t),Cr(i,t,r,n),Tr(i,t,n)}}function vr(e,t,n,r){Q(e,r,n,t.references,t.file);let i=Y([t.description,`- key: \`${t.key}\``]);if(t.properties===void 0){X(e,`${i}export type ${t.name} = ${t.type};`);return}let a=t.properties.map(e=>`${Y([e.description],` `)} ${e.name}${e.optional?`?`:``}: ${e.type};`);t.type!==void 0&&a.push(` [key: string]: ${t.type};`),X(e,`${i}export interface ${t.name} {\n${a.join(`
|
|
18
|
+
`)}\n}`)}function yr(e,t){let n=e.aggregates.map(t=>`${e.name}.${t.name}.`),r=t===void 0?`${e.name}.`:`${e.name}.${t.name}.`;return e.errors.filter(e=>t===void 0?!n.some(t=>e.code.startsWith(t)):e.code.startsWith(r)).map(e=>({member:k((e.code.startsWith(r)?e.code.slice(r.length):e.code).split(/[^A-Za-z0-9]+/))||`ERROR`,error:e}))}function br(e,t){return e.length===0?``:`${t}Errors: {\n${e.map(({member:e,error:n})=>`${Y([`${n.status}: ${n.description??n.code}`],`${t} `)}${t} ${e}: ${j(n.code)},`).join(`
|
|
19
|
+
`)}\n${t}},\n`}function xr(e,t,n){let r=t.module(`${e.directory}/contract.ts`),a=`${e.typeName}Contract`;r.imports.add(J,[`Hop`,`wait`]);for(let t of e.aggregates)r.imports.add(P(r.directoryPath,(0,i.join)(n,t.directory,`aggregate.ts`)),[`${t.typeName}Aggregate`]);let o=e.aggregates.map(e=>` ${e.typeName}: ${e.typeName}Aggregate,\n`);X(r,`${Y([`The bounded context \`${e.name}\`: its name, its error codes and its aggregates, as the Kotlin \`${a}\` names them. A problem's \`code\` is one of its \`Errors\`, or of an aggregate's.`,e.description])}export const ${a} = {\n NAME: ${j(e.name)},\n${br(yr(e),` `)}${o.join(``)}} as const;`),X(r,`${Y([`An error code of \`${e.name}\`, of the context or of one of its aggregates.`])}export type ${e.typeName}ErrorCode = ${Z(e.errors.map(e=>j(e.code)))};`);let s=e.subscriptions.length>0;s&&X(r,`${Y([`The subscriptions of \`${e.name}\` a \`handled\` hop names.`])}export type ${e.typeName}Subscription = ${Z(e.subscriptions.map(j))};`);let c=`${a}.NAME`,l=[` /** Until a command of \`${e.name}\` passed admission. */\n accepted: (): Hop => wait.accepted(${c}),`,` /** Until a command's events are appended to the log of \`${e.name}\`. */\n committed: (): Hop => wait.committed(${c}),`,` /** Until the snapshot of \`${e.name}\` holds the commit. */\n snapshot: (): Hop => wait.snapshot(${c}),`];s&&l.push(` /** Until a subscription of \`${e.name}\` handled the commit. */\n handled: (subscription: ${e.typeName}Subscription): Hop => wait.handled(subscription, ${c}),`),X(r,`${Y([`The hops of a wait chain (\`Wow-Wait\`) in \`${e.name}\`.`])}export const ${O(e.name)}Wait = {\n${l.join(`
|
|
20
|
+
`)}\n} as const;`)}function Sr(e,t){let n=t.module(`${e.directory}/manifest.ts`),r=`${e.typeName}Manifest`;n.imports.add(J,[`MANIFEST_FORMAT`,`RoutingManifest`]);let i=(e,t,n)=>` { name: ${j(e)}, routes: ${Ar(t)}${n===void 0?``:`, idProperty: ${j(n)}`} },`,a=e.aggregates.map(e=>{let t=[...e.commands.filter(e=>e.routes.length>0).map(e=>i(e.name,e.routes,e.idProperty)),...e.lifecycle.map(e=>i(e.name,e.routes))];return` {\n name: ${j(e.name)},\n commands: [\n${t.join(`
|
|
21
21
|
`)}\n ],\n },`}),o=e.routes.map(e=>` { name: ${j(e.name)}, route: { method: ${j(e.method)}, path: ${j(e.path)} } },`),s=o.length===0?``:` routes: [\n${o.join(`
|
|
22
22
|
`)}\n ],\n`;X(n,`${Y([o.length===0?`The routes of \`${e.name}\`'s commands, as its Manifest lists them: what its command clients send by, with no Manifest fetched and no schema.`:`The routes of \`${e.name}\`'s commands and service routes, as its Manifest lists them: what its clients send by, with no Manifest fetched and no schema.`])}export const ${r}: RoutingManifest = {\n format: MANIFEST_FORMAT,\n contexts: [\n {\n name: ${j(e.name)},\n aggregates: [\n${a.join(`
|
|
23
|
-
`)}\n ],\n${s} },\n ],\n};`)}function
|
|
23
|
+
`)}\n ],\n${s} },\n ],\n};`)}function Cr(e,t,n,r){if(e.routes.length===0)return;let i=t.module(`${e.directory}/routes.ts`),a=`${e.typeName}Routes`;i.imports.add(J,[`RequestOptions`,`WowClientOptions`]),i.imports.add(gr,[`ServiceRoutes`]),i.imports.add(`./manifest.js`,[`${e.typeName}Manifest`]),Q(i,r,n,e.routes.flatMap(e=>[e.requestType,e.responseType,...e.parameters.map(e=>e.type)].filter(e=>e!==void 0).flatMap(e=>e.match(/[A-Za-z_$][A-Za-z0-9_$]*/g)??[])));let o=e.routes.map(t=>wr(e,t));X(i,`${Y([`The service routes of \`${e.name}\`: routes whose handler is the service's own code, each called by its Manifest's name.`])}export class ${a} {\n /** Calls any route of the service by its name. */\n readonly routes: ServiceRoutes;\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.routes = new ServiceRoutes(options, { manifest: ${e.typeName}Manifest });\n }\n\n${o.join(`
|
|
24
24
|
|
|
25
|
-
`)}\n}`)}function
|
|
25
|
+
`)}\n}`)}function wr(e,t){let n=t.parameters.filter(e=>e.location===`path`),r=t.parameters.filter(e=>e.location===`query`),i=n.map(e=>`${e.name}: ${e.type}`);if(t.requestType!==void 0&&i.push(`body: ${t.requestType}`),r.length>0){let e=r.map(e=>`readonly ${A(e.name)}${e.required?``:`?`}: ${e.type}`).join(`; `),t=r.some(e=>e.required);i.push(`query${t?``:`?`}: { ${e} }`)}i.push(`options?: RequestOptions`);let a=t.responseType??`void`,o=[...n.length===0?[]:[`path: { ${n.map(e=>A(e.name)).join(`, `)} }`],...t.requestType===void 0?[]:[`body`],...r.length===0?[]:[`query`]];return`${Y([t.description,`\`${t.method} ${t.path}\``,t.deprecated?`@deprecated The service deprecates this route.`:void 0],` `)} ${A(t.name)}(${i.join(`, `)}): Promise<${a}> {\n return this.routes.call(${j(e.name)}, ${j(t.name)}, { ${o.join(`, `)} }, options) as Promise<${a}>;\n }`}function Tr(e,t,n){let r=t.module(`${e.directory}/client.ts`),a=`${e.typeName}Client`;r.imports.add(J,[`CommandClient`,`WowClientOptions`]),r.imports.add(`./manifest.js`,[`${e.typeName}Manifest`]);let o=[],s=[];for(let t of e.aggregates){let e=t.typeName,a=e=>P(r.directoryPath,(0,i.join)(n,t.directory,e)),c=[[`commands`,`${e}CommandClient`]];t.queryModels.includes(`snapshot`)&&c.push([`snapshots`,`${e}SnapshotQueryClient`]),t.queryModels.includes(`events`)&&c.push([`events`,`${e}EventQueryClient`]),c.push([`state`,`${e}StateClient`]),r.imports.add(a(`commandClient.ts`),[`${e}CommandClient`]),r.imports.add(a(`queryClient.ts`),c.slice(1).map(([,e])=>e));let l=A(O(t.name));o.push(`${Y([`The clients of \`${t.context}.${t.name}\`.`],` `)} readonly ${l}: {\n${c.map(([e,t])=>` readonly ${e}: ${t};`).join(`
|
|
26
26
|
`)}\n };`),s.push(` this.${l} = {\n${c.map(([e,t])=>` ${e}: new ${t}(options),`).join(`
|
|
27
27
|
`)}\n };`)}e.routes.length>0&&(r.imports.add(`./routes.js`,[`${e.typeName}Routes`]),o.push(`${Y([`The service routes of \`${e.name}\`.`],` `)} readonly routes: ${e.typeName}Routes;`),s.push(` this.routes = new ${e.typeName}Routes(options);`)),X(r,`${Y([e.routes.length===0?`The clients of \`${e.name}\`: its command client, and per aggregate its command, query and state clients.`:`The clients of \`${e.name}\`: its command client, per aggregate its command, query and state clients, and its service routes.`])}export class ${a} {\n /** Sends any command of the service, by its Manifest's routes: \`send\`, \`wait\` and \`stream\`. */\n readonly commands: CommandClient;\n\n${o.join(`
|
|
28
28
|
|
|
29
29
|
`)}\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.commands = new CommandClient(options, { manifest: ${e.typeName}Manifest });\n${s.join(`
|
|
30
|
-
`)}\n }\n}`)}function
|
|
30
|
+
`)}\n }\n}`)}function Er(e){return e===!0?`true`:`{ ${Object.entries(e).map(([e,t])=>`${A(e)}: ${Er(t)}`).join(`, `)} }`}function Dr(e){let t=e.textNumbers;return t===void 0?``:` textNumbers: {\n${[`state`,`events`,`commands`].flatMap(e=>{let n=t[e];return n===void 0?[]:e===`state`?[` state: ${Er(n)},`]:[` ${e}: {\n${Object.entries(n).map(([e,t])=>` ${A(e)}: ${Er(t)},`).join(`
|
|
31
31
|
`)}\n },`]}).join(`
|
|
32
|
-
`)}\n },\n`}function
|
|
33
|
-
`)}\n }`:``,h=`${t.typeName}Manifest`;o.imports.add(
|
|
32
|
+
`)}\n },\n`}function Or(e,t,n,r,i){let a=n.module(`${e.directory}/aggregate.ts`),o=e.typeName;X(a,`${Y([`The aggregate \`${e.context}.${e.name}\`.`,e.description])}export const ${o}Aggregate = {\n context: ${j(t.name)},\n name: ${j(e.name)},\n path: ${j(`/${t.name}/${e.name}`)},\n ownership: ${j(e.ownership)},\n${e.idSource===`assigned`?``:` idSource: ${j(e.idSource)},\n`} snapshot: ${e.snapshot},\n${Dr(e)}${br(yr(t,e),` `)}} as const;`),X(a,`${Y([`The \`state.*\` paths of \`${e.name}\`'s snapshots a query filters, sorts and projects on.`])}export type ${o}StateField = ${Z(e.stateFields.map(j))};`);let s=e.events.map(e=>`CommittedEvent<${j(e.wireName)}, ${e.type}>`);a.imports.add(J,s.length>0?[`CommittedEvent`,`SystemEvent`]:[`SystemEvent`]),X(a,`${Y([`The events of \`${e.name}\`, named as the server sends them, \`${e.context}.${e.name}.<Event>\` at its current revision (the \`events\` query upgrades older records), and the system events every aggregate has.`])}export type ${o}Event = ${Z([...s,`SystemEvent`])};`),Q(a,i,r,e.events.map(e=>e.type))}function kr(e,t){let n=(t===void 0?[e.byIdPath,e.unaddressedPath]:[t?e.unaddressedPath:e.byIdPath]).filter(e=>e!==void 0).map(e=>`\`POST ${e.path}\``).join(`, `),r=e.creation===`required`?`Creates the aggregate.`:e.creation===`allowed`?`Creates the aggregate, or acts on the one that exists.`:void 0;return Y([e.description,`\`${e.name}\`${e.mounted?`, mounted (a transformer finds its aggregate)`:``}${t===!0?`, to the caller's own aggregate, whose id is the caller's owner`:``}: ${n}.`,t===!1?"By id, for a caller with no owner; `"+e.ownMethod+"` sends it to the caller's own.":void 0,e.idProperty===void 0?void 0:`Its body names its aggregate: \`${e.idProperty}\`${e.idComputed?`, which the service computes from the fields given`:``}.`,r,e.produces.length>0?`Produces ${e.produces.map(e=>`\`${e}\``).join(`, `)}.`:void 0],` `)}function Ar(e){return`[${e.map(e=>`{ method: ${j(e.method)}, path: ${j(e.path)} }`).join(`, `)}]`}function $(e,t,n,r){let i=e.bodyType===`unknown`?`object`:e.bodyType,a=e.idComputed?`Omit<${i}, ${j(e.idProperty)}>`:i,o=e.bodyOptional?`body: ${a} = {}`:`body: ${a}`,s=n?`stream`:`wait`,c=n?`Promise<CommandResultStream>`:`Promise<CommandResult>`,l=r===!0?e.ownMethod:e.method,u=n?`${l}Stream`:l,d=n?Y([`\`${e.name}\`${r===!0?` to the caller's own aggregate`:``}, answered as one result per hop of its wait (\`text/event-stream\`).`],` `):kr(e,r),f=j(`${t.context}.${t.name}.${e.name}`),p=e=>`{ ...options, command: ${f}, body${e} }`,m=r===void 0?e.byIdPath:!r,h=r===void 0?e.unaddressedPath:r,g=m&&h?`CreateCommandOptions`:`CommandOptions`,ee=m&&!h?`id: string, `:``,_=p(m&&!h?`, id`:``);return n?`${d} ${u}(${ee}${o}, options?: ${g}): ${c} {\n return this.client.${s}(${_});\n }`:jr(d,u,`${ee}${o}`,g,_)}function jr(e,t,n,r,i){return`${e} ${t}(${n?`${n}, `:``}options?: ${r}): Promise<CommandResult> {\n return this.client.wait(${i});\n }`}function Mr(e,t,n,r,a){let o=n.module(`${e.directory}/commandClient.ts`),s=e.typeName,c=e.commands.filter(e=>e.byIdPath||e.unaddressedPath),l=c.flatMap(t=>t.ownMethod===void 0?[$(t,e,!1),$(t,e,!0)]:[!1,!0].flatMap(n=>[$(t,e,!1,n),$(t,e,!0,n)])),u=[`CommandClient`,`CommandResult`,`WowClientOptions`];c.length>0&&u.push(`CommandResultStream`);let d=e=>e.byIdPath!==void 0&&e.unaddressedPath!==void 0&&e.ownMethod===void 0;c.some(d)&&u.push(`CreateCommandOptions`),(c.some(e=>!d(e))||e.lifecycle.length>0)&&u.push(`CommandOptions`);let f=[];for(let t of e.lifecycle){u.push(`LifecycleCommands`),t.bodyType&&(t.bodyGenerated?f:u).push(t.bodyType);let n=t.bodyType?`body: ${t.bodyType}`:``,r=n=>`{ ...options, command: LifecycleCommands.${t.member}, type: { context: ${j(e.context)}, name: ${j(e.name)} }${n?`, id`:``}${t.bodyType?`, body`:``} }`;l.push(jr(Y([t.description,`The lifecycle command \`${t.name}\`.`,t.ownMethod===void 0?void 0:`By id, for a caller with no owner; \`${t.ownMethod}\` sends it to the caller's own.`],` `),t.method,n?`id: string, ${n}`:`id: string`,`CommandOptions`,r(!0))),t.ownMethod!==void 0&&l.push(jr(Y([t.description,`The lifecycle command \`${t.name}\`, to the caller's own aggregate, whose id is the caller's owner.`],` `),t.ownMethod,n,`CommandOptions`,r(!1)))}let p=c.filter(e=>e.bodyNumbers);p.length>0&&o.imports.add(`./aggregate.js`,[`${s}Aggregate`]);let m=p.length?`, bodyNumbers: {\n${p.map(t=>` ${j(`${e.context}.${e.name}.${t.name}`)}: ${s}Aggregate.textNumbers.commands.${A(t.name)===t.name?t.name:`[${j(t.name)}]`},`).join(`
|
|
33
|
+
`)}\n }`:``,h=`${t.typeName}Manifest`;o.imports.add(P(o.directoryPath,(0,i.join)(a,t.directory,`manifest.ts`)),[h]),o.imports.add(J,[...new Set(u)].sort()),Q(o,a,r,[...c.map(e=>e.bodyType),...f]),X(o,`${Y([`Sends the commands of \`${e.context}.${e.name}\` by its service's routes (\`${h}\`). Each method answers the result its wait plan ends with, as \`CommandClient.wait\` does: the server's default plan unless the options give one, \`{ wait: WaitPlan.ACCEPTED }\` to answer once it is accepted. A rejected command rejects with a \`CommandRejectedError\`; anything else that did not succeed with a \`WowProblemError\`.`])}export class ${s}CommandClient {\n readonly client: CommandClient;\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.client = new CommandClient(options, { manifest: ${h}${m} });\n }\n\n${l.join(`
|
|
34
34
|
|
|
35
|
-
`)}\n}`)}function
|
|
36
|
-
`;await
|
|
37
|
-
//# sourceMappingURL=codeGenerator-
|
|
35
|
+
`)}\n}`)}function Nr(e,t,n,r){let i=t.module(`${e.directory}/queryClient.ts`),a=e.typeName,o=e.stateType,s=e.idSource===`owner`,c=s?`OwnStateClient`:`StateClient`,l=[c,`WowClientOptions`],u=[`${a}Aggregate`,`${a}Event`],d=` /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(${a}Aggregate, options);\n }`;e.queryModels.includes(`snapshot`)&&(l.push(`SnapshotQueryClient`),u.push(`${a}StateField`),X(i,`${Y([`Queries the snapshots of \`${e.context}.${e.name}\`: \`POST /${e.context}/${e.name}/snapshot/query\`.`])}export class ${a}SnapshotQueryClient extends SnapshotQueryClient<${o}, ${a}StateField> {\n${d}\n}`)),e.queryModels.includes(`events`)&&(l.push(`EventQueryClient`),X(i,`${Y([`Queries the event streams of \`${e.context}.${e.name}\`, one record per commit: \`POST /${e.context}/${e.name}/events/query\`.`])}export class ${a}EventQueryClient extends EventQueryClient<${a}Event> {\n${d}\n}`)),X(i,`${Y([s?`Reads the states of \`${e.context}.${e.name}\`, at a version or a time, and their traces: the caller's own by no id (\`readOwn\`, \`getOwn\`, \`findOwn\`, \`traceOwn\`: \`GET /${e.context}/${e.name}/state\`), and by id for a caller with no owner (\`GET /${e.context}/${e.name}/{id}/state\`).`:`Reads the states of \`${e.context}.${e.name}\`, at a version or a time, and their traces: \`GET /${e.context}/${e.name}/{id}/state\`.`])}export class ${a}StateClient extends ${c}<${o}, ${a}Event> {\n${d}\n}`),i.imports.add(J,l.sort()),i.imports.add(`./aggregate.js`,u),Q(i,r,n,[o])}function Pr(e){return{openAPI:e,components:e.components,endpoints:Ie(e.paths,e.components)}}var Fr=`.wow-generator.json`,Ir=class e{project;outputPath;outputDir;previous;written=new Set;stale=new Set;constructor(e,t,n,r){this.project=e,this.outputPath=t,this.outputDir=n,this.previous=r}static open(n,r,i){let a=n.getFileSystem(),o=r;r=(0,t.resolve)(a.getCurrentDirectory(),r);let c=(0,t.join)(r,Fr),l=new Map;if(a.fileExistsSync(c)){let e=Lr(c,a.readFileSync(c));for(let[n,i]of Object.entries(e.files)){let e=(0,t.resolve)(r,n);if(Vr(r,e),(0,t.isAbsolute)(n)||!n.endsWith(`.ts`)||typeof i!=`string`||!/^[a-f0-9]{64}$/.test(i))throw new s(`output`,`Invalid generated file entry in ${c}: ${n}`);l.set(e,i)}}let u=new Set([...i?.written??[],...l.keys()]);for(let e of n.getSourceFiles())u.has(e.getFilePath())&&e.forget();return new e(n,o,r,l)}get files(){return this.written}claim(e,t=this.outputPath){let n=f(t,e);Vr(t,n);let r=this.project.getSourceFile(n)??this.project.createSourceFile(n,``,{overwrite:!0}),i=r.getFilePath();return this.written.has(i)||(r.removeText(),this.written.add(i)),r}forgetStale(){for(let[e,t]of this.previous)!this.written.has(e)&&this.isUnchanged(e,t)&&this.stale.add(e);for(let e of this.project.getSourceFiles())this.stale.has(e.getFilePath())&&e.forget()}async commit(e){e?.throwIfAborted();let n=this.project.getFileSystem(),r=new Set([...this.written].map(e=>e.toLowerCase()));for(let e of this.stale)!this.written.has(e)&&r.has(e.toLowerCase())&&this.isUnchanged(e,this.previous.get(e))&&(await Br(`delete`,e,()=>n.delete(e)),this.stale.delete(e));let i=[...this.written].sort().map(e=>this.project.getSourceFileOrThrow(e));(await Promise.allSettled(i.map(e=>e.save()))).forEach((e,t)=>{if(e.status===`rejected`)throw zr(`write`,i[t].getFilePath(),e.reason)}),e?.throwIfAborted();for(let e of this.stale)!this.written.has(e)&&this.isUnchanged(e,this.previous.get(e))&&await Br(`delete`,e,()=>n.delete(e));let a=(0,t.join)(this.outputDir,Fr),o=JSON.stringify({version:1,files:Object.fromEntries(i.map(e=>[(0,t.relative)(this.outputDir,e.getFilePath()).split(t.sep).join(`/`),Rr(n.readFileSync(e.getFilePath()))]))},null,2)+`
|
|
36
|
+
`;await Br(`write`,a,async()=>{n.mkdirSync(this.outputDir),await n.writeFile(a,o)})}isUnchanged(e,t){let n=this.project.getFileSystem();return n.fileExistsSync(e)?(Vr(n.realpathSync(this.outputDir),n.realpathSync(e)),Rr(n.readFileSync(e))===t):!1}};function Lr(e,t){let n=`delete it; without it this run cannot remove the stale files of the last run`,r;try{r=JSON.parse(t)}catch(t){throw new s(`output`,`Cannot parse the generation manifest ${e}: ${c(t)}. Resolve the merge conflict in it if it has one, or ${n}.`,{cause:t})}let i=r?.version;if(typeof i==`number`&&Number.isInteger(i)&&i>1)throw new s(`output`,`The generation manifest ${e} was written by a newer wow-generator (manifest version ${i}); this one reads version 1. Upgrade wow-generator.`);if(i!==1||!r.files||typeof r.files!=`object`||Array.isArray(r.files))throw new s(`output`,`Invalid generation manifest ${e}: expected "version": 1 and a "files" object. Restore it from version control, or ${n}.`);return r}function Rr(t){if(!e.ts.sys.createSHA256Hash)throw Error(`SHA-256 hashing is unavailable in this environment.`);return e.ts.sys.createSHA256Hash(t)}function zr(e,t,n){return n instanceof s?n:new s(`output`,`Cannot ${e} ${t}: ${c(n)}`,{cause:n})}async function Br(e,t,n){try{await n()}catch(n){throw zr(e,t,n)}}function Vr(e,n){let r=n.split(`/`).join(t.sep),i=(0,t.resolve)(e),a=(0,t.resolve)(r),o=(0,t.relative)(i,a);if(o===``||o.startsWith(`..`)||(0,t.isAbsolute)(o))throw new s(`output`,`Path traversal detected: "${n}" resolves outside the output directory "${e}".`)}var Hr=Symbol(`project`),Ur=Symbol(`signal`),Wr=class{options;project;logger;signal;output;constructor(t){this.options=t,this.logger=t.logger??new u,this.signal=t[Ur],this.project=t[Hr]??Gr(t.tsConfigFilePath),this.project.manipulationSettings.set({indentationText:e.IndentationText.TwoSpaces,quoteKind:e.QuoteKind.Single,useTrailingCommas:!0}),this.logger.debug(`Project instance created with tsConfigFilePath: ${this.options.tsConfigFilePath}`)}async generate(){let{logger:e,signal:t,options:n}=this,r=0,i=t=>{for(let n of t)r++,e.warn(n)};e.debug(`Starting code generation`),e.debug(`Work directory: ${process.cwd()}`),e.debug(`Input path: ${n.inputPath}`),e.debug(`Output directory: ${n.outputDir}`);let a={headers:n.headers,timeoutMs:n.timeoutMs,signal:t},o=await Ln(n.configPath,e,a);i(o.warnings),t?.throwIfAborted(),e.debug(`Parsing the input document`);let c=await Nn(n.inputPath,a);if(t?.throwIfAborted(),Jn(c))return this.generateFromManifest(Yn(c,n.inputPath),o.origin,i,()=>r);let l=Pn(c,n.inputPath);e.debug(`OpenAPI specification parsed successfully`);let u=ee(l);if(u.length>0)throw new s(`specification`,`${n.inputPath} has ${u.length} $ref(s) that point at nothing: ${u.slice(0,10).map(({ref:e,location:t})=>`${e} (at ${t})`).join(`, `)}${u.length>10?`, …`:``}`);let d=Pr(l),f=Ir.open(this.project,n.outputDir,this.output);this.output=f,e.debug(`Analysing the document`);let p=ct(d,o.config);i(p.warnings),e.debug(`Writing generated modules`);let m=new dt(e=>f.claim(e));pn(p.model,{modules:m,outputDir:n.outputDir,types:ln(d.components),schemaDocs:n.schemaDocs??`summary`}),m.build(),e.debug(`Generated modules written`),f.forgetStale();let h=this.project.getDirectory(n.outputDir);return h?(e.debug(`Generating index files`),i(mn(h,e=>f.claim(`index.ts`,e))),e.debug(`Optimizing source files`),En(h.getDescendantSourceFiles().filter(e=>f.files.has(e.getFilePath())),e),e.debug(`Source files optimized successfully`)):e.debug(`Output directory not found.`),e.debug(`Saving project to disk`),await f.commit(t),e.debug(`Code generation completed successfully`),{files:[...f.files].sort(),configPath:o.origin,warnings:r}}async generateFromManifest(e,t,n,r){let{logger:i,signal:a,options:o}=this,s=Ir.open(this.project,o.outputDir,this.output);this.output=s,i.debug(`Analysing the Manifest`);let c=lr(e);n(c.warnings);let l=new dt(e=>s.claim(e));_r(c.model,l,o.outputDir),l.build(),s.forgetStale();let u=this.project.getDirectory(o.outputDir);return u&&(n(mn(u,e=>s.claim(`index.ts`,e))),En(u.getDescendantSourceFiles().filter(e=>s.files.has(e.getFilePath())),i)),await s.commit(a),i.debug(`Code generation from the Manifest completed successfully`),{files:[...s.files].sort(),configPath:t,warnings:r()}}};function Gr(t){try{return new e.Project({tsConfigFilePath:t,skipAddingFilesFromTsConfig:!0})}catch(e){throw new s(`configuration`,`Cannot read the TypeScript configuration ${t}: ${c(e)}`,{cause:e})}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return Ur}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Dn}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Wr}});
|
|
37
|
+
//# sourceMappingURL=codeGenerator-CADTvm2G.cjs.map
|