@ahoo-wang/wow-generator 9.7.0 → 9.9.0
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 +2 -1
- package/README.zh-CN.md +1 -1
- package/dist/cli/program.d.cts +7 -0
- package/dist/cli/program.d.ts +7 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +3 -93
- package/dist/cli.js.map +1 -1
- package/dist/codeGenerator-BMyiC0tW.cjs +23 -0
- package/dist/{codeGenerator-CXVxnY-Z.cjs.map → codeGenerator-BMyiC0tW.cjs.map} +1 -1
- package/dist/{codeGenerator-DCYj0aYK.js → codeGenerator-CsWf0pZy.js} +33 -61
- package/dist/{codeGenerator-DCYj0aYK.js.map → codeGenerator-CsWf0pZy.js.map} +1 -1
- package/dist/fetcherGeneratorCli.cjs +3 -0
- package/dist/fetcherGeneratorCli.cjs.map +1 -0
- package/dist/fetcherGeneratorCli.d.cts +8 -0
- package/dist/fetcherGeneratorCli.d.ts +8 -0
- package/dist/fetcherGeneratorCli.js +6 -0
- package/dist/fetcherGeneratorCli.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -2
- package/dist/program-64WQvLq1.js +103 -0
- package/dist/program-64WQvLq1.js.map +1 -0
- package/dist/program-DWjbTSVJ.cjs +10 -0
- package/dist/program-DWjbTSVJ.cjs.map +1 -0
- package/package.json +6 -6
- package/dist/codeGenerator-CXVxnY-Z.cjs +0 -23
package/README.md
CHANGED
|
@@ -23,7 +23,8 @@ second the generator and TypeScript. The generator's peers (`fetcher`,
|
|
|
23
23
|
packages of the first line; `wow-client` has to be on the generator's minor
|
|
24
24
|
version. Node 22.12 or later is required, and TypeScript 6 or later: CI tests
|
|
25
25
|
6.0 through the latest 7.x. The command
|
|
26
|
-
used to be `fetcher-generator`; that name stays as an alias until v10
|
|
26
|
+
used to be `fetcher-generator`; that name stays as an alias until v10 and
|
|
27
|
+
prints a deprecation notice to stderr before it runs.
|
|
27
28
|
|
|
28
29
|
Generated clients are decorator classes, so the project that compiles them
|
|
29
30
|
needs `"experimentalDecorators": true` in its `tsconfig.json`. Released with
|
package/README.zh-CN.md
CHANGED
|
@@ -21,7 +21,7 @@ pnpm exec wow-generator generate \
|
|
|
21
21
|
`fetcher-decorator`、`fetcher-eventstream`、`wow-client`)就是第一行的运行时包;`wow-client`
|
|
22
22
|
须与生成器的次版本一致。需要 Node 22.12 或更高版本,以及 TypeScript 6 或更高版本:CI 测试
|
|
23
23
|
6.0 到最新的 7.x。命令原名
|
|
24
|
-
`fetcher-generator`,这个名字作为别名保留到 v10
|
|
24
|
+
`fetcher-generator`,这个名字作为别名保留到 v10,运行前会向 stderr 打印一行弃用提示。
|
|
25
25
|
|
|
26
26
|
生成的客户端是装饰器类,编译它们的项目需要在 `tsconfig.json` 中设置
|
|
27
27
|
`"experimentalDecorators": true`。随 Wow 9.2.0 发布,与 Wow 同一个 tag、同一个版本号。
|
package/dist/cli/program.d.cts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
import { Command, CommanderError } from 'commander';
|
|
2
|
+
/** The exit codes `generate --help` lists, as the README's table does. */
|
|
3
|
+
export declare const EXIT_CODE_HELP: string;
|
|
4
|
+
/**
|
|
5
|
+
* What the `fetcher-generator` bin prints to stderr before it runs: the name
|
|
6
|
+
* still works, and goes in v10.
|
|
7
|
+
*/
|
|
8
|
+
export declare const DEPRECATED_BIN_NOTICE = "fetcher-generator is deprecated and will be removed in v10; run wow-generator instead.";
|
|
2
9
|
/** Collects the values of an option given more than once, such as `--header`. */
|
|
3
10
|
export declare function collect(value: string, previous?: string[]): string[];
|
|
4
11
|
/**
|
package/dist/cli/program.d.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
import { Command, CommanderError } from 'commander';
|
|
2
|
+
/** The exit codes `generate --help` lists, as the README's table does. */
|
|
3
|
+
export declare const EXIT_CODE_HELP: string;
|
|
4
|
+
/**
|
|
5
|
+
* What the `fetcher-generator` bin prints to stderr before it runs: the name
|
|
6
|
+
* still works, and goes in v10.
|
|
7
|
+
*/
|
|
8
|
+
export declare const DEPRECATED_BIN_NOTICE = "fetcher-generator is deprecated and will be removed in v10; run wow-generator instead.";
|
|
2
9
|
/** Collects the values of an option given more than once, such as `--header`. */
|
|
3
10
|
export declare function collect(value: string, previous?: string[]): string[];
|
|
4
11
|
/**
|
package/dist/cli.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./program-DWjbTSVJ.cjs");e.r(),exports.collect=e.n,exports.runCLI=e.r,exports.setupCLI=e.i;
|
|
3
3
|
//# sourceMappingURL=cli.cjs.map
|
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.cjs","names":["GeneratorError","EXIT_CODES","ConsoleLogger","CodeGenerator","relative","SIGNAL_SEAM","program","DEFAULT_CONFIG_PATH","DEFAULT_HTTP_TIMEOUT_MS","EXIT_CODES","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","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/** 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 // compat(fetcher): package.json also installs this CLI as `fetcher-generator`, the\n // name existing scripts call; drop that bin alias in v10.\n target\n .name('wow-generator')\n .description('OpenAPI Specification TypeScript code generator for Wow')\n .version(VERSION, '-v, --version');\n\n target\n .command('generate')\n .description('Generate TypeScript code from OpenAPI specification')\n .requiredOption(\n '-i, --input <file>',\n 'Input OpenAPI specification 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 .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":["runCLI","require_program"],"sources":["../src/cli.ts"],"sourcesContent":["#!/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":";6GAWKA,EAAAA,EAAO"}
|
package/dist/cli.js
CHANGED
|
@@ -1,98 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import { relative as s } from "path";
|
|
4
|
-
import { CommanderError as c, program as l } from "commander";
|
|
5
|
-
//#region src/version.ts
|
|
6
|
-
var u = "9.7.0";
|
|
7
|
-
//#endregion
|
|
8
|
-
//#region src/cli/runGenerate.ts
|
|
9
|
-
function d(e) {
|
|
10
|
-
if (!e) return !1;
|
|
11
|
-
let t;
|
|
12
|
-
try {
|
|
13
|
-
t = new URL(e);
|
|
14
|
-
} catch {
|
|
15
|
-
return !0;
|
|
16
|
-
}
|
|
17
|
-
return /^[a-z]:$/i.test(t.protocol) ? !0 : t.protocol === "http:" || t.protocol === "https:";
|
|
18
|
-
}
|
|
19
|
-
function f(e = []) {
|
|
20
|
-
let t = {};
|
|
21
|
-
for (let n of e) {
|
|
22
|
-
let e = n.indexOf(":"), r = e > 0 ? n.slice(0, e).trim() : "";
|
|
23
|
-
if (!r) throw new a("input", `Invalid --header "${n}": expected "Name: value".`);
|
|
24
|
-
t[r] = n.slice(e + 1).trim();
|
|
25
|
-
}
|
|
26
|
-
return t;
|
|
27
|
-
}
|
|
28
|
-
function p(e) {
|
|
29
|
-
if (e === void 0) return;
|
|
30
|
-
let t = Number(e);
|
|
31
|
-
if (!Number.isInteger(t) || t <= 0) throw new a("input", `Invalid --timeout "${e}": expected a positive number of milliseconds.`);
|
|
32
|
-
return t;
|
|
33
|
-
}
|
|
34
|
-
function m(e) {
|
|
35
|
-
if (e === void 0 || e === "summary") return "summary";
|
|
36
|
-
if (e === "full") return "full";
|
|
37
|
-
throw new a("input", `Invalid --schema-docs "${e}": expected "summary" or "full".`);
|
|
38
|
-
}
|
|
39
|
-
function h(e) {
|
|
40
|
-
return e.verbose ? "verbose" : e.quiet ? "quiet" : "normal";
|
|
41
|
-
}
|
|
42
|
-
function g(e, t, n) {
|
|
43
|
-
if (t instanceof a) return e.error(t.message), n && t.cause !== void 0 && e.error("Caused by:", t.cause), t.exitCode;
|
|
44
|
-
let i = t instanceof Error ? t.message : String(t);
|
|
45
|
-
return e.error(`Code generation failed: ${i}`), n ? e.error("", t) : e.error("Rerun with --verbose for the stack trace, and report it at https://github.com/Ahoo-Wang/Wow/issues if the input is valid."), r.internal;
|
|
46
|
-
}
|
|
47
|
-
async function _(e, i = new t({ level: h(e) }), a = {}) {
|
|
48
|
-
if (!d(e.input)) return i.error(`Invalid input "${e.input}": expected a file path or an http(s) URL.`), r.input;
|
|
49
|
-
try {
|
|
50
|
-
i.debug(`wow-generator v${u}`);
|
|
51
|
-
let t = {
|
|
52
|
-
...a,
|
|
53
|
-
inputPath: e.input,
|
|
54
|
-
outputDir: e.output,
|
|
55
|
-
configPath: e.config,
|
|
56
|
-
tsConfigFilePath: e.tsConfigFilePath,
|
|
57
|
-
headers: f(e.header),
|
|
58
|
-
timeoutMs: p(e.timeout),
|
|
59
|
-
schemaDocs: m(e.schemaDocs),
|
|
60
|
-
logger: i
|
|
61
|
-
}, n = await new o(t).generate(), c = n.warnings ? `, ${n.warnings} warning${n.warnings === 1 ? "" : "s"}` : "", l = n.configPath ? ` with ${s(process.cwd(), n.configPath) || n.configPath}` : "";
|
|
62
|
-
return i.info(`Generated ${n.files.length} files into ${e.output}${l}${c}`), e.strict && n.warnings > 0 ? (i.error(`--strict: the run logged ${n.warnings} warning${n.warnings === 1 ? "" : "s"}.`), r.specification) : r.success;
|
|
63
|
-
} catch (t) {
|
|
64
|
-
return a[n]?.aborted ? r.interrupted : g(i, t, !!e.verbose);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
async function v(e) {
|
|
68
|
-
let t = new AbortController();
|
|
69
|
-
process.once("SIGINT", () => {
|
|
70
|
-
console.error("Generation interrupted by user"), t.abort();
|
|
71
|
-
}), process.exitCode = await _(e, void 0, { [n]: t.signal });
|
|
72
|
-
}
|
|
73
|
-
//#endregion
|
|
74
|
-
//#region src/cli/program.ts
|
|
75
|
-
function y(e, t = []) {
|
|
76
|
-
return [...t, e];
|
|
77
|
-
}
|
|
78
|
-
function b(t = l) {
|
|
79
|
-
return t.exitOverride(), t.name("wow-generator").description("OpenAPI Specification TypeScript code generator for Wow").version(u, "-v, --version"), t.command("generate").description("Generate TypeScript code from OpenAPI specification").requiredOption("-i, --input <file>", "Input OpenAPI specification file path or URL (http/https)").option("-o, --output <path>", "Output directory path", "src/generated").option("-c, --config <file>", `Configuration file path (default: ${e})`).option("-t, --ts-config-file-path <file>", "TypeScript configuration file path").option("-H, --header <header>", "Request header for an http(s) input or configuration, as \"Name: value\"; repeatable", y).option("--timeout <ms>", `Milliseconds before fetching an http(s) input is abandoned (default: ${i})`).option("--schema-docs <mode>", "What model doc comments carry: \"summary\" (title, description, constraints) or \"full\" (also the JSON schema)", "summary").option("--strict", "Exit with code 4 when the run logs a warning").option("--verbose", "Log every step, and the stack trace of a failure").option("--quiet", "Log only warnings and errors").action(v), t;
|
|
80
|
-
}
|
|
81
|
-
function x(e) {
|
|
82
|
-
return e.exitCode === 0 ? r.success : r.input;
|
|
83
|
-
}
|
|
84
|
-
async function S(e, t = b()) {
|
|
85
|
-
try {
|
|
86
|
-
e === void 0 ? await t.parseAsync() : await t.parseAsync(e, { from: "user" });
|
|
87
|
-
} catch (e) {
|
|
88
|
-
if (!(e instanceof c)) throw e;
|
|
89
|
-
process.exitCode = x(e);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
//#endregion
|
|
2
|
+
import { i as e, n as t, r as n } from "./program-64WQvLq1.js";
|
|
93
3
|
//#region src/cli.ts
|
|
94
|
-
|
|
4
|
+
n();
|
|
95
5
|
//#endregion
|
|
96
|
-
export {
|
|
6
|
+
export { t as collect, n as runCLI, e as setupCLI };
|
|
97
7
|
|
|
98
8
|
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":["DEFAULT_CONFIG_PATH","ConsoleLogger","EXIT_CODES","DEFAULT_HTTP_TIMEOUT_MS","GeneratorError","CodeGenerator","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","relative","SIGNAL_SEAM","generateAction","interruption","collect","previous","setupCLI","program","target","commanderExitCode","runCLI","args","CommanderError"],"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/** 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 // compat(fetcher): package.json also installs this CLI as `fetcher-generator`, the\n // name existing scripts call; drop that bin alias in v10.\n target\n .name('wow-generator')\n .description('OpenAPI Specification TypeScript code generator for Wow')\n .version(VERSION, '-v, --version');\n\n target\n .command('generate')\n .description('Generate TypeScript code from OpenAPI specification')\n .requiredOption(\n '-i, --input <file>',\n 'Input OpenAPI specification 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 .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.js","names":["setupCLI","collect","runCLI"],"sources":["../src/cli.ts"],"sourcesContent":["#!/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":";;;AAWKE,EAAO"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
let e=require("ts-morph"),t=require("path"),n=require("yaml"),r=require("fs");var i=`./wow-generator.config.json`,a={success:0,internal:1,input:2,configuration:3,specification:4,output:5,interrupted:130},o=class extends Error{kind;constructor(e,t,n){super(t,n),this.kind=e,this.name=`GeneratorError`}get exitCode(){return a[this.kind]}};function s(e){return e instanceof Error?e.message:String(e)}function c(){return!!process.stdout?.isTTY&&!process.env.NO_COLOR}var l=class{level;decorate;constructor(e={}){this.level=e.level??`normal`,this.decorate=e.decorate??c()}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)}},u=class{debug(){}info(){}warn(){}error(){}},d=/[^\p{L}\p{N}$]+/u,f=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 p(e){return/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u.test(e)&&!f.has(e)}function m(e){return/^\p{N}/u.test(e)?`_${e}`:e}function h(e){if(p(e))return e;let t=m(v(e)||`_`);return f.has(t)?`${t}_`:t}function ee(e){return/^\p{Lu}[\p{L}\p{N}$]*$/u.test(e)&&p(e)}function te(e){return m((Array.isArray(e)?e:[e]).map(e=>ee(e)?e:re(e)).join(``)||`_`)}function ne(e){return e.split(d)}function g(e){return Array.isArray(e)?e.flatMap(e=>_(ne(e))):_(ne(e))}function _(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 re(e){return e===``||e.length===0?``:g(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 v(e){let t=re(e);return t.charAt(0).toLowerCase()+t.slice(1)}function ie(e){return e===``||Array.isArray(e)&&e.length===0?``:g(e).filter(e=>e.length>0).map(e=>e.toUpperCase()).join(`_`)}function y(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:b(e)}function ae(e){return/^\d+$/.test(e)?`NUM_${e}`:ie(e)||e}function b(e){return`'${JSON.stringify(e).slice(1,-1).replace(/\\"/g,`"`).replace(/'/g,`\\'`)}'`}var oe=new Intl.Collator(`en-US`);function x(e,t){return oe.compare(e,t)}function S(e){return!!(e&&typeof e==`object`&&`$ref`in e)}function se(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 ce(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/`)&&se(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 C=`#/components/`,le=`${C}parameters/`,ue=`${C}requestBodies/`,w=`${C}responses/`,de=`${C}schemas/`;function T(e){return e.$ref.split(`/`).pop()}function E(e,t,n){let r=new Set,i=e;for(;S(i);){if(!i.$ref.startsWith(n))return;if(r.has(i.$ref))throw new o(`specification`,`Cyclic component reference: ${i.$ref}`);r.add(i.$ref),i=t?.[i.$ref.slice(n.length)]}return i}function D(e,t){return E(e,t.schemas,de)}function fe(e,t){return E(e,t.responses,w)}function pe(e,t){return E(e,t.requestBodies,ue)}function me(e,t){return E(e,t.parameters,le)}function O(e,t){return{key:T(e),schema:D(e,t)}}var k=`application/json`,he=`text/event-stream`;function A(e){return e.split(`;`)[0].trim().toLowerCase()}function ge(e){let t=A(e);return t===`application/json`||/^application\/[^/]+\+json$/.test(t)}function _e(e){let t=A(e);return t.startsWith(`text/`)&&t!==`text/event-stream`}function j(e,t,n=e=>A(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 ve(e,t){if(t&&!S(t))return j(t.content,e)?.schema}function ye(e){if(e&&!S(e))return j(e.content,k,ge)?.schema}function be(e){return ve(he,e)}function xe(e){return ve(`*/*`,e)}function Se(e){return!e||S(e)?!1:Object.keys(e.content??{}).some(_e)}var Ce=[`string`,`number`,`integer`,`boolean`,`null`];function we(e){return Array.isArray(e)?!0:Ce.includes(e)}function M(e){return Array.isArray(e.enum)&&e.enum.length>0}var Te=`x-enum-text`;function Ee(e){return e[Te]}function De(e){return e.type===`object`&&!!e.properties}function Oe(e){return e.type===`array`&&!!e.items}function ke(e){return Array.isArray(e.anyOf)&&e.anyOf.length>0}function Ae(e){return Array.isArray(e.oneOf)&&e.oneOf.length>0}function je(e){return Array.isArray(e.allOf)&&e.allOf.length>0}function N(e){return ke(e)||Ae(e)||je(e)}function Me(e){return e.includes(`|`)||e.includes(`&`)?`(${e})[]`:`${e}[]`}function Ne(e){return e.type===`object`&&!e.properties&&e.additionalProperties!==void 0}var Pe=`x-map-key-schema`;function Fe(e){return e[Pe]}function Ie(e){return e.type===`object`?!e.properties||Object.keys(e.properties).length===0:!1}function Le(e){return e.readOnly===!0}function P(e){if(Array.isArray(e))return e.map(e=>P(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 Re(e,t){let n=[],r=new Set,i=new Set,a=!1,o=e=>{if(!(!e||i.has(e)||a)){if(i.add(e),S(e))o(t&&D(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 ze(e,t){return e.operation.operationId&&t.operation.operationId?x(e.operation.operationId,t.operation.operationId):e.path&&t.path?x(e.path,t.path):e.method&&t.method?x(e.method,t.method):0}function Be(e,t,n){let r=new Map;for(let i of[...e,...t]){let e=S(i)?n&&me(i,n):i,t=e?`${e.in}:${e.name}`:i.$ref;r.set(t,i)}return[...r.values()]}function Ve(e,t){let n=[];for(let[r,i]of Object.entries(e))He(i).forEach(e=>{n.push({method:e.method,operation:i.parameters?.length?{...e.operation,parameters:Be(i.parameters,e.operation.parameters??[],t)}:e.operation,path:r})});return n.sort(ze)}function He(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 Ue(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 F(e,t){let n=Ue(e),r=n?e.responses[n]:void 0;return t&&S(r)?fe(r,t):r}function We(e,t){return ye(F(e,t))}function Ge(e,t){return(e.parameters??[]).map(e=>S(e)?me(e,t):e).filter(e=>e!==void 0)}function Ke(e,t){return e.parameters?e.parameters.map(e=>S(e)?me(e,t):e).filter(e=>e?.in===`path`):[]}function qe(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 Je=`string`;function Ye(e){return!e.schema||S(e.schema)||!e.schema.type||!we(e.schema.type)?Je:P(e.schema.type)}var Xe=`8.10`,Ze=`x-wow-context-alias`;function Qe(e){return e.info[Ze]}function $e(e){let t=e.split(`.`);return t.length!=2||t[0].length===0||t[1].length===0?null:t}function et(e){let t=$e(e.name);return t?{tag:e,contextAlias:t[0],aggregateName:t[1]}:null}function tt(e){if(!e)return null;let t=e.split(`.`);return t.length==3?t[2]:null}var nt=`.snapshot_state.single`,rt=`.snapshot.count`,it=`x-wow-query-fields`,at=/^(?:\/tenant\/\{tenantId\})?(?:\/owner\/\{ownerId\})?\/(.+?)\/snapshot(?:\/|$)/,ot=[`MaterializedSnapshot`,`MaterializedSnapshotPagedList`,`MaterializedSnapshotCursorPage`,`MaterializedSnapshotServerSentEventNonNullData`,`PagedList`,`ServerSentEventNonNullData`,`Snapshot`,`StateEvent`];function st(e){return ot.map(t=>e+t)}function ct(e,t,n){return e!==`wow.api.query.PagedList`&&e.startsWith(`wow.api.query.`)&&e.endsWith(`PagedList`)||e.startsWith(`wow.api.query.Operator`)&&e.endsWith(`Map`)?!1:e.startsWith(`wow.`)||e.endsWith(`AggregatedCondition`)||e.endsWith(`AggregatedDomainEventStream`)||e.endsWith(`AggregatedDomainEventStreamPagedList`)||e.endsWith(`AggregatedDomainEventStreamCursorPage`)||e.endsWith(`AggregatedDomainEventStreamServerSentEventNonNullData`)||e.endsWith(`AggregatedListQuery`)||e.endsWith(`AggregatedPagedQuery`)||e.endsWith(`AggregatedSingleQuery`)?!0:n.has(t())}var I=`@ahoo-wang/wow-client`,lt=`@ahoo-wang/wow-client/legacy`,ut=new Set([`Condition`,`ConditionOptions`,`ListQuery`,`Operator`,`PagedQuery`]),dt={"wow.command.CommandResult":`CommandResult`,"wow.command.CommandResultArray":`CommandResultArray`,"wow.MessageHeaderSqlType":`MessageHeaderSqlType`,"wow.api.BindingError":`BindingError`,"wow.api.DefaultErrorInfo":`ErrorInfo`,"wow.api.RecoverableType":`RecoverableType`,"wow.api.command.DefaultDeleteAggregate":`DeleteAggregate`,"wow.api.command.DefaultRecoverAggregate":`RecoverAggregate`,"wow.api.abac.DefaultApplyResourceTags":`ApplyResourceTags`,"wow.api.messaging.FunctionInfoData":`FunctionInfo`,"wow.api.messaging.FunctionKind":`FunctionKind`,"wow.api.modeling.AggregateId":`AggregateId`,"wow.api.query.Condition":`Condition`,"wow.api.query.ConditionOptions":`ConditionOptions`,"wow.api.query.ListQuery":`ListQuery`,"wow.api.query.Operator":`Operator`,"wow.api.query.PagedQuery":`PagedQuery`,"wow.api.query.Pagination":`Pagination`,"wow.api.query.Projection":`Projection`,"wow.api.query.Sort":`FieldSort`,"wow.api.query.Sort.Direction":`SortDirection`,"wow.api.query.DynamicDocument":`DynamicDocument`,"wow.api.query.DynamicDocumentArray":`DynamicDocumentArray`,"wow.command.CommandStage":`CommandStage`,"wow.command.SimpleWaitSignal":`WaitSignal`,"wow.configuration.Aggregate":`Aggregate`,"wow.configuration.BoundedContext":`BoundedContext`,"wow.configuration.WowMetadata":`WowMetadata`,"wow.modeling.DomainEvent":`DomainEvent`,"wow.openapi.BatchResult":`BatchResult`,"wow.messaging.CompensationTarget":`CompensationTarget`};function ft(e,t){let n=dt[e];if(t&&`filter`in t&&(e===`wow.api.query.ListQuery`?n=`FilterListQuery`:e===`wow.api.query.PagedQuery`&&(n=`FilterPagedQuery`)),n)return{name:n,path:ut.has(n)?lt:I}}var pt=new Set([`wow`,`Actuator`]),mt=[`tenantId`,`ownerId`];function ht(e){let t=0,n=0;return e.commands.forEach(e=>{e.path.startsWith(`/tenant/{tenantId}`)&&(t+=1),e.path.startsWith(`/owner/{ownerId}`)&&(n+=1)}),t===0&&n===0?`ResourceAttributionPathSpec.NONE`:t>n?`ResourceAttributionPathSpec.TENANT`:`ResourceAttributionPathSpec.OWNER`}function gt(e,t){return`${e.contextAlias}/${e.aggregateName}/${t}.ts`}function L(e,t){return`${te(e.aggregateName)}${t}`}var _t=`x-fetcher-method`;function vt(e,t){let n=t??e[`x-fetcher-method`];if(n!==void 0){if(typeof n!=`string`||!yt(n))throw new o(`specification`,`${_t} of ${e.operationId??`an operation`} is ${JSON.stringify(n)}, which is not a valid method name.`);return n}if(!e.operationId)return;let r=v(e.operationId.split(`.`).pop())||`_`;return/^\p{N}/u.test(r)?`_${r}`:r}function yt(e){return p(e)||/^[a-z]+$/.test(e)}function bt(e,t){let n=h(e),r=n;for(let e=2;t.has(r);e++)r=`${n}${e}`;return t.add(r),r}function R(e,t){if(!e)return{name:``,path:`/`};let n=ft(e,t?.properties);if(n)return n;let r=e.split(`.`),i=-1;for(let e=0;e<r.length;e++)if(r[e]&&/^[A-Z]/.test(r[e])){i=e;break}let a=r.slice(0,i),o=a.length>0?`/${a.join(`/`)}`:`/`;return{name:te(r.slice(i)),path:o}}function xt(e,t){if(!e.$ref.startsWith(de))throw new o(`specification`,`Unsupported schema reference: ${e.$ref}. Bundle or inline external schemas before generation.`);return R(T(e),t?D(e,t):void 0)}function z(e){let t=`${ie(e)}_BOUNDED_CONTEXT_ALIAS`;return/^\p{N}/u.test(t)?`_${t}`:t}var St=`Command`;function Ct(e,t){return[...t.contexts.values()].flatMap(t=>[...t].map(t=>wt(e,t)))}function wt(e,t){let{contextAlias:n,aggregateName:r}=t.aggregate;return{contextAlias:n,aggregateName:r,context:{alias:n,constantName:z(n)},commandClient:Tt(e,t),queryClient:At(t)}}function Tt(e,t){let n=t.aggregate,r=Ot(t);return{file:gt(n,`commandClient`),endpointPathsName:L(n,`CommandEndpointPaths`),className:L(n,`CommandClient`),streamClassName:L(n,`StreamCommandClient`),commands:[...t.commands.values()].map(t=>{let n=R(t.schema.key),i=new Set([`commandRequest`,`attributes`]);return{path:t.path,endpointMember:r.get(t),httpMethod:t.method,methodName:kt(t),typeName:Et(n),body:n,bodyKey:t.schema.key,optionalFields:Re(t.schema.schema,e.components),requestOptional:Ie(t.schema.schema),pathParameters:qe(t.path,t.pathParameters).filter(e=>!mt.includes(e.name)).map(e=>({name:bt(e.name,i),pathName:e.name,type:Ye(e)})),docs:[t.summary,t.description,`- operationId: \`${t.operation.operationId}\``,`- path: \`${t.path}\``]}})}}function Et(e){return e.path===`@ahoo-wang/wow-client`?`${e.name}Command`:e.name.endsWith(St)?void 0:`${e.name}${St}`}function Dt(e,t){for(let n of e){let e=`/${n.contextAlias}/${n.aggregateName}`,r=new Map;for(let n of t)n.info.path===e&&r.set(n.info.name,{holder:`the model of schema ${n.key}`,key:n.key});for(let{body:e,bodyKey:t}of n.commandClient.commands)e.path!==`@ahoo-wang/wow-client`&&r.set(e.name,{holder:`the model of schema ${t}`,key:t});for(let e of n.commandClient.commands){let{typeName:t,bodyKey:i}=e;if(t===void 0||e.body.path===`@ahoo-wang/wow-client`)continue;let a=r.get(t);if(a!==void 0&&a.bodyKey!==i)throw new o(`specification`,`Command ${e.methodName}() of aggregate ${n.contextAlias}.${n.aggregateName} generates the type ${t} for its body ${i}, but ${a.holder} already has that name. Rename the schema ${i} or ${a.key} in the document.`);r.set(t,{holder:`the type of command ${e.methodName}()`,key:i,bodyKey:i})}}}function Ot(e){let t=new Map,n=new Set;for(let r of e.commands.values()){let e=r.name.toUpperCase().replace(/[^\p{L}\p{N}_$]/gu,`_`);(!e||/^\p{N}/u.test(e))&&(e=`_${e}`);let i=e;for(let t=2;n.has(i);t++)i=`${e}_${t}`;n.add(i),t.set(r,i)}return t}function kt(e){let t=v(e.name)||`_`;return/^\p{N}/u.test(t)?`_${t}`:t}function At(e){let t=e.aggregate,n=v(t.aggregateName)||`_`;return{file:gt(t,`queryClient`),resourceName:e.resourceName,resourceAttribution:ht(e),state:R(e.state.key),fields:R(e.fields.key),eventTitlesName:L(t,`DomainEventTypeMapTitle`),eventTypeName:L(t,`DomainEventType`),events:[...e.events.values()].map(e=>({memberName:y(e.name),title:e.title,body:R(e.schema.key)})),factoryName:`${/^\p{N}/u.test(n)?`_`:``}${n}QueryClientFactory`}}function B(e,t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:t?`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`:e}var jt=`types.ts`;function Mt(e){return B(e.path,jt)}function Nt(e){return`${e}/boundedContext.ts`}function Pt(e){return e.contextAlias!==void 0||e.aggregateTags.size>0}function Ft(e,t){return t?{...e,...t}:e}var It=[`httpRequest`,`attributes`];function Lt(e,t,n,r){return new Rt(e,t,n,r).clients()}var Rt=class{document;wow;config;warnings;basePath;wowDocument;constructor(e,t,n,r){this.document=e,this.wow=t,this.config=n,this.warnings=r,this.wowDocument=Pt(t),t.contextAlias&&(this.basePath={alias:t.contextAlias,constantName:z(t.contextAlias)})}clients(){let e=this.tags(),t=this.groupOperations(e),n=new Map;return[...t.keys()].sort().map(r=>{let i=R(r),a=i;for(let e=2;n.has(V(a));e++)a={...i,name:`${i.name}${e}`};return a!==i&&this.warnings.push(`Tags ${n.get(V(i))} and ${r} both name the API client ${i.name}ApiClient; ${r} generates ${a.name}ApiClient.`),n.set(V(a),r),this.client(e.get(r),a,[...t.get(r)])})}client(e,t,n){let r=`${t.name}ApiClient`,i=t.path;this.wow.contextAlias&&(i=B(this.wow.contextAlias,i)),i=B(i,zt(r));let a=new Map;return{tagName:e.name,className:r,file:i,description:e.description,basePath:this.basePath,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(It),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=vt(n.operation,this.config.apiClients?.[e.name]?.methodNames?.[i]),s=r.get(a);if(s!==void 0)throw new o(`specification`,`Operations ${s} 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=Ge(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`?qe(t.path,o):o)a===`path`&&this.ignoresPathParameter(e.name,r.name)||i.push({parameter:{name:bt(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??(this.wowDocument?mt:[])).includes(t)}body(e,t){if(!e.requestBody)return;let n=S(e.requestBody)?pe(e.requestBody,this.document.components):e.requestBody;if(!n)return;let r=n.required===!0,i=n.content??{},a=j(i,k,ge),o=bt(`body`,t);return a?.schema?{name:o,required:r,content:{kind:`json`,schema:a.schema,optionalFields:Re(a.schema,this.document.components)}}:j(i,`multipart/form-data`)?{name:o,required:r,content:{kind:`formData`}}:j(i,`application/x-www-form-urlencoded`)?{name:o,required:r,content:{kind:`urlEncoded`}}:Object.keys(i).some(_e)?{name:o,required:r,content:{kind:`text`}}:{name:o,required:r,content:{kind:`binary`}}}returns(e){let t=F(e,this.document.components);if(!t)return{kind:`response`};let n=ye(t),r=n||xe(t);if(r)return{kind:`json`,schema:r,wildcard:!n};let i=be(t);if(i){if(S(i)){let e=D(i,this.document.components);if(Oe(e)&&S(e.items)){let t=xt(e.items,this.document.components);return{kind:`eventStream`,items:e.items,serverSentEvent:t.name.includes(`ServerSentEvent`)}}}return{kind:`eventStream`,serverSentEvent:!1}}return Se(t)?{kind:`text`}:{kind:`response`}}groupOperations(e){let t=new Map;for(let n of this.document.endpoints){let r=`${n.method.toUpperCase()} ${n.path}`,i=n.operation.tags??[];if(i.length===0){this.warnings.push(`Skipping ${r}: it has no tag, and the tag names its API client.`);continue}let a=i.filter(t=>e.has(t));if(!(a.length<i.length)){if(!n.operation.operationId)this.warnings.push(`Skipping ${r}: it has no operationId, and the operationId names its method.`);else for(let e of a)t.has(e)||t.set(e,new Set),t.get(e).add(n)}}return t}tags(){let e=new Map;for(let{operation:t}of this.document.endpoints)t.tags?.forEach(t=>{!this.ignoresTag(t)&&!e.has(t)&&e.set(t,{name:t,description:``})});return this.document.openAPI.tags?.forEach(t=>{this.ignoresTag(t.name)||e.set(t.name,t)}),e}ignoresTag(e){return pt.has(e)||this.wow.aggregateTags.has(e)}};function zt(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}.ts`}function V(e){return`${e.path}/${e.name}`.toLowerCase()}function Bt(e){let t=new Set(e.contexts.keys());return e.contextAlias&&t.add(e.contextAlias),[...t].sort().map(e=>({alias:e,constantName:z(e),file:Nt(e)}))}function Vt(e,t){let n=e.components?.schemas;if(!n)return[];let r=Ut(t),i=Ht(e,t),a=Object.keys(n).filter(e=>!ct(e,()=>R(e).name,r)||!e.startsWith(`wow.`)&&i.has(e));Wt(a);let o=Gt(t);return a.map(e=>{let r=n[e],i=R(e);return{key:e,info:i,file:Mt(i),schema:r,docSchema:Ft(r,t.schemaDocOverrides.get(e)),emptyMessageBody:o.has(e)&&Kt(r)}})}function Ht(e,t){let n=new Set,r=new Set,i=e.components??{},a=e=>{if(typeof e!=`object`||!e||r.has(e))return;if(r.add(e),Array.isArray(e)){e.forEach(a);return}let{$ref:t}=e;if(typeof t==`string`&&t.startsWith(`#/components/`)){let[e,...r]=t.slice(C.length).split(`/`),o=r.join(`/`);e===`schemas`&&n.add(o),a(i[e]?.[o])}Object.values(e).forEach(a)};for(let{operation:n}of e.endpoints){let e=n.tags??[];e.length>0&&e.every(e=>!pt.has(e)&&!t.aggregateTags.has(e))&&a(n)}return n}function Ut(e){let t=new Set;for(let n of e.contexts.values())for(let e of n)st(R(e.state.key).name).forEach(e=>t.add(e));return t}function Wt(e){let t=new Map;for(let n of e){let e=R(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 o(`specification`,`Schemas generate the same model: ${n.map(([e,t])=>`${t.join(`, `)} → ${e}`).join(`; `)}. Rename all but one of them in the document.`)}function Gt(e){return new Set([...e.contexts.values()].flatMap(e=>[...e].flatMap(e=>[...[...e.commands.values()].map(e=>e.schema.key),...[...e.events.values()].map(e=>e.schema.key)])))}function Kt(e){return!S(e)&&e.type===`object`&&Object.keys(e.properties??{}).length===0&&(e.additionalProperties===void 0||e.additionalProperties===!1)&&!e.required?.length&&!N(e)&&e.enum===void 0&&e.const===void 0}function qt(e,t,n){let r=[],i=Bt(t),a=Vt(e,t),o=Ct(e,t);return Dt(o,a),{model:{contexts:i,models:a,aggregates:o,apiClients:Lt(e,t,n,r)},warnings:r}}var Jt=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})}))}},Yt=class{sourceFile;imports=new Jt;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&&Qt(n,e)&&t.push(Zt),t.push(e),n=e;return t.length>0&&this.sourceFile.addStatements(t),this.sourceFile}},Xt=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 Yt(t),this.modules.set(n,r)),r}build(){for(let e of this.modules.values())e.build();this.modules.clear()}},Zt=e=>{e.blankLineIfLastNot()};function Qt(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 $t(e){return e.map(e=>({...e,initializer:`${e.initializer},`}))}function en(e,t){return{name:`[key: string]`,type:e,docs:t}}var tn=`@`;function H(e,t,n){return e.imports.add(t,n)}function U(e,t,n){return H(e,W(e,t,n),[n.name])}function W(e,n,r){return r.path.startsWith(tn)?r.path:nn(e.directoryPath,(0,t.join)(n,r.path,jt))}function nn(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 G(e,n,r,i){return H(e,nn(e.directoryPath,(0,t.join)(n,Nt(r))),[i])}function rn(e,t=`
|
|
2
|
+
`){if(!Array.isArray(e))return;let n=e.filter(e=>typeof e==`string`&&e.length>0).map(an);return n.length>0?n.join(t):void 0}function an(e){return e.replace(/\*\//g,`*\\/`)}function K(e,t){let n=rn(t);n&&(e.docs=[...e.docs??[],n])}function on(e,t,n=!1){e=ln(e);let r=[e.title,e.description];return t&&r.push(`- key: ${t}`),n&&un(r,e),e.format&&r.push(e.format===`int64`?`- format: int64 (a value beyond Number.MAX_SAFE_INTEGER loses precision)`:`- format: ${e.format}`),dn(r,e,`default`),dn(r,e,`example`),pn(r,e),mn(r,e),hn(r,e),r}function sn(e,t,n){K(e,on(t,n))}function cn(e,t,n,r=!1){let i=on(t,n,!0);r&&fn(i,`schema`,t),K(e,i)}function ln(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 un(e,t){let n=t.required??[];(n.length||Object.keys(t.properties??{}).length)&&e.push(`- required: ${n.length?n.join(`, `):`(none)`}`)}function dn(e,t,n){let r=t[n];r&&(typeof r==`object`?fn(e,n,r):e.push(`- ${n}: \`${r}\``))}function fn(e,t,n){e.push(`- ${t}: `),e.push("```json"),e.push(JSON.stringify(n,null,2)),e.push("```")}function pn(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 mn(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 hn(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 gn(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 _n=[`Array`,`Blob`,`Exclude`,`FormData`,`Partial`,`Promise`,`ReadonlyArray`,`Record`,`Response`,`Symbol`,`URLSearchParams`],vn=new Set([`string`,`number`,`boolean`]),yn=new Set([`$comment`,`$schema`,`default`,`deprecated`,`description`,`example`,`examples`,`externalDocs`,`readOnly`,`title`,`writeOnly`,`xml`]);function bn(e,t){return e===void 0?!1:typeof e==`string`||typeof t==`string`?e===t:e.primitive===t.primitive}function q(e,t,n=new Set){if(S(e)){if(!t||n.has(e.$ref))return;n.add(e.$ref);let r=D(e,t);return r?q(r,t,n):void 0}if(!(e.nullable||Array.isArray(e.type))){if(je(e)&&e.type===void 0){let r=e.allOf.map(e=>q(e,t,n)),[i]=r;return i!==void 0&&r.every(e=>bn(e,i))?i:void 0}if(!(N(e)||e.const!==void 0||e.type===void 0))return e.type===`object`?`object`:e.type===`array`?`array`:{primitive:P(e.type)}}}function xn(e,t,n){let r=q(t,n);if(typeof r!=`object`)return!1;let i=q(e,n);return i===void 0||typeof i==`string`||i.primitive!==r.primitive}function Sn(e,t){let n=e.additionalProperties;return typeof n==`object`&&Object.values(e.properties??{}).some(e=>xn(e,n,t))}function Cn(e){return e.nullable!==!0||M(e)||!N(e)?!1:[e.allOf,e.oneOf,e.anyOf].every(e=>e===void 0||e.every(S))}function wn(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 J(t){if(typeof t==`string`)return new e.CodeBlockWriter({useSingleQuote:!0}).quote(t).toString();if(Array.isArray(t))return`[${t.map(e=>J(e)).join(`, `)}]`;if(typeof t==`object`&&t){let e=Object.entries(t).map(([e,t])=>`${y(e)}: ${J(t)}`);return e.length?`{ ${e.join(`; `)}; readonly [globalThis.Symbol.iterator]?: never }`:`globalThis.Record<string, never>`}return JSON.stringify(t)??`never`}var Tn=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([..._n,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=(Le(t)?`readonly `:``)+y(e);if(!S(t)){let e=rn(on(t),`
|
|
3
|
+
* `);if(e)return`
|
|
4
|
+
/**
|
|
5
|
+
* ${e}
|
|
6
|
+
*/
|
|
7
|
+
${r}: ${n}
|
|
8
|
+
`}return`${r}: ${n}`})}objectType(e){let t=[];De(e)&&t.push(...this.propertyDefinitions(e));for(let n of e.required??[])Object.hasOwn(e.properties??{},n)||t.push(`${y(n)}: ${this.requiredAdditionalPropertyType(e)}`);let n=Ne(e)&&Fe(e)?this.mapType(e):Sn(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=Fe(e);return t?this.type(t):`string`}mapType(e){return`globalThis.Record<${this.mapKeyType(e)},${this.mapValueType(e)}>`}objectConstrained(e){let t=e=>S(e)?this.components&&D(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(S(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(Cn(e))return`(${this.type({...e,nullable:!1})}) | null`;if(N(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(!wn(e.const,e))return`never`;let t=J(e.const),n=this.type({...e,const:void 0});return n===`any`?t:`(${t}) & (${n})`}if(e.nullable&&e.type&&!M(e))return`(${this.type({...e,nullable:!1})}) | null`;if(M(e)){let t=e.enum.filter(t=>wn(t,e)).map(e=>J(e)).join(` | `)||`never`,n=this.type({...e,enum:void 0});return n===`any`||vn.has(n)?t:`(${t}) & (${n})`}return Ne(e)&&!e.required?.length?this.mapType(e):e.type===`array`?Me(this.type(e.items??{})):e.type===`object`?this.objectType(e):e.type?P(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-`)&&!yn.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`||yn.has(e));if(!r.every(e=>S(e)||i(e)))return;let a=r.map(t=>S(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||!S(n))return r;let a=T(n),o=Object.entries(i.mapping??{}).filter(([,e])=>e===n.$ref||e===a).map(([e])=>e),s=(o.length>0?o:[a]).map(e=>b(e)).join(` | `);return`(${r} & { ${y(i.propertyName)}: ${s} })`}};function Y(e,t){let n=new Tn(e);return{text:t(n),imports:n.imports()}}function En(e,t){return Y(t,t=>t.type(e))}function Dn(e,t){return Y(t,t=>t.additionalProperties(e))}function On(e,t){return Y(t,t=>t.additionalPropertyType(e))}function kn(e,t){return Y(t,t=>t.requiredAdditionalPropertyType(e))}function An(e,t){return Y(t,t=>t.mapValueType(e))}var jn=`@ahoo-wang/fetcher`,Mn=[`ContentTypeValues`,`ResultExtractors`],Nn=`@ahoo-wang/fetcher-decorator`,Pn=[`ApiMetadata`,`ApiMetadataCapable`,`ParameterRequest`,`api`,`get`,`post`,`put`,`patch`,`del`,`request`,`attribute`,`path`,`query`,`header`,`body`,`autoGeneratedError`],Fn={type:`Promise<Response>`,metadata:`{resultExtractor: ResultExtractors.Response }`},In={type:`Promise<string>`,metadata:`{resultExtractor: ResultExtractors.Text }`},Ln=`{
|
|
10
|
+
headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },
|
|
11
|
+
resultExtractor: JsonEventStreamResultExtractor,
|
|
12
|
+
}`,Rn=`COMMAND_STREAM_ENDPOINT`;function zn(e){H(e,jn,Mn)}function Bn(e){H(e,Nn,Pn)}function Vn(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 Hn(t,n){t.implements=[...[t.implements??[]].flat(),`ApiMetadataCapable`],t.ctors??=[],n===void 0?t.ctors.push({parameters:[{name:`apiMetadata`,type:`ApiMetadata`,hasQuestionToken:!0,scope:e.Scope.Public,isReadonly:!0}]}):(t.properties=[...t.properties??[],{name:`apiMetadata`,type:`ApiMetadata`,isReadonly:!0}],t.ctors.push({parameters:[{name:`apiMetadata`,type:`ApiMetadata`,hasQuestionToken:!0}],statements:`this.apiMetadata = { ${n}, ...apiMetadata };`,docs:["@param apiMetadata - Merged over the defaults, so passing only a `fetcher` keeps the base path."]}))}function Un(e){return e===`delete`?`del`:e}var Wn=`@ahoo-wang/fetcher-eventstream`;function Gn(e){H(e,Wn,[`JsonEventStreamResultExtractor`,`JsonServerSentEventStream`])}function Kn(e,t){let n=t.modules.module(e.file);zn(n),Bn(n),Gn(n);let r=Vn(e.className,n);K(r,[e.description]);let i;e.basePath&&(G(n,t.outputDir,e.basePath.alias,e.basePath.constantName),i=`basePath: ${e.basePath.constantName}`),Hn(r,i);let a=qn(e.className,n,t);for(let t of e.methods)(r.methods??=[]).push(Jn(t,a))}function qn(e,t,n){let r={context:n.types,owner:{name:e},specifierOf:e=>W(t,n.outputDir,e),imports:t.imports};return{module:t,resolveType(e){let n=En(e,r);return t.imports.apply(n.imports),n.text}}}function Jn(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:[b(i.parameterName)]}]});e.body&&(e.body.required?n:r).push({name:e.body.name,type:Yn(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=Xn(e.returns,t),o=b(e.path),s={name:e.name,decorators:[{name:Un(e.httpMethod),arguments:a.metadata?[o,a.metadata]:[o]}],parameters:i,returnType:a.type,statements:[`throw autoGeneratedError(${i.map(e=>e.name).join(`,`)});`]};return K(s,[...e.docs]),s}function Yn(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:(H(t.module,jn,[`PartialBy`]),`PartialBy<${e}, ${r.map(b).join(` | `)}>`)}case`formData`:return`FormData`;case`urlEncoded`:return`URLSearchParams`;case`text`:return`string`;case`binary`:return`BodyInit`}}function Xn(e,t){switch(e.kind){case`json`:{let n=t.resolveType(e.schema);return e.wildcard&&n===`string`?In:{type:`Promise<${n}>`}}case`eventStream`:{if(!e.items)return{type:`Promise<JsonServerSentEventStream<any>>`,metadata:Ln};let n=t.resolveType(e.items);return{type:`Promise<JsonServerSentEventStream<${e.serverSentEvent?`${n}['data']`:n}>>`,metadata:Ln}}case`text`:return In;case`response`:return Fn}}var Zn=`DEFAULT_COMMAND_CLIENT_OPTIONS`;function Qn(t,n){let r=t.commandClient;if(r.commands.length===0)return;let i=n.modules.module(r.file);i.add({kind:e.StructureKind.Enum,name:r.endpointPathsName,isExported:!0,members:$t(r.commands.map(e=>({name:e.endpointMember,initializer:b(e.path)})))});let a=new Set,o=r.commands.map(e=>$n(i,n.outputDir,e,a));G(i,n.outputDir,t.context.alias,t.context.constantName),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:Zn,type:`ApiMetadata`,initializer:`{
|
|
13
|
+
basePath: ${t.context.constantName}
|
|
14
|
+
}`}],isExported:!1}),H(i,I,[`CommandRequest`,`CommandResult`,`CommandResultEventStream`,`CommandBody`,Rn]),H(i,`@ahoo-wang/fetcher`,[`PartialBy`]),Bn(i);let s=Vn(r.className,i,[],[`R = CommandResult`]);Hn(s,`...${Zn}`);for(let[e,t]of r.commands.entries()){let n=er(t,o[e]),i={name:t.methodName,decorators:[{name:Un(t.httpMethod),arguments:[`${r.endpointPathsName}.${t.endpointMember}`]}],parameters:n,returnType:`Promise<R>`,statements:`throw autoGeneratedError(${n.map(e=>e.name).join(`,`)});`};(s.methods??=[]).push(i),K(i,[...t.docs])}Vn(r.streamClassName,i,[`''`,Rn],[],`${r.className}<CommandResultEventStream>`)}function $n(t,n,r,i){if(r.body.path===`@ahoo-wang/wow-client`)return H(t,I,[r.typeName]),r.typeName;U(t,n,r.body);let a=r.body.name,o=r.optionalFields.map(b).join(` | `);o!==``&&(a=`PartialBy<${a},${o}>`);let s=`CommandBody<${a}>`;return r.typeName===void 0?s:(i.has(r.typeName)||(i.add(r.typeName),t.add({kind:e.StructureKind.TypeAlias,name:r.typeName,type:s,isExported:!0})),r.typeName)}function er(e,t){return[...e.pathParameters.map(e=>({name:e.name,type:e.type,hasQuestionToken:!1,decorators:[{name:`path`,arguments:[b(e.pathName)]}]})),{name:`commandRequest`,hasQuestionToken:e.requestOptional,type:`CommandRequest<${t}>`,decorators:[{name:`request`,arguments:[]}]},{name:`attributes`,hasQuestionToken:!0,type:`Record<string, unknown>`,decorators:[{name:`attribute`,arguments:[]}]}]}function tr(e){return gn(e,{ofKey:e=>R(e),ofReference:xt})}function nr(t,n){let r=n.modules.module(t.file);t.emptyMessageBody?cn(r.add({kind:e.StructureKind.TypeAlias,name:t.info.name,type:`globalThis.Record<string, never>`,isExported:!0}),t.docSchema,t.key,n.schemaDocs===`full`):new ir(t,r,n).write()}function rr(e){let t=new Set,n=new Map;for(let r of e){let e=ae(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,y(a))}return n}var ir=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=>W(t,n.outputDir,e),imports:t.imports}}write(){let e=this.process();e&&cn(e,this.model.docSchema,this.model.key,this.target.schemaDocs===`full`)}process(){let{schema:e}=this.model;return S(e)?this.processTypeAlias(e):M(e)?this.processEnum(e):e.const!==void 0||e.nullable&&e.type||N(e)&&(e.type||e.properties||e.required)?this.processTypeAlias(e):De(e)?this.processInterface(e):Ne(e)&&typeof e.additionalProperties==`object`&&!Fe(e)&&!e.required?.length?this.processIndexSignature(e):Oe(e)?this.processArray(e):N(e)?this.processComposition(e):this.processTypeAlias(e)}scope;emit(e){return this.module.imports.apply(e.imports),e.text}resolveType(e){return this.emit(En(e,this.scope))}processEnum(t){let n=Ee(t);if(n){let t=rr(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:J(n[e])}))})}let r=[...new Set(t.enum.filter(e=>typeof e==`string`))],i=rr(r);return N(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:J(e)}))})}addPropertyToInterface(e,t,n){let r={name:y(t),type:this.resolveType(n),isReadonly:Le(n)};(e.properties??=[]).push(r),sn(r,n)}processInterface(t){if(Sn(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:y(e),type:this.emit(kn(t,this.scope))});return this.emit(Dn(t,this.scope))&&n.push(en(this.emit(On(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:Me(n),isExported:!0})}processIndexSignature(t){return this.module.add({kind:e.StructureKind.Interface,name:this.modelInfo.name,isExported:!0,properties:[en(this.emit(An(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})}},ar=`DEFAULT_QUERY_CLIENT_OPTIONS`;function or(t,n){let r=t.queryClient,i=n.modules.module(r.file);H(i,I,[`QueryClientFactory`,`QueryClientOptions`,`ResourceAttributionPathSpec`]),G(i,n.outputDir,t.context.alias,t.context.constantName),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:ar,type:`QueryClientOptions`,initializer:`{
|
|
15
|
+
contextAlias: ${t.context.constantName},
|
|
16
|
+
aggregateName: ${b(r.resourceName)},
|
|
17
|
+
resourceAttribution: ${r.resourceAttribution},
|
|
18
|
+
}`}],isExported:!1}),i.add({kind:e.StructureKind.Enum,name:r.eventTitlesName,isExported:!0,members:$t(r.events.map(e=>({name:e.memberName,initializer:b(e.title)})))});for(let e of r.events)U(i,n.outputDir,e.body);i.add({kind:e.StructureKind.TypeAlias,isExported:!0,name:r.eventTypeName,type:r.events.map(e=>e.body.name).join(` | `)||`never`}),U(i,n.outputDir,r.state),U(i,n.outputDir,r.fields),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:r.factoryName,initializer:`new QueryClientFactory<${r.state.name}, \`\${${r.fields.name}}\`, ${r.eventTypeName}>(${ar})`}],isExported:!0})}function sr(e,t){e.contexts.forEach(e=>cr(e,t)),e.models.forEach(e=>nr(e,t)),e.aggregates.forEach(e=>or(e,t)),e.aggregates.forEach(e=>Qn(e,t)),e.apiClients.forEach(e=>Kn(e,t))}function cr(e,t){t.modules.module(e.file).add(`export const ${e.constantName} = ${b(e.alias)};`)}function lr(e,t){let n=[];return ur(e,t,n),n}function ur(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:fr(t)})}for(let i of e.getDirectories()){let e=ur(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:dr(i,r,t,n)}function dr(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])=>x(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 fr(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 pr(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 mr(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())&&!pr(t)){let e=t.getSymbol();e&&i.add(e.compilerSymbol)}}),n.map(e=>hr(e,e=>{let t=e.getSymbol();return!!t&&!i.has(t.compilerSymbol)}))}function hr(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 gr(e){let t=e.flatMap(mr);for(let e of t)e()}var _r=new Set([2300,2304,2308,2393,2451,2456,2503,2552]);function vr(t){let n=[];for(let r of t)for(let t of r.getPreEmitDiagnostics()){if(!_r.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(`
|
|
19
|
+
`)}`)}var yr=`// Code generated by wow-generator. DO NOT EDIT.
|
|
20
|
+
|
|
21
|
+
`,br={indentSize:2,tabSize:2,convertTabsToSpaces:!0,semicolons:`insert`,insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces:!0};function xr(e,t){e.forEach((n,r)=>{t.debug(`Optimizing file [${n.getFilePath()}] - ${r+1}/${e.length}`),n.formatText(br),n.organizeImports(br)}),gr(e),vr(e);for(let t of e)t.insertText(0,yr)}var Sr=3e4;function Cr(e){return/^https?:\/\//i.test(e)}function wr(e,t={}){return Cr(e)?Tr(e,t):Dr(e)}async function Tr(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`:Er(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 Er(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 Dr(e){return new Promise((t,n)=>{(0,r.readFile)(e,`utf-8`,(e,r)=>{e?n(e):t(r)})})}async function Or(e,t){let n;try{n=await wr(e,t)}catch(t){throw new o(`input`,`Cannot read the OpenAPI document ${e}: ${s(t)}`,{cause:t})}let r;try{r=Ar(n)}catch(t){throw new o(`input`,`Cannot parse the OpenAPI document ${e}: ${s(t)}`,{cause:t})}return kr(r,e)}function kr(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new o(`input`,`${t} is not an OpenAPI document: expected an object at the top level.`);let n=e;if(n.swagger!==void 0)throw new o(`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 o(`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 o(`input`,`${t} is not a valid OpenAPI document: its "info" object is missing.`);return{...n,paths:n.paths??{}}}function Ar(e){switch(jr(e)){case`json`:return JSON.parse(e);case`yaml`:return(0,n.parse)(e)}}function jr(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`)}var Mr=`./fetcher-generator.config.json`;async function Nr(e,t,n){if(e!==void 0)return{...await Ir({path:e,explicit:!0},t,n),origin:X(e)};for(let e of[i,Mr]){let r=await Ir({path:e,explicit:!1},t,n);if(r===void 0)continue;let a=[...r.warnings];return e===`./fetcher-generator.config.json`&&a.push(`${X(e)} uses the deprecated name; rename it to ${i.slice(2)}. The old name is no longer read from v10.`),{config:r.config,origin:X(e),warnings:a}}return t.debug(`No configuration file found, generating with defaults`),{config:{},warnings:[]}}var Pr=[`apiClients`],Fr=[`ignorePathParameters`,`methodNames`];async function Ir(e,t,n){let r=X(e.path);t.debug(`Reading configuration: ${r}`);let i;try{i=await wr(e.path,n)}catch(n){if(!e.explicit&&Lr(n)){t.debug(`No configuration file at ${r}`);return}throw new o(`configuration`,`Cannot read configuration ${r}: ${s(n)}`,{cause:n})}if(!i.trim())return{config:{},warnings:[`Configuration ${r} is empty, generating with defaults`]};let a;try{a=Ar(i)}catch(e){throw new o(`configuration`,`Cannot parse configuration ${r}: ${s(e)}`,{cause:e})}let c=zr(a,r);return t.debug(`Configuration loaded from ${r}: ${Vr(c.config)}`),c}function X(e){return Cr(e)||(0,t.isAbsolute)(e)?e:(0,t.resolve)(e)}function Lr(e){return typeof e==`object`&&!!e&&e.code===`ENOENT`}function Z(e){return e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rr(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 zr(e,t){if(!Q(e))throw new o(`configuration`,`Configuration ${t} must be a JSON or YAML object, found ${Z(e)}`);let n=[];return Rr(n,t,`configuration`,e,Pr),Br(e.apiClients,t,n),{config:e,warnings:n}}function Br(e,t,n){if(e!==void 0){if(!Q(e))throw new o(`configuration`,`apiClients in ${t} must be an object keyed by tag name, found ${Z(e)}`);for(let[r,i]of Object.entries(e)){if(!Q(i))throw new o(`configuration`,`apiClients["${r}"] in ${t} must be an object, found ${Z(i)}`);Rr(n,t,`apiClients["${r}"]`,i,Fr);let{ignorePathParameters:e}=i;if(e!==void 0&&!(Array.isArray(e)&&e.every(e=>typeof e==`string`)))throw new o(`configuration`,`apiClients["${r}"].ignorePathParameters in ${t} must be an array of strings, found ${Z(e)}`);let{methodNames:a}=i;if(a!==void 0){if(!Q(a))throw new o(`configuration`,`apiClients["${r}"].methodNames in ${t} must be an object mapping operationIds to method names, found ${Z(a)}`);for(let[e,n]of Object.entries(a))if(typeof n!=`string`||!p(n))throw new o(`configuration`,`apiClients["${r}"].methodNames["${e}"] in ${t} must be a valid method name, found ${JSON.stringify(n)}`)}}}}function Vr(e){let t=Object.keys(e.apiClients??{});return`apiClients=${t.length?t.join(`, `):`none`}`}function Hr(e){return{openAPI:e,components:e.components,endpoints:Ve(e.paths,e.components)}}var Ur=`.wow-generator.json`,Wr=`.fetcher-generator.json`,Gr=class e{project;outputPath;outputDir;previous;legacyManifest;written=new Set;stale=new Set;constructor(e,t,n,r,i){this.project=e,this.outputPath=t,this.outputDir=n,this.previous=r,this.legacyManifest=i}static open(n,r,i){let a=n.getFileSystem(),s=r;r=(0,t.resolve)(a.getCurrentDirectory(),r);let c=(0,t.join)(r,Wr),l=a.fileExistsSync(c)?c:void 0,u=(0,t.join)(r,Ur);!a.fileExistsSync(u)&&l&&(u=l);let d=new Map;if(a.fileExistsSync(u)){let e=Kr(u,a.readFileSync(u));for(let[n,i]of Object.entries(e.files)){let e=(0,t.resolve)(r,n);if(Yr(r,e),(0,t.isAbsolute)(n)||!n.endsWith(`.ts`)||typeof i!=`string`||!/^[a-f0-9]{64}$/.test(i))throw new o(`output`,`Invalid generated file entry in ${u}: ${n}`);d.set(e,i)}}let f=new Set([...i?.written??[],...d.keys()]);for(let e of n.getSourceFiles())f.has(e.getFilePath())&&e.forget();return new e(n,s,r,d,l)}get files(){return this.written}claim(e,t=this.outputPath){let n=B(t,e);Yr(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 $(`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 Jr(`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 $(`delete`,e,()=>n.delete(e));let a=(0,t.join)(this.outputDir,Ur),o=JSON.stringify({version:1,files:Object.fromEntries(i.map(e=>[(0,t.relative)(this.outputDir,e.getFilePath()).split(t.sep).join(`/`),qr(n.readFileSync(e.getFilePath()))]))},null,2)+`
|
|
22
|
+
`;await $(`write`,a,async()=>{n.mkdirSync(this.outputDir),await n.writeFile(a,o)});let s=this.legacyManifest;s&&n.fileExistsSync(s)&&await $(`delete`,s,()=>n.delete(s))}isUnchanged(e,t){let n=this.project.getFileSystem();return n.fileExistsSync(e)?(Yr(n.realpathSync(this.outputDir),n.realpathSync(e)),qr(n.readFileSync(e))===t):!1}};function Kr(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 o(`output`,`Cannot parse the generation manifest ${e}: ${s(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 o(`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 o(`output`,`Invalid generation manifest ${e}: expected "version": 1 and a "files" object. Restore it from version control, or ${n}.`);return r}function qr(t){if(!e.ts.sys.createSHA256Hash)throw Error(`SHA-256 hashing is unavailable in this environment.`);return e.ts.sys.createSHA256Hash(t)}function Jr(e,t,n){return n instanceof o?n:new o(`output`,`Cannot ${e} ${t}: ${s(n)}`,{cause:n})}async function $(e,t,n){try{await n()}catch(n){throw Jr(e,t,n)}}function Yr(e,n){let r=n.split(`/`).join(t.sep),i=(0,t.resolve)(e),a=(0,t.resolve)(r),s=(0,t.relative)(i,a);if(s===``||s.startsWith(`..`)||(0,t.isAbsolute)(s))throw new o(`output`,`Path traversal detected: "${n}" resolves outside the output directory "${e}".`)}function Xr(e){let{openAPI:t,components:n,endpoints:r}=e,i=[],a=new Map,s=new Set,c=t.tags??[],l=new Set(c.map(e=>e.name)),u=new Set(r.flatMap(e=>e.operation.tags??[]).filter(e=>!l.has(e))),d=new Map;for(let e of[...c,...[...u].map(e=>({name:e}))]){let t=et(e);t&&d.set(e.name,{aggregate:t,commands:new Map,events:new Map})}let f=e=>(e.tags??[]).flatMap(e=>{let t=d.get(e);return t?(s.add(e),[t]):[]}),p=(e,t,n)=>{let r=a.get(e.key);r||(r={},a.set(e.key,r));let i=t in r?r[t]:e.schema[t];r[t]=i||n},m=(e,t)=>new o(`specification`,`Cannot read the Wow metadata of ${e.operationId}: ${t}. wow-generator reads documents from Wow ${Xe} or later.`),h=(e,t)=>{let n=at.exec(t)?.[1];n&&e.forEach(e=>{e.resourceName??=n})},ee=e=>{let{operation:t,path:r}=e;if(t.operationId===`wow.command.send`)return;let a=tt(t.operationId);if(!a)return;let s=F(t),c=new Set;for(;s&&S(s)&&s.$ref!==`#/components/responses/wow.CommandOk`;){if(!s.$ref.startsWith(w))return;if(c.has(s.$ref))throw new o(`specification`,`Cyclic component reference: ${s.$ref}`);c.add(s.$ref),s=n?.responses?.[s.$ref.slice(w.length)]}if(!s||!S(s)||s.$ref!==`#/components/responses/wow.CommandOk`)return;let l=f(t);if(!t.requestBody)return;let u=Ke(t,n??{}),d=(S(t.requestBody)?pe(t.requestBody,n??{}):t.requestBody)?.content?.[k]?.schema;if(!S(d)){l.length>0&&i.push(`Skipping command ${t.operationId} (${e.method.toUpperCase()} ${r}): its application/json request body is not a $ref to a component schema.`);return}let m=O(d,n??{});if(!m.schema)return;p(m,`title`,t.summary),p(m,`description`,t.description);let h={name:a,method:e.method,path:r,pathParameters:u,summary:t.summary,description:t.description,schema:m,operation:t};l.forEach(e=>{e.commands.set(a,h)})},te=({operation:e,path:t})=>{if(!e.operationId?.endsWith(`.snapshot_state.single`))return;let r=f(e);h(r,t);let i=We(e,n);if(!S(i)){if(r.length>0)throw m(e,`its 200 application/json response is not a $ref to the state schema`);return}let a=O(i,n);r.forEach(e=>{e.state=a})},ne=({operation:e})=>{if(!n||!e.operationId?.endsWith(`.event.list_query`))return;let t=f(e);if(t.length===0)return;let r=We(e,n);if(S(r))return;let i=r?.items;if(!S(i))throw m(e,`its 200 application/json response is not an array of a $ref to the event stream schema`);let a=Zr(D(i,n),[`properties`,`body`,`items`,`anyOf`]);if(!Array.isArray(a))throw m(e,`the event stream schema ${i.$ref} has no properties.body.items.anyOf listing the domain events`);let o=a.map((t,r)=>{let a=Zr(t,[`properties`,`name`,`const`]),o=Zr(t,[`properties`,`body`]);if(typeof a!=`string`||!S(o))throw m(e,`domain event ${r} of ${i.$ref} needs a properties.name.const and a properties.body that is a $ref to the event schema`);let s=O(o,n);return p(s,`title`,t.title),{title:t.title??a,name:a,schema:s}});t.forEach(e=>{o.forEach(t=>{e.events.set(t.name,t)})})},g=({operation:e,path:t})=>{if(!n||!e.operationId?.endsWith(`.snapshot.count`))return;let r=f(e);if(r.length===0)return;h(r,t);let i=e.requestBody?S(e.requestBody)?pe(e.requestBody,n):e.requestBody:void 0;if(!i)throw m(e,`it has no request body`);let a=i[it],o;if(a!==void 0){if(!S(a))throw m(e,`${it} must be a schema reference`);o=a}else{let t=i.content?.[k]?.schema,r=(S(t)?D(t,n):void 0)?.properties?.field;if(!S(r))throw m(e,`its request body has no ${it}, and its condition schema has no field $ref to read the query fields from`);o=r}let s=O(o,n);r.forEach(e=>{e.fields=s})};for(let e of r)ee(e),te(e),ne(e),g(e);let _=new Map;for(let[e,t]of d){if(!t.state||!t.fields){if(s.has(e)){let n=[t.state?void 0:`${e}${nt}`,t.fields?void 0:`${e}${rt}`].filter(Boolean);i.push(`Skipping aggregate ${e}: the document has no ${n.join(` or `)} operation, so it generates neither command nor query clients for it.`)}continue}let n=t.aggregate.contextAlias,r=_.get(n);r||(r=new Set,_.set(n,r)),r.add({...t,resourceName:t.resourceName??t.aggregate.aggregateName})}return{contextAlias:Qe(t),contexts:_,aggregateTags:s,schemaDocOverrides:a,warnings:i}}function Zr(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}var Qr=Symbol(`project`),$r=Symbol(`signal`),ei=class{options;project;logger;signal;output;constructor(t){this.options=t,this.logger=t.logger??new l,this.signal=t[$r],this.project=t[Qr]??ti(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 from OpenAPI specification`),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},s=await Nr(n.configPath,e,a);i(s.warnings),t?.throwIfAborted(),e.debug(`Parsing OpenAPI specification`);let c=await Or(n.inputPath,a);t?.throwIfAborted(),e.debug(`OpenAPI specification parsed successfully`);let l=ce(c);if(l.length>0)throw new o(`specification`,`${n.inputPath} has ${l.length} $ref(s) that point at nothing: ${l.slice(0,10).map(({ref:e,location:t})=>`${e} (at ${t})`).join(`, `)}${l.length>10?`, …`:``}`);let u=Hr(c);e.debug(`Resolving bounded context aggregates`);let d=Xr(u);i(d.warnings),e.debug(`Resolved ${d.contexts.size} bounded context aggregates`);let f=Gr.open(this.project,n.outputDir,this.output);this.output=f,e.debug(`Analysing the document`);let p=qt(u,d,s.config);i(p.warnings),e.debug(`Writing generated modules`);let m=new Xt(e=>f.claim(e));sr(p.model,{modules:m,outputDir:n.outputDir,types:tr(u.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(lr(h,e=>f.claim(`index.ts`,e))),e.debug(`Optimizing source files`),xr(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:s.origin,warnings:r}}};function ti(t){try{return new e.Project({tsConfigFilePath:t,skipAddingFilesFromTsConfig:!0})}catch(e){throw new o(`configuration`,`Cannot read the TypeScript configuration ${t}: ${s(e)}`,{cause:e})}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return $r}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Sr}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return ei}});
|
|
23
|
+
//# sourceMappingURL=codeGenerator-BMyiC0tW.cjs.map
|