@ahoo-wang/fetcher-generator 3.3.0 → 3.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs +2 -2
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +1 -2
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +196 -200
- package/dist/index.js.map +1 -1
- package/dist/utils/sourceFiles.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/cli.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("commander"),a=require("./index.cjs");require("@ahoo-wang/fetcher");require("yaml");require("fs");
|
|
3
|
-
`,t),process.exit(1)}}const d="3.3.
|
|
2
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("commander"),a=require("./index.cjs");require("@ahoo-wang/fetcher");require("yaml");require("fs");class f{getTimestamp(){return new Date().toTimeString().slice(0,8)}info(e,...t){const o=this.getTimestamp();t.length>0?console.log(`[${o}] ℹ️ ${e}`,...t):console.log(`[${o}] ℹ️ ${e}`)}success(e,...t){const o=this.getTimestamp();t.length>0?console.log(`[${o}] ✅ ${e}`,...t):console.log(`[${o}] ✅ ${e}`)}error(e,...t){const o=this.getTimestamp();t.length>0?console.error(`[${o}] ❌ ${e}`,...t):console.error(`[${o}] ❌ ${e}`)}progress(e,t=0,...o){const i=this.getTimestamp(),r=" ".repeat(t);o.length>0?console.log(`[${i}] 🔄 ${r}${e}`,...o):console.log(`[${i}] 🔄 ${r}${e}`)}progressWithCount(e,t,o,i=0,...r){const s=this.getTimestamp(),p=" ".repeat(i),l=`[${e}/${t}]`;r.length>0?console.log(`[${s}] 🔄 ${p}${l} ${o}`,...r):console.log(`[${s}] 🔄 ${p}${l} ${o}`)}}function h(n){if(!n)return!1;try{const e=new URL(n);return e.protocol==="http:"||e.protocol==="https:"}catch{return n.length>0}}async function $(n){const e=new f;process.on("SIGINT",()=>{e.error("Generation interrupted by user"),process.exit(130)}),h(n.input)||(e.error("Invalid input: must be a valid file path or HTTP/HTTPS URL"),process.exit(2));try{e.info("Starting code generation...");const t={inputPath:n.input,outputDir:n.output,configPath:n.config,tsConfigFilePath:n.tsConfigFilePath,logger:e};await new a.CodeGenerator(t).generate(),e.success(`Code generation completed successfully! Files generated in: ${n.output}`)}catch(t){e.error(`Error during code generation:
|
|
3
|
+
`,t),process.exit(1)}}const d="3.3.1",m={version:d};function u(){return c.program.name("fetcher-generator").description("OpenAPI Specification TypeScript code generator for Wow").version(m.version,"-v, --version"),c.program.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",a.DEFAULT_CONFIG_PATH).option("-t, --ts-config-file-path <file>","TypeScript configuration file path").action($),c.program}function g(){u().parse()}g();exports.runCLI=g;exports.setupCLI=u;
|
|
4
4
|
//# sourceMappingURL=cli.cjs.map
|
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.cjs","sources":["../src/utils/logger.ts","../src/utils/clis.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\nimport { Logger } from '../types';\n\n/**\n * Default console-based logger implementation.\n * Provides friendly colored output for different log levels.\n */\nexport class ConsoleLogger implements Logger {\n private getTimestamp(): string {\n return new Date().toTimeString().slice(0, 8); // HH:MM:SS format\n }\n\n info(message: string, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n if (params.length > 0) {\n console.log(`[${timestamp}] ℹ️ ${message}`, ...params);\n } else {\n console.log(`[${timestamp}] ℹ️ ${message}`);\n }\n }\n\n success(message: string, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n if (params.length > 0) {\n console.log(`[${timestamp}] ✅ ${message}`, ...params);\n } else {\n console.log(`[${timestamp}] ✅ ${message}`);\n }\n }\n\n error(message: string, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n if (params.length > 0) {\n console.error(`[${timestamp}] ❌ ${message}`, ...params);\n } else {\n console.error(`[${timestamp}] ❌ ${message}`);\n }\n }\n\n progress(message: string, level = 0, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n const indent = ' '.repeat(level);\n if (params.length > 0) {\n console.log(`[${timestamp}] 🔄 ${indent}${message}`, ...params);\n } else {\n console.log(`[${timestamp}] 🔄 ${indent}${message}`);\n }\n }\n\n progressWithCount(\n current: number,\n total: number,\n message: string,\n level = 0,\n ...params: any[]\n ): void {\n const timestamp = this.getTimestamp();\n const indent = ' '.repeat(level);\n const countStr = `[${current}/${total}]`;\n if (params.length > 0) {\n console.log(\n `[${timestamp}] 🔄 ${indent}${countStr} ${message}`,\n ...params,\n );\n } else {\n console.log(`[${timestamp}] 🔄 ${indent}${countStr} ${message}`);\n }\n }\n}\n\n/**\n * Silent logger that suppresses all output.\n */\nexport class SilentLogger implements Logger {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n info(_message: string, ...params: any[]): void {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n success(_message: string, ...params: any[]): void {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n error(_message: string, ...params: any[]): void {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n progress(_message: string, ...params: any[]): void {}\n\n /* eslint-disable @typescript-eslint/no-unused-vars */\n progressWithCount(\n _current: number,\n _total: number,\n _message: string,\n _level = 0,\n ..._params: any[]\n ): void {}\n\n /* eslint-enable @typescript-eslint/no-unused-vars */\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 { CodeGenerator } from '../index';\nimport { GeneratorOptions } from '../types';\nimport { ConsoleLogger } from './logger';\n\n/**\n * Validates the input path or URL.\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\n // Check if it's a URL\n try {\n const url = new URL(input);\n return url.protocol === 'http:' || url.protocol === 'https:';\n } catch {\n // Not a URL, check if it's a file path\n // For file paths, we'll let parseOpenAPI handle it\n return input.length > 0;\n }\n}\n\n/**\n * Action handler for the generate command.\n * @param options - Command options\n */\nexport async function generateAction(options: {\n input: string;\n output: string;\n config?: string;\n tsConfigFilePath?: string;\n}) {\n const logger = new ConsoleLogger();\n\n // Handle signals\n process.on('SIGINT', () => {\n logger.error('Generation interrupted by user');\n process.exit(130);\n });\n\n // Validate input\n if (!validateInput(options.input)) {\n logger.error('Invalid input: must be a valid file path or HTTP/HTTPS URL');\n process.exit(2);\n }\n\n try {\n logger.info('Starting code generation...');\n const generatorOptions: GeneratorOptions = {\n inputPath: options.input,\n outputDir: options.output,\n configPath: options.config,\n tsConfigFilePath: options.tsConfigFilePath,\n logger,\n };\n const codeGenerator = new CodeGenerator(generatorOptions);\n await codeGenerator.generate();\n logger.success(\n `Code generation completed successfully! Files generated in: ${options.output}`,\n );\n } catch (error) {\n logger.error(`Error during code generation: \\n`, error);\n process.exit(1);\n }\n}\n","#!/usr/bin/env node\n\n/**\n * CLI entry point for the Fetcher OpenAPI code generator.\n * Sets up the commander program with generate command and handles execution.\n */\n\nimport { program } from 'commander';\nimport packageJson from '../package.json';\nimport { DEFAULT_CONFIG_PATH } from './index';\nimport { generateAction } from './utils';\n\n/**\n * Sets up the CLI program with all commands and options.\n * @returns The configured commander program instance\n */\nexport function setupCLI() {\n program\n .name('fetcher-generator')\n .description('OpenAPI Specification TypeScript code generator for Wow')\n .version(packageJson.version, '-v, --version');\n\n program\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 .option(\n '-c, --config <file>',\n 'Configuration file path',\n DEFAULT_CONFIG_PATH,\n )\n .option(\n '-t, --ts-config-file-path <file>',\n 'TypeScript configuration file path',\n )\n .action(generateAction);\n\n return program;\n}\n\n/**\n * Runs the CLI program by parsing command line arguments.\n * Only executes when this file is run directly (not imported).\n */\nexport function runCLI() {\n setupCLI().parse();\n}\n\nrunCLI();\n"],"names":["ConsoleLogger","message","params","timestamp","level","indent","current","total","countStr","validateInput","input","url","generateAction","options","logger","generatorOptions","CodeGenerator","error","setupCLI","program","packageJson","DEFAULT_CONFIG_PATH","runCLI"],"mappings":";kNAmBO,MAAMA,CAAgC,CACnC,cAAuB,CAC7B,WAAW,OAAO,eAAe,MAAM,EAAG,CAAC,CAC7C,CAEA,KAAKC,KAAoBC,EAAqB,CAC5C,MAAMC,EAAY,KAAK,aAAA,EACnBD,EAAO,OAAS,EAClB,QAAQ,IAAI,IAAIC,CAAS,SAASF,CAAO,GAAI,GAAGC,CAAM,EAEtD,QAAQ,IAAI,IAAIC,CAAS,SAASF,CAAO,EAAE,CAE/C,CAEA,QAAQA,KAAoBC,EAAqB,CAC/C,MAAMC,EAAY,KAAK,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MC,EAAS,IAAId,EAGnB,QAAQ,GAAG,SAAU,IAAM,CACzBc,EAAO,MAAM,gCAAgC,EAC7C,QAAQ,KAAK,GAAG,CAClB,CAAC,EAGIL,EAAcI,EAAQ,KAAK,IAC9BC,EAAO,MAAM,4DAA4D,EACzE,QAAQ,KAAK,CAAC,GAGhB,GAAI,CACFA,EAAO,KAAK,6BAA6B,EACzC,MAAMC,EAAqC,CACzC,UAAWF,EAAQ,MACnB,UAAWA,EAAQ,OACnB,WAAYA,EAAQ,OACpB,iBAAkBA,EAAQ,iBAC1B,OAAAC,CAAA,EAGF,MADsB,IAAIE,EAAAA,cAAcD,CAAgB,EACpC,SAAA,EACpBD,EAAO,QACL,+DAA+DD,EAAQ,MAAM,EAAA,CAEjF,OAASI,EAAO,CACdH,EAAO,MAAM;AAAA,EAAoCG,CAAK,EACtD,QAAQ,KAAK,CAAC,CAChB,CACF,+BC9DO,SAASC,GAAW,CACzBC,OAAAA,UACG,KAAK,mBAAmB,EACxB,YAAY,yDAAyD,EACrE,QAAQC,EAAY,QAAS,eAAe,EAE/CD,EAAAA,QACG,QAAQ,UAAU,EAClB,YAAY,qDAAqD,EACjE,eACC,qBACA,2DAAA,EAED,OAAO,sBAAuB,wBAAyB,eAAe,EACtE,OACC,sBACA,0BACAE,EAAAA,mBAAA,EAED,OACC,mCACA,oCAAA,EAED,OAAOT,CAAc,EAEjBO,EAAAA,OACT,CAMO,SAASG,GAAS,CACvBJ,EAAA,EAAW,MAAA,CACb,CAEAI,EAAA"}
|
|
1
|
+
{"version":3,"file":"cli.cjs","sources":["../src/utils/logger.ts","../src/utils/clis.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\nimport { Logger } from '../types';\n\n/**\n * Default console-based logger implementation.\n * Provides friendly colored output for different log levels.\n */\nexport class ConsoleLogger implements Logger {\n private getTimestamp(): string {\n return new Date().toTimeString().slice(0, 8); // HH:MM:SS format\n }\n\n info(message: string, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n if (params.length > 0) {\n console.log(`[${timestamp}] ℹ️ ${message}`, ...params);\n } else {\n console.log(`[${timestamp}] ℹ️ ${message}`);\n }\n }\n\n success(message: string, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n if (params.length > 0) {\n console.log(`[${timestamp}] ✅ ${message}`, ...params);\n } else {\n console.log(`[${timestamp}] ✅ ${message}`);\n }\n }\n\n error(message: string, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n if (params.length > 0) {\n console.error(`[${timestamp}] ❌ ${message}`, ...params);\n } else {\n console.error(`[${timestamp}] ❌ ${message}`);\n }\n }\n\n progress(message: string, level = 0, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n const indent = ' '.repeat(level);\n if (params.length > 0) {\n console.log(`[${timestamp}] 🔄 ${indent}${message}`, ...params);\n } else {\n console.log(`[${timestamp}] 🔄 ${indent}${message}`);\n }\n }\n\n progressWithCount(\n current: number,\n total: number,\n message: string,\n level = 0,\n ...params: any[]\n ): void {\n const timestamp = this.getTimestamp();\n const indent = ' '.repeat(level);\n const countStr = `[${current}/${total}]`;\n if (params.length > 0) {\n console.log(\n `[${timestamp}] 🔄 ${indent}${countStr} ${message}`,\n ...params,\n );\n } else {\n console.log(`[${timestamp}] 🔄 ${indent}${countStr} ${message}`);\n }\n }\n}\n\n/**\n * Silent logger that suppresses all output.\n */\nexport class SilentLogger implements Logger {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n info(_message: string, ...params: any[]): void {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n success(_message: string, ...params: any[]): void {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n error(_message: string, ...params: any[]): void {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n progress(_message: string, ...params: any[]): void {}\n\n /* eslint-disable @typescript-eslint/no-unused-vars */\n progressWithCount(\n _current: number,\n _total: number,\n _message: string,\n _level = 0,\n ..._params: any[]\n ): void {}\n\n /* eslint-enable @typescript-eslint/no-unused-vars */\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 { CodeGenerator } from '../index';\nimport { GeneratorOptions } from '../types';\nimport { ConsoleLogger } from './logger';\n\n/**\n * Validates the input path or URL.\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\n // Check if it's a URL\n try {\n const url = new URL(input);\n return url.protocol === 'http:' || url.protocol === 'https:';\n } catch {\n // Not a URL, check if it's a file path\n // For file paths, we'll let parseOpenAPI handle it\n return input.length > 0;\n }\n}\n\n/**\n * Action handler for the generate command.\n * @param options - Command options\n */\nexport async function generateAction(options: {\n input: string;\n output: string;\n config?: string;\n tsConfigFilePath?: string;\n}) {\n const logger = new ConsoleLogger();\n\n // Handle signals\n process.on('SIGINT', () => {\n logger.error('Generation interrupted by user');\n process.exit(130);\n });\n\n // Validate input\n if (!validateInput(options.input)) {\n logger.error('Invalid input: must be a valid file path or HTTP/HTTPS URL');\n process.exit(2);\n }\n\n try {\n logger.info('Starting code generation...');\n const generatorOptions: GeneratorOptions = {\n inputPath: options.input,\n outputDir: options.output,\n configPath: options.config,\n tsConfigFilePath: options.tsConfigFilePath,\n logger,\n };\n const codeGenerator = new CodeGenerator(generatorOptions);\n await codeGenerator.generate();\n logger.success(\n `Code generation completed successfully! Files generated in: ${options.output}`,\n );\n } catch (error) {\n logger.error(`Error during code generation: \\n`, error);\n process.exit(1);\n }\n}\n","#!/usr/bin/env node\n\n/**\n * CLI entry point for the Fetcher OpenAPI code generator.\n * Sets up the commander program with generate command and handles execution.\n */\n\nimport { program } from 'commander';\nimport packageJson from '../package.json';\nimport { DEFAULT_CONFIG_PATH } from './index';\nimport { generateAction } from './utils';\n\n/**\n * Sets up the CLI program with all commands and options.\n * @returns The configured commander program instance\n */\nexport function setupCLI() {\n program\n .name('fetcher-generator')\n .description('OpenAPI Specification TypeScript code generator for Wow')\n .version(packageJson.version, '-v, --version');\n\n program\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 .option(\n '-c, --config <file>',\n 'Configuration file path',\n DEFAULT_CONFIG_PATH,\n )\n .option(\n '-t, --ts-config-file-path <file>',\n 'TypeScript configuration file path',\n )\n .action(generateAction);\n\n return program;\n}\n\n/**\n * Runs the CLI program by parsing command line arguments.\n * Only executes when this file is run directly (not imported).\n */\nexport function runCLI() {\n setupCLI().parse();\n}\n\nrunCLI();\n"],"names":["ConsoleLogger","message","params","timestamp","level","indent","current","total","countStr","validateInput","input","url","generateAction","options","logger","generatorOptions","CodeGenerator","error","setupCLI","program","packageJson","DEFAULT_CONFIG_PATH","runCLI"],"mappings":";kMAmBO,MAAMA,CAAgC,CACnC,cAAuB,CAC7B,WAAW,OAAO,eAAe,MAAM,EAAG,CAAC,CAC7C,CAEA,KAAKC,KAAoBC,EAAqB,CAC5C,MAAMC,EAAY,KAAK,aAAA,EACnBD,EAAO,OAAS,EAClB,QAAQ,I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5
5
|
import "yaml";
|
|
6
6
|
import "fs";
|
|
7
|
-
import "path";
|
|
8
7
|
class u {
|
|
9
8
|
getTimestamp() {
|
|
10
9
|
return (/* @__PURE__ */ new Date()).toTimeString().slice(0, 8);
|
|
@@ -64,7 +63,7 @@ async function h(n) {
|
|
|
64
63
|
`, t), process.exit(1);
|
|
65
64
|
}
|
|
66
65
|
}
|
|
67
|
-
const $ = "3.3.
|
|
66
|
+
const $ = "3.3.1", m = {
|
|
68
67
|
version: $
|
|
69
68
|
};
|
|
70
69
|
function d() {
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sources":["../src/utils/logger.ts","../src/utils/clis.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\nimport { Logger } from '../types';\n\n/**\n * Default console-based logger implementation.\n * Provides friendly colored output for different log levels.\n */\nexport class ConsoleLogger implements Logger {\n private getTimestamp(): string {\n return new Date().toTimeString().slice(0, 8); // HH:MM:SS format\n }\n\n info(message: string, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n if (params.length > 0) {\n console.log(`[${timestamp}] ℹ️ ${message}`, ...params);\n } else {\n console.log(`[${timestamp}] ℹ️ ${message}`);\n }\n }\n\n success(message: string, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n if (params.length > 0) {\n console.log(`[${timestamp}] ✅ ${message}`, ...params);\n } else {\n console.log(`[${timestamp}] ✅ ${message}`);\n }\n }\n\n error(message: string, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n if (params.length > 0) {\n console.error(`[${timestamp}] ❌ ${message}`, ...params);\n } else {\n console.error(`[${timestamp}] ❌ ${message}`);\n }\n }\n\n progress(message: string, level = 0, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n const indent = ' '.repeat(level);\n if (params.length > 0) {\n console.log(`[${timestamp}] 🔄 ${indent}${message}`, ...params);\n } else {\n console.log(`[${timestamp}] 🔄 ${indent}${message}`);\n }\n }\n\n progressWithCount(\n current: number,\n total: number,\n message: string,\n level = 0,\n ...params: any[]\n ): void {\n const timestamp = this.getTimestamp();\n const indent = ' '.repeat(level);\n const countStr = `[${current}/${total}]`;\n if (params.length > 0) {\n console.log(\n `[${timestamp}] 🔄 ${indent}${countStr} ${message}`,\n ...params,\n );\n } else {\n console.log(`[${timestamp}] 🔄 ${indent}${countStr} ${message}`);\n }\n }\n}\n\n/**\n * Silent logger that suppresses all output.\n */\nexport class SilentLogger implements Logger {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n info(_message: string, ...params: any[]): void {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n success(_message: string, ...params: any[]): void {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n error(_message: string, ...params: any[]): void {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n progress(_message: string, ...params: any[]): void {}\n\n /* eslint-disable @typescript-eslint/no-unused-vars */\n progressWithCount(\n _current: number,\n _total: number,\n _message: string,\n _level = 0,\n ..._params: any[]\n ): void {}\n\n /* eslint-enable @typescript-eslint/no-unused-vars */\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 { CodeGenerator } from '../index';\nimport { GeneratorOptions } from '../types';\nimport { ConsoleLogger } from './logger';\n\n/**\n * Validates the input path or URL.\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\n // Check if it's a URL\n try {\n const url = new URL(input);\n return url.protocol === 'http:' || url.protocol === 'https:';\n } catch {\n // Not a URL, check if it's a file path\n // For file paths, we'll let parseOpenAPI handle it\n return input.length > 0;\n }\n}\n\n/**\n * Action handler for the generate command.\n * @param options - Command options\n */\nexport async function generateAction(options: {\n input: string;\n output: string;\n config?: string;\n tsConfigFilePath?: string;\n}) {\n const logger = new ConsoleLogger();\n\n // Handle signals\n process.on('SIGINT', () => {\n logger.error('Generation interrupted by user');\n process.exit(130);\n });\n\n // Validate input\n if (!validateInput(options.input)) {\n logger.error('Invalid input: must be a valid file path or HTTP/HTTPS URL');\n process.exit(2);\n }\n\n try {\n logger.info('Starting code generation...');\n const generatorOptions: GeneratorOptions = {\n inputPath: options.input,\n outputDir: options.output,\n configPath: options.config,\n tsConfigFilePath: options.tsConfigFilePath,\n logger,\n };\n const codeGenerator = new CodeGenerator(generatorOptions);\n await codeGenerator.generate();\n logger.success(\n `Code generation completed successfully! Files generated in: ${options.output}`,\n );\n } catch (error) {\n logger.error(`Error during code generation: \\n`, error);\n process.exit(1);\n }\n}\n","#!/usr/bin/env node\n\n/**\n * CLI entry point for the Fetcher OpenAPI code generator.\n * Sets up the commander program with generate command and handles execution.\n */\n\nimport { program } from 'commander';\nimport packageJson from '../package.json';\nimport { DEFAULT_CONFIG_PATH } from './index';\nimport { generateAction } from './utils';\n\n/**\n * Sets up the CLI program with all commands and options.\n * @returns The configured commander program instance\n */\nexport function setupCLI() {\n program\n .name('fetcher-generator')\n .description('OpenAPI Specification TypeScript code generator for Wow')\n .version(packageJson.version, '-v, --version');\n\n program\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 .option(\n '-c, --config <file>',\n 'Configuration file path',\n DEFAULT_CONFIG_PATH,\n )\n .option(\n '-t, --ts-config-file-path <file>',\n 'TypeScript configuration file path',\n )\n .action(generateAction);\n\n return program;\n}\n\n/**\n * Runs the CLI program by parsing command line arguments.\n * Only executes when this file is run directly (not imported).\n */\nexport function runCLI() {\n setupCLI().parse();\n}\n\nrunCLI();\n"],"names":["ConsoleLogger","message","params","timestamp","level","indent","current","total","countStr","validateInput","input","url","generateAction","options","logger","generatorOptions","CodeGenerator","error","setupCLI","program","packageJson","DEFAULT_CONFIG_PATH","runCLI"],"mappings":";;;;;;;AAmBO,MAAMA,EAAgC;AAAA,EACnC,eAAuB;AAC7B,gCAAW,QAAO,eAAe,MAAM,GAAG,CAAC;AAAA,EAC7C;AAAA,EAEA,KAAKC,MAAoBC,GAAqB;AAC5C,UAAMC,IAAY,KAAK,aAAA;AACvB,IAAID,EAAO,SAAS,IAClB,QAAQ,IAAI,IAAIC,CAAS,SAASF,CAAO,IAAI,GAAGC,CAAM,IAEtD,QAAQ,IAAI,IAAIC,CAAS,SAASF,CAAO,EAAE;AAAA,EAE/C;AAAA,EAEA,QAAQA,MAAoBC,GAAqB;AAC/C,UAAMC,IAAY,KAAK,aAAA;AACvB,IAAID,EAAO,SAAS,IAClB,QAAQ,IAAI,IAAIC,CAAS,OAAOF,CAAO,IAAI,GAAGC,CAAM,IAEpD,QAAQ,IAAI,IAAIC,CAAS,OAAOF,CAAO,EAAE;AAAA,EAE7C;AAAA,EAEA,MAAMA,MAAoBC,GAAqB;AAC7C,UAAMC,IAAY,KAAK,aAAA;AACvB,IAAID,EAAO,SAAS,IAClB,QAAQ,MAAM,IAAIC,CAAS,OAAOF,CAAO,IAAI,GAAGC,CAAM,IAEtD,QAAQ,MAAM,IAAIC,CAAS,O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AACzC,UAAMC,IAAqC;AAAA,MACzC,WAAWF,EAAQ;AAAA,MACnB,WAAWA,EAAQ;AAAA,MACnB,YAAYA,EAAQ;AAAA,MACpB,kBAAkBA,EAAQ;AAAA,MAC1B,QAAAC;AAAA,IAAA;AAGF,UADsB,IAAIE,EAAcD,CAAgB,EACpC,SAAA,GACpBD,EAAO;AAAA,MACL,+DAA+DD,EAAQ,MAAM;AAAA,IAAA;AAAA,EAEjF,SAASI,GAAO;AACd,IAAAH,EAAO,MAAM;AAAA,GAAoCG,CAAK,GACtD,QAAQ,KAAK,CAAC;AAAA,EAChB;AACF;;;;AC9DO,SAASC,IAAW;AACzB,SAAAC,EACG,KAAK,mBAAmB,EACxB,YAAY,yDAAyD,EACrE,QAAQC,EAAY,SAAS,eAAe,GAE/CD,EACG,QAAQ,UAAU,EAClB,YAAY,qDAAqD,EACjE;AAAA,IACC;AAAA,IACA;AAAA,EAAA,EAED,OAAO,uBAAuB,yBAAyB,eAAe,EACtE;AAAA,IACC;AAAA,IACA;AAAA,IACAE;AAAA,EAAA,EAED;AAAA,IACC;AAAA,IACA;AAAA,EAAA,EAED,OAAOT,CAAc,GAEjBO;AACT;AAMO,SAASG,IAAS;AACvB,EAAAJ,EAAA,EAAW,MAAA;AACb;AAEAI,EAAA;"}
|
|
1
|
+
{"version":3,"file":"cli.js","sources":["../src/utils/logger.ts","../src/utils/clis.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\nimport { Logger } from '../types';\n\n/**\n * Default console-based logger implementation.\n * Provides friendly colored output for different log levels.\n */\nexport class ConsoleLogger implements Logger {\n private getTimestamp(): string {\n return new Date().toTimeString().slice(0, 8); // HH:MM:SS format\n }\n\n info(message: string, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n if (params.length > 0) {\n console.log(`[${timestamp}] ℹ️ ${message}`, ...params);\n } else {\n console.log(`[${timestamp}] ℹ️ ${message}`);\n }\n }\n\n success(message: string, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n if (params.length > 0) {\n console.log(`[${timestamp}] ✅ ${message}`, ...params);\n } else {\n console.log(`[${timestamp}] ✅ ${message}`);\n }\n }\n\n error(message: string, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n if (params.length > 0) {\n console.error(`[${timestamp}] ❌ ${message}`, ...params);\n } else {\n console.error(`[${timestamp}] ❌ ${message}`);\n }\n }\n\n progress(message: string, level = 0, ...params: any[]): void {\n const timestamp = this.getTimestamp();\n const indent = ' '.repeat(level);\n if (params.length > 0) {\n console.log(`[${timestamp}] 🔄 ${indent}${message}`, ...params);\n } else {\n console.log(`[${timestamp}] 🔄 ${indent}${message}`);\n }\n }\n\n progressWithCount(\n current: number,\n total: number,\n message: string,\n level = 0,\n ...params: any[]\n ): void {\n const timestamp = this.getTimestamp();\n const indent = ' '.repeat(level);\n const countStr = `[${current}/${total}]`;\n if (params.length > 0) {\n console.log(\n `[${timestamp}] 🔄 ${indent}${countStr} ${message}`,\n ...params,\n );\n } else {\n console.log(`[${timestamp}] 🔄 ${indent}${countStr} ${message}`);\n }\n }\n}\n\n/**\n * Silent logger that suppresses all output.\n */\nexport class SilentLogger implements Logger {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n info(_message: string, ...params: any[]): void {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n success(_message: string, ...params: any[]): void {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n error(_message: string, ...params: any[]): void {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n progress(_message: string, ...params: any[]): void {}\n\n /* eslint-disable @typescript-eslint/no-unused-vars */\n progressWithCount(\n _current: number,\n _total: number,\n _message: string,\n _level = 0,\n ..._params: any[]\n ): void {}\n\n /* eslint-enable @typescript-eslint/no-unused-vars */\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 { CodeGenerator } from '../index';\nimport { GeneratorOptions } from '../types';\nimport { ConsoleLogger } from './logger';\n\n/**\n * Validates the input path or URL.\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\n // Check if it's a URL\n try {\n const url = new URL(input);\n return url.protocol === 'http:' || url.protocol === 'https:';\n } catch {\n // Not a URL, check if it's a file path\n // For file paths, we'll let parseOpenAPI handle it\n return input.length > 0;\n }\n}\n\n/**\n * Action handler for the generate command.\n * @param options - Command options\n */\nexport async function generateAction(options: {\n input: string;\n output: string;\n config?: string;\n tsConfigFilePath?: string;\n}) {\n const logger = new ConsoleLogger();\n\n // Handle signals\n process.on('SIGINT', () => {\n logger.error('Generation interrupted by user');\n process.exit(130);\n });\n\n // Validate input\n if (!validateInput(options.input)) {\n logger.error('Invalid input: must be a valid file path or HTTP/HTTPS URL');\n process.exit(2);\n }\n\n try {\n logger.info('Starting code generation...');\n const generatorOptions: GeneratorOptions = {\n inputPath: options.input,\n outputDir: options.output,\n configPath: options.config,\n tsConfigFilePath: options.tsConfigFilePath,\n logger,\n };\n const codeGenerator = new CodeGenerator(generatorOptions);\n await codeGenerator.generate();\n logger.success(\n `Code generation completed successfully! Files generated in: ${options.output}`,\n );\n } catch (error) {\n logger.error(`Error during code generation: \\n`, error);\n process.exit(1);\n }\n}\n","#!/usr/bin/env node\n\n/**\n * CLI entry point for the Fetcher OpenAPI code generator.\n * Sets up the commander program with generate command and handles execution.\n */\n\nimport { program } from 'commander';\nimport packageJson from '../package.json';\nimport { DEFAULT_CONFIG_PATH } from './index';\nimport { generateAction } from './utils';\n\n/**\n * Sets up the CLI program with all commands and options.\n * @returns The configured commander program instance\n */\nexport function setupCLI() {\n program\n .name('fetcher-generator')\n .description('OpenAPI Specification TypeScript code generator for Wow')\n .version(packageJson.version, '-v, --version');\n\n program\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 .option(\n '-c, --config <file>',\n 'Configuration file path',\n DEFAULT_CONFIG_PATH,\n )\n .option(\n '-t, --ts-config-file-path <file>',\n 'TypeScript configuration file path',\n )\n .action(generateAction);\n\n return program;\n}\n\n/**\n * Runs the CLI program by parsing command line arguments.\n * Only executes when this file is run directly (not imported).\n */\nexport function runCLI() {\n setupCLI().parse();\n}\n\nrunCLI();\n"],"names":["ConsoleLogger","message","params","timestamp","level","indent","current","total","countStr","validateInput","input","url","generateAction","options","logger","generatorOptions","CodeGenerator","error","setupCLI","program","packageJson","DEFAULT_CONFIG_PATH","runCLI"],"mappings":";;;;;;AAmBO,MAAMA,EAAgC;AAAA,EACnC,eAAuB;AAC7B,gCAAW,QAAO,eAAe,MAAM,GAAG,CAAC;AAAA,EAC7C;AAAA,EAEA,KAAKC,MAAoBC,GAAqB;AAC5C,UAAMC,IAAY,KAAK,aAAA;AACvB,IAAID,EAAO,SAAS,IAClB,QAAQ,IAAI,IAAIC,CAAS,SAASF,CAAO,IAAI,GAAGC,CAAM,IAEtD,QAAQ,IAAI,IAAIC,CAAS,SAASF,CAAO,EAAE;AAAA,EAE/C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ANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("ts-morph"),f=require("@ahoo-wang/fetcher"),z=require("@ahoo-wang/fetcher-wow"),
|
|
2
|
-
`){if(!Array.isArray(n))return;const t=n.filter(o=>typeof o=="string"&&o.length>0);return t.length>0?t.join(e):void 0}function $(n,e){const t=
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("ts-morph"),f=require("@ahoo-wang/fetcher"),z=require("@ahoo-wang/fetcher-wow"),K=require("yaml"),ye=require("fs");function T(n){return n.$ref.split("/").pop()}function S(n,e){const t=T(n);return e.schemas?.[t]}function H(n,e){const t=T(n);return e.requestBodies?.[t]}function Y(n,e){const t=T(n);return e.parameters?.[t]}function v(n,e){return{key:T(n),schema:S(n,e)}}const xe=/[-_'\s.]+/;function N(n){return n.split(xe)}function Z(n){return Array.isArray(n)?n.flatMap(e=>L(N(e))):L(N(n))}function L(n){return n.flatMap(e=>{if(e.length===0)return[];const t=[];let o="";for(let r=0;r<e.length;r++){const i=e[r],s=/[A-Z]/.test(i),a=r>0&&/[a-z]/.test(e[r-1]);s&&a&&o?(t.push(o),o=i):o+=i}return o&&t.push(o),t})}function R(n){return n===""||n.length===0?"":Z(n).filter(t=>t.length>0).map(t=>{const o=t.charAt(0),r=t.slice(1);return(/[a-zA-Z]/.test(o)?o.toUpperCase():o)+r.toLowerCase()}).join("")}function h(n){const e=R(n);return e.charAt(0).toLowerCase()+e.slice(1)}function X(n){return n===""||Array.isArray(n)&&n.length===0?"":Z(n).filter(t=>t.length>0).map(t=>t.toUpperCase()).join("_")}function O(n){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n)?n:`'${n}'`}function Ae(n){return/^\d+$/.test(n)?`NUM_${n}`:O(X(n))}function g(n){return!!(n&&typeof n=="object"&&"$ref"in n)}function _(n,e){if(e&&!g(e)&&e.content)return e.content[n]?.schema}function ee(n){return _(f.ContentTypeValues.APPLICATION_JSON,n)}function Ce(n){return _(f.ContentTypeValues.TEXT_EVENT_STREAM,n)}function Pe(n){return _("*/*",n)}const $e=["string","number","integer","boolean","null"];function te(n){return Array.isArray(n)?!0:$e.includes(n)}function B(n){return Array.isArray(n.enum)&&n.enum.length>0}function I(n){return n.type==="object"&&!!n.properties}function b(n){return n.type==="array"&&!!n.items}function Te(n){return Array.isArray(n.anyOf)&&n.anyOf.length>0}function ve(n){return Array.isArray(n.oneOf)&&n.oneOf.length>0}function M(n){return Array.isArray(n.allOf)&&n.allOf.length>0}function U(n){return Te(n)||ve(n)||M(n)}function Ie(n){return n.includes("|")||n.includes("&")?`(${n})[]`:`${n}[]`}function Ee(n){return n.type==="object"&&!n.properties&&n.additionalProperties!==void 0}function Se(n){return n.type!=="object"?!1:n.properties?Object.keys(n.properties).length===0:!0}function Re(n){return n.readOnly===!0}function w(n){if(Array.isArray(n))return n.map(e=>w(e)).join(" | ");switch(n){case"string":return"string";case"number":case"integer":return"number";case"boolean":return"boolean";case"null":return"null";default:return"any"}}function we(n){if(!I(n))return[];const e=n.required||[];return Object.keys(n.properties).filter(t=>!e.includes(t))}function De(n,e){return n.operation.operationId&&e.operation.operationId?n.operation.operationId.localeCompare(e.operation.operationId):n.path&&e.path?n.path.localeCompare(e.path):n.method&&e.method?n.method.localeCompare(e.method):0}function ne(n){const e=[];for(const[t,o]of Object.entries(n))oe(o).forEach(r=>{e.push({method:r.method,operation:r.operation,path:t})});return e.sort(De)}function oe(n){return[{method:"get",operation:n.get},{method:"put",operation:n.put},{method:"post",operation:n.post},{method:"delete",operation:n.delete},{method:"options",operation:n.options},{method:"head",operation:n.head},{method:"patch",operation:n.patch},{method:"trace",operation:n.trace}].filter(({operation:e})=>e!==void 0)}function G(n){return n.responses[200]}function J(n){const e=G(n);return ee(e)}function Ne(n,e){return n.parameters?n.parameters.map(t=>g(t)?Y(t,e):t).filter(t=>t.in==="path"):[]}const Oe="string";function re(n){return!n.schema||g(n.schema)||!n.schema.type||!te(n.schema.type)?Oe:w(n.schema.type)}function ie(n){return n.startsWith("http://")||n.startsWith("https://")?be(n):Me(n)}async function be(n){return await(await fetch(n)).text()}function Me(n){return new Promise((e,t)=>{ye.readFile(n,"utf-8",(o,r)=>{o?t(o):e(r)})})}async function qe(n){const e=await ie(n);switch(se(e)){case"json":return JSON.parse(e);case"yaml":return K.parse(e);default:throw new Error(`Unsupported file format: ${n}`)}}async function Fe(n){const e=await ie(n);switch(se(e)){case"json":return JSON.parse(e);case"yaml":return K.parse(e);default:throw new Error(`Unsupported file format: ${n}`)}}function se(n){const e=n.trimStart();if(e.startsWith("{")||e.startsWith("["))return"json";if(e.startsWith("-")||e.startsWith("%YAML"))return"yaml";try{return JSON.parse(e),"json"}catch{if(e.length>0)return"yaml"}throw new Error("Unable to infer file format")}const ae="types.ts",je="@";function _e(n){return f.combineURLs(n.path,ae)}function ce(n,e,t){const o=f.combineURLs(e,t),r=n.getSourceFile(o);return r||n.createSourceFile(o,"",{overwrite:!0})}function P(n,e,t){let o=n.getImportDeclaration(r=>r.getModuleSpecifierValue()===e);o||(o=n.addImportDeclaration({moduleSpecifier:e})),t.forEach(r=>{o.getNamedImports().some(s=>s.getName()===r)||o.addNamedImport(r)})}function m(n,e,t){if(t.path.startsWith(je)){P(n,t.path,[t.name]);return}const o=n.getDirectoryPath(),r=(void 0)(e,t.path,ae);let i=(void 0)(o,r);i=i.replace(/\.ts$/,""),i=i.split(void 0).join("/"),i.startsWith(".")||(i="./"+i),P(n,i,[t.name])}function Ge(n,e,t,o){n.path!==o.path&&m(e,t,o)}function ge(n,e=`
|
|
2
|
+
`){if(!Array.isArray(n))return;const t=n.filter(o=>typeof o=="string"&&o.length>0);return t.length>0?t.join(e):void 0}function $(n,e){const t=ge(e);t&&n.addJsDoc(t)}function W(n,e){const t=[n.title,n.description];return e&&t.push(`- key: ${e}`),n.format&&t.push(`- format: ${n.format}`),Q(t,n,"default"),Q(t,n,"example"),ze(t,n),Le(t,n),Be(t,n),t}function We(n,e,t){const o=W(e,t);$(n,o)}function ke(n,e,t){const o=W(e,t);pe(o,"schema",e),$(n,o)}function Q(n,e,t){const o=e[t];if(o){if(typeof o!="object"){n.push(`- ${t}: \`${o}\``);return}pe(n,t,o)}}function pe(n,e,t){n.push(`- ${e}: `),n.push("```json"),n.push(JSON.stringify(t,null,2)),n.push("```")}function ze(n,e){const t=["- Numeric Constraints"];e.minimum!==void 0&&t.push(` - minimum: ${e.minimum}`),e.maximum!==void 0&&t.push(` - maximum: ${e.maximum}`),e.exclusiveMinimum!==void 0&&t.push(` - exclusiveMinimum: ${e.exclusiveMinimum}`),e.exclusiveMaximum!==void 0&&t.push(` - exclusiveMaximum: ${e.exclusiveMaximum}`),e.multipleOf!==void 0&&t.push(` - multipleOf: ${e.multipleOf}`),t.length!==1&&n.push(...t)}function Le(n,e){const t=["- String Constraints"];e.minLength!==void 0&&t.push(` - minLength: ${e.minLength}`),e.maxLength!==void 0&&t.push(` - maxLength: ${e.maxLength}`),e.pattern!==void 0&&t.push(` - pattern: ${e.pattern}`),t.length!==1&&n.push(...t)}function Be(n,e){const t=["- Array Constraints"];e.minItems!==void 0&&t.push(` - minItems: ${e.minItems}`),e.maxItems!==void 0&&t.push(` - maxItems: ${e.maxItems}`),e.uniqueItems!==void 0&&t.push(` - uniqueItems: ${e.uniqueItems}`),t.length!==1&&n.push(...t)}function Ue(n){const e=n.split(".");return e.length!=2||e[0].length===0||e[1].length===0?null:e}function Je(n){const e=Ue(n.name);return e?{tag:n,contextAlias:e[0],aggregateName:e[1]}:null}function Qe(n){const e=n?.map(o=>Je(o)).filter(o=>o!==null);if(!e)return new Map;const t=new Map;return e.forEach(o=>{t.set(o.tag.name,{aggregate:o,commands:new Map,events:new Map})}),t}function Ve(n){if(!n)return null;const e=n.split(".");return e.length!=3?null:e[2]}const Ke="#/components/responses/wow.CommandOk",He="#/components/parameters/wow.id";class Ye{constructor(e){this.openAPI=e,this.aggregates=Qe(e.tags),this.build()}aggregates;build(){const e=ne(this.openAPI.paths);for(const t of e)this.commands(t.path,t),this.state(t.operation),this.events(t.operation),this.fields(t.operation)}resolve(){const e=new Map;for(const t of this.aggregates.values()){if(!t.state||!t.fields)continue;const o=t.aggregate.contextAlias;let r=e.get(o);r||(r=new Set,e.set(o,r)),r.add(t)}return e}commands(e,t){const o=t.operation;if(o.operationId==="wow.command.send")return;const r=Ve(o.operationId);if(!r)return;const i=G(o);if(!i||!g(i)||i.$ref!==Ke||!o.requestBody)return;const s=o.parameters??[],a=s.filter(l=>g(l)&&l.$ref===He).at(0),c=s.filter(l=>!g(l)&&l.in==="path");if(a){const l=Y(a,this.openAPI.components);c.push(l)}const p=o.requestBody.content[f.ContentTypeValues.APPLICATION_JSON].schema,A=v(p,this.openAPI.components);A.schema.title=A.schema.title||o.summary,A.schema.description=A.schema.description||o.description;const he={name:r,method:t.method,path:e,pathParameters:c,summary:o.summary,description:o.description,schema:A,operation:o};o.tags?.forEach(l=>{const k=this.aggregates.get(l);k&&k.commands.set(r,he)})}state(e){if(!e.operationId?.endsWith(".snapshot_state.single"))return;const t=J(e);if(!g(t))return;const o=v(t,this.openAPI.components);e.tags?.forEach(r=>{const i=this.aggregates.get(r);i&&(i.state=o)})}events(e){if(!this.openAPI.components||!e.operationId?.endsWith(".event.list_query"))return;const t=J(e);if(g(t))return;const o=t?.items;if(!g(o))return;const i=S(o,this.openAPI.components).properties.body.items.anyOf.map(s=>{const a=s.title,c=s.properties.name.const,u=s.properties.body,p=v(u,this.openAPI.components);return p.schema.title=p.schema.title||s.title,{title:a,name:c,schema:p}});e.tags?.forEach(s=>{const a=this.aggregates.get(s);a&&i.forEach(c=>{a.events.set(c.name,c)})})}fields(e){if(!this.openAPI.components||!e.operationId?.endsWith(".snapshot.count"))return;const o=H(e.requestBody,this.openAPI.components).content[f.ContentTypeValues.APPLICATION_JSON].schema,i=S(o,this.openAPI.components).properties?.field,s=v(i,this.openAPI.components);e.tags?.forEach(a=>{const c=this.aggregates.get(a);c&&(c.fields=s)})}}const x="@ahoo-wang/fetcher-wow",Ze={"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.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 d(n){if(!n)return{name:"",path:"/"};const e=Ze[n];if(e)return{name:e,path:x};const t=n.split(".");let o=-1;for(let c=0;c<t.length;c++)if(t[c]&&/^[A-Z]/.test(t[c])){o=c;break}const r=t.slice(0,o),i=r.length>0?`/${r.join("/")}`:"/",s=t.slice(o);return{name:R(s),path:i}}function E(n){const e=T(n);return d(e)}function D(n){return`${X(n)}_BOUNDED_CONTEXT_ALIAS`}class Xe{constructor(e,t,o,r){this.modelInfo=e,this.sourceFile=t,this.keySchema=o,this.outputDir=r}generate(){const e=this.process();e&&ke(e,this.keySchema.schema,this.keySchema.key)}process(){const{schema:e}=this.keySchema;return B(e)?this.processEnum(e):I(e)?this.processInterface(e):b(e)?this.processArray(e):M(e)?this.processIntersection(e):U(e)?this.processComposition(e):this.processTypeAlias(e)}resolveReference(e){const t=E(e);return Ge(this.modelInfo,this.sourceFile,this.outputDir,t),t}resolveAdditionalProperties(e){return e.additionalProperties===void 0||e.additionalProperties===!1?"":e.additionalProperties===!0?"[key: string]: any":`[key: string]: ${this.resolveType(e.additionalProperties)}`}resolvePropertyDefinitions(e){const{properties:t}=e;return Object.entries(t).map(([o,r])=>{const i=this.resolveType(r),s=O(o);if(!g(r)){const a=W(r),c=ge(a,`
|
|
3
3
|
* `);if(c)return`
|
|
4
4
|
/**
|
|
5
5
|
* ${c}
|
|
@@ -8,14 +8,14 @@
|
|
|
8
8
|
`}return`${s}: ${i}`})}resolveObjectType(e){const t=[];if(I(e)){const r=this.resolvePropertyDefinitions(e);t.push(...r)}const o=this.resolveAdditionalProperties(e);return o&&t.push(o),t.length===0?"Record<string, any>":`{
|
|
9
9
|
${t.join(`;
|
|
10
10
|
`)};
|
|
11
|
-
}`}resolveMapValueType(e){return e.additionalProperties===void 0||e.additionalProperties===!1||e.additionalProperties===!0?"any":this.resolveType(e.additionalProperties)}resolveType(e){if(
|
|
11
|
+
}`}resolveMapValueType(e){return e.additionalProperties===void 0||e.additionalProperties===!1||e.additionalProperties===!0?"any":this.resolveType(e.additionalProperties)}resolveType(e){if(g(e))return this.resolveReference(e).name;if(Ee(e))return`Record<string,${this.resolveMapValueType(e)}>`;if(e.const)return`'${e.const}'`;if(B(e))return e.enum.map(t=>`\`${t}\``).join(" | ");if(U(e)){const o=(e.oneOf||e.anyOf||e.allOf||[]).map(i=>this.resolveType(i)),r=M(e)?" & ":" | ";return`(${o.join(r)})`}if(b(e)){const t=this.resolveType(e.items);return Ie(t)}return e.type==="object"?this.resolveObjectType(e):e.type?w(e.type):"any"}processEnum(e){return this.sourceFile.addEnum({name:this.modelInfo.name,isExported:!0,members:e.enum.filter(t=>typeof t=="string"&&t.length>0).map(t=>({name:Ae(t),initializer:`\`${t}\``}))})}addPropertyToInterface(e,t,o){const r=this.resolveType(o),i=O(t);let s=e.getProperty(i);s?s.setType(r):s=e.addProperty({name:i,type:r,isReadonly:Re(o)}),We(s,o)}processInterface(e){const t=this.sourceFile.addInterface({name:this.modelInfo.name,isExported:!0}),o=e.properties||{};return Object.entries(o).forEach(([r,i])=>{this.addPropertyToInterface(t,r,i)}),e.additionalProperties&&t.addIndexSignature({keyName:"key",keyType:"string",returnType:this.resolveType(e.additionalProperties===!0?{}:e.additionalProperties)}).addJsDoc("Additional properties"),t}processArray(e){const t=this.resolveType(e.items);return this.sourceFile.addTypeAlias({name:this.modelInfo.name,type:`Array<${t}>`,isExported:!0})}processComposition(e){return this.sourceFile.addTypeAlias({name:this.modelInfo.name,type:this.resolveType(e),isExported:!0})}processIntersection(e){const t=this.sourceFile.addInterface({name:this.modelInfo.name,isExported:!0});return e.allOf.forEach(o=>{if(g(o)){const r=this.resolveType(o);t.addExtends(r);return}I(o)&&Object.entries(o.properties).forEach(([r,i])=>{this.addPropertyToInterface(t,r,i)})}),t}processTypeAlias(e){return this.sourceFile.addTypeAlias({name:this.modelInfo.name,type:this.resolveType(e),isExported:!0})}}class et{constructor(e){this.context=e}getOrCreateSourceFile(e){const t=_e(e);return this.context.getOrCreateSourceFile(t)}generate(){const e=this.context.openAPI.components?.schemas;if(!e){this.context.logger.info("No schemas found in OpenAPI specification");return}const t=this.stateAggregatedTypeNames(),o=this.filterSchemas(e,t);this.context.logger.progress(`Generating models for ${o.length} schemas`),o.forEach((r,i)=>{this.context.logger.progressWithCount(i+1,o.length,`Processing schema: ${r.key}`,2),this.generateKeyedSchema(r)}),this.context.logger.success("Model generation completed")}filterSchemas(e,t){return Object.entries(e).map(([o,r])=>({key:o,schema:r})).filter(o=>!this.isWowSchema(o.key,t))}isWowSchema(e,t){if(e!=="wow.api.query.PagedList"&&e.startsWith("wow.api.query.")&&e.endsWith("PagedList"))return!1;if(e.startsWith("wow.")||e.endsWith("AggregatedCondition")||e.endsWith("AggregatedDomainEventStream")||e.endsWith("AggregatedDomainEventStreamPagedList")||e.endsWith("AggregatedDomainEventStreamServerSentEventNonNullData")||e.endsWith("AggregatedListQuery")||e.endsWith("AggregatedPagedQuery")||e.endsWith("AggregatedSingleQuery"))return!0;const o=d(e);return t.has(o.name)}aggregatedSchemaSuffix=["MaterializedSnapshot","MaterializedSnapshotPagedList","MaterializedSnapshotServerSentEventNonNullData","PagedList","ServerSentEventNonNullData","Snapshot","StateEvent"];stateAggregatedTypeNames(){const e=new Set;for(const[t,o]of this.context.contextAggregates){this.generateBoundedContext(t);for(const r of o)this.aggregatedSchemaSuffix.forEach(i=>{const s=d(r.state.key),a=R(s.name)+i;e.add(a)})}return e}generateKeyedSchema(e){const t=d(e.key),o=this.getOrCreateSourceFile(t);new Xe(t,o,e,this.context.outputDir).generate()}generateBoundedContext(e){const t=`${e}/boundedContext.ts`;this.context.logger.info(`Creating bounded context file: ${t}`);const o=this.context.getOrCreateSourceFile(t),r=D(e);o.addStatements(`export const ${r} = '${e}';`)}}const tt="@ahoo-wang/fetcher-decorator",nt=["type ApiMetadata","type ApiMetadataCapable","type ParameterRequest","api","get","post","put","patch","del","request","attribute","path","autoGeneratedError"],ot={type:"Promise<Response>",metadata:"{resultExtractor: ResultExtractors.Response }"},V={type:"Promise<string>",metadata:"{resultExtractor: ResultExtractors.Text }"},q=`{
|
|
12
12
|
headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },
|
|
13
13
|
resultExtractor: JsonEventStreamResultExtractor,
|
|
14
|
-
}`;function me(n){P(n,ot,rt)}function F(n,e,t=[],o=[],r){return e.addClass({name:n,isExported:!0,typeParameters:o,extends:r,decorators:[{name:"api",arguments:t}]})}function de(n,e){n.addImplements("ApiMetadataCapable"),n.addConstructor({parameters:[{name:"apiMetadata",type:"ApiMetadata",hasQuestionToken:e===void 0,scope:C.Scope.Public,isReadonly:!0,initializer:e}]})}const st="@ahoo-wang/fetcher-eventstream";function fe(n){P(n,st,["JsonEventStreamResultExtractor","type JsonServerSentEventStream"])}function at(n){let e=0,t=0;return n.commands.forEach(o=>{o.path.startsWith(z.ResourceAttributionPathSpec.TENANT)&&(e+=1),o.path.startsWith(z.ResourceAttributionPathSpec.OWNER)&&(t+=1)}),e===0&&t===0?"ResourceAttributionPathSpec.NONE":e>t?"ResourceAttributionPathSpec.TENANT":"ResourceAttributionPathSpec.OWNER"}function he(n,e,t,o){const r=`${t.contextAlias}/${t.aggregateName}/${o}.ts`;return ge(n,e,r)}function y(n,e){return`${R(n.aggregateName)}${e}`}function j(n){return n==="delete"?"del":n}const ct="x-fetcher-method";function pt(n,e){const t=n[ct];if(t)return t;if(!n.operationId)return;const o=N(n.operationId);for(let r=o.length-1;r>=0;r--){const i=h(o.slice(r));if(!e(i))return i}return h(o)}class gt{constructor(e){this.context=e,this.apiMetadataCtorInitializer=this.context.currentContextAlias?`{basePath:${D(this.context.currentContextAlias)}}`:void 0}defaultParameterRequestType="ParameterRequest";defaultReturnType=it;apiMetadataCtorInitializer;generate(){this.context.logger.info("Starting API client generation");const e=this.resolveApiTags();this.context.logger.info(`Resolved ${e.size} API client tags: ${Array.from(e.keys()).join(", ")}`);const t=this.groupOperations(e);this.context.logger.info(`Grouped operations into ${t.size} tag groups`),this.generateApiClients(e,t),this.context.logger.success("API client generation completed")}generateApiClients(e,t){this.context.logger.info(`Generating ${t.size} API client classes`);let o=0;for(const[r,i]of t){o++,this.context.logger.progressWithCount(o,t.size,`Generating API client for tag: ${r}`);const s=e.get(r);this.generateApiClient(s,i)}}createApiClientFile(e){let t=e.path;return this.context.currentContextAlias&&(t=f.combineURLs(this.context.currentContextAlias,t)),t=f.combineURLs(t,`${e.name}ApiClient.ts`),this.context.logger.info(`Creating API client file: ${t}`),this.context.getOrCreateSourceFile(t)}generateApiClient(e,t){const o=m(e.name);this.context.logger.info(`Generating API client class: ${o.name}ApiClient with ${t.size} operations`);const r=this.createApiClientFile(o);me(r),fe(r);const i=F(o.name+"ApiClient",r);$(i,[e.description]),de(i,this.apiMetadataCtorInitializer),this.context.logger.info(`Processing ${t.size} operations for ${o.name}ApiClient`),t.forEach(s=>{this.processOperation(e,r,i,s)}),this.context.logger.success(`Completed API client: ${o.name}ApiClient`)}getMethodName(e,t){const o=pt(t,r=>e.getMethod(r)!==void 0);if(!o)throw new Error(`Unable to resolve method name for apiClientClass:${e.getName()}.`);return o}resolveRequestType(e,t){if(!t.requestBody)return this.context.logger.info(`No request body found for operation ${t.operationId}, using default: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType;let o;if(p(t.requestBody)?(this.context.logger.info(`Extracting request body from reference for operation: ${t.operationId}`),o=Z(t.requestBody,this.context.openAPI.components)):o=t.requestBody,!o)return this.context.logger.info(`Request body extraction failed for operation ${t.operationId}, using default: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType;if(o.content["multipart/form-data"])return this.context.logger.info(`Detected multipart/form-data content for operation ${t.operationId}, using ParameterRequest<FormData>`),"ParameterRequest<FormData>";if(o.content["application/json"]){const r=o.content["application/json"].schema;if(p(r)){const i=E(r);this.context.logger.info(`Adding import for request body model: ${i.name} from ${i.path}`),d(e,this.context.outputDir,i);const s=`ParameterRequest<${i.name}>`;return this.context.logger.info(`Resolved request type for operation ${t.operationId}: ${s}`),s}}return this.context.logger.info(`Using default request type for operation ${t.operationId}: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType}resolveParameters(e,t,o){const r=be(o,this.context.openAPI.components).filter(a=>!this.context.isIgnoreApiClientPathParameters(e.name,a.name));this.context.logger.info(`Found ${r.length} path parameters for operation ${o.operationId}`);const i=r.map(a=>{const c=se(a);return this.context.logger.info(`Adding path parameter: ${a.name} (type: ${c})`),{name:a.name,type:c,hasQuestionToken:!1,decorators:[{name:"path",arguments:[`'${a.name}'`]}]}}),s=this.resolveRequestType(t,o);return this.context.logger.info(`Adding httpRequest parameter: ${s}`),i.push({name:"httpRequest",hasQuestionToken:s===this.defaultParameterRequestType,type:`${s}`,decorators:[{name:"request",arguments:[]}]}),this.context.logger.info("Adding attributes parameter: Record<string, any>"),i.push({name:"attributes",hasQuestionToken:!0,type:"Record<string, any>",decorators:[{name:"attribute",arguments:[]}]}),i}resolveSchemaReturnType(e,t){const o="Promise<any>";if(p(t)){const r=E(t);this.context.logger.info(`Adding import for response model: ${r.name} from ${r.path}`),d(e,this.context.outputDir,r);const i=`Promise<${r.name}>`;return this.context.logger.info(`Resolved reference return type: ${i}`),i}if(!t.type)return this.context.logger.info(`Schema has no type, using default return type: ${o}`),o;if(oe(t.type)){const i=`Promise<${w(t.type)}>`;return this.context.logger.info(`Resolved primitive return type: ${i}`),i}return this.context.logger.info(`Using default return type: ${o}`),o}resolveReturnType(e,t){const o=G(t);if(!o)return this.context.logger.info(`No OK response found for operation ${t.operationId}, using default return type: ${this.defaultReturnType.type}`),this.defaultReturnType;const r=ne(o)||Te(o);if(r){const s=this.resolveSchemaReturnType(e,r);return this.context.logger.info(`Resolved JSON/wildcard response return type for operation ${t.operationId}: ${s}`),{type:s,metadata:s===H.type?H.metadata:void 0}}const i=$e(o);if(i){if(p(i)){const a=S(i,this.context.openAPI.components);if(b(a)&&p(a.items)){const c=E(a.items);this.context.logger.info(`Adding import for event stream model: ${c.name} from ${c.path}`),d(e,this.context.outputDir,c);const g=`Promise<JsonServerSentEventStream<${c.name.includes("ServerSentEvent")?`${c.name}['data']`:c.name}>>`;return this.context.logger.info(`Resolved event stream return type for operation ${t.operationId}: ${g}`),{type:g,metadata:q}}}const s="Promise<JsonServerSentEventStream<any>>";return this.context.logger.info(`Resolved generic event stream return type for operation ${t.operationId}: ${s}`),{type:s,metadata:q}}return this.context.logger.info(`Using default return type for operation ${t.operationId}: ${this.defaultReturnType.type}`),this.defaultReturnType}processOperation(e,t,o,r){this.context.logger.info(`Processing operation: ${r.operation.operationId} (${r.method} ${r.path})`);const i=this.getMethodName(o,r.operation);this.context.logger.info(`Generated method name: ${i}`);const s=this.resolveParameters(e,t,r.operation),a=this.resolveReturnType(t,r.operation),c=a.metadata?{name:j(r.method),arguments:[`'${r.path}'`,a.metadata]}:{name:j(r.method),arguments:[`'${r.path}'`]};this.context.logger.info(`Creating method with ${s.length} parameters, return type: ${a.type}`);const u=o.addMethod({name:i,decorators:[c],parameters:s,returnType:a.type,statements:[`throw autoGeneratedError(${s.map(g=>g.name).join(",")});`]});$(u,[r.operation.summary,r.operation.description,`- operationId: \`${r.operation.operationId}\``,`- path: \`${r.path}\``]),this.context.logger.success(`Operation method generated: ${i}`)}groupOperations(e){this.context.logger.info("Grouping operations by API client tags");const t=new Map,o=re(this.context.openAPI.paths).filter(i=>{if(!i.operation.operationId)return!1;const s=i.operation.tags;return!s||s.length==0?!1:s.every(a=>e.has(a))});let r=0;for(const i of o)i.operation.tags.forEach(s=>{t.has(s)||t.set(s,new Set),t.get(s).add(i),r++});return this.context.logger.info(`Grouped ${r} operations into ${t.size} tag groups`),t}shouldIgnoreTag(e){return e==="wow"||e==="Actuator"||this.isAggregateTag(e)}resolveApiTags(){this.context.logger.info("Resolving API client tags from OpenAPI specification");const e=new Map,t=this.context.openAPI.tags?.length||0;for(const r of Object.values(this.context.openAPI.paths))ie(r).forEach(i=>{i.operation.tags?.forEach(s=>{!this.shouldIgnoreTag(s)&&!e.has(s)&&e.set(s,{name:s,description:""})})});let o=0;return this.context.openAPI.tags?.forEach(r=>{this.shouldIgnoreTag(r.name)?this.context.logger.info(`Excluded tag: ${r.name} (wow/Actuator/aggregate)`):(e.set(r.name,r),o++,this.context.logger.info(`Included API client tag: ${r.name}`))}),this.context.logger.info(`Resolved ${o} API client tags from ${t} total tags`),e}isAggregateTag(e){for(const t of this.context.contextAggregates.values())for(const o of t)if(o.aggregate.tag.name===e)return!0;return!1}}class ut{constructor(e){this.context=e}commandEndpointPathsSuffix="CommandEndpointPaths";defaultCommandClientOptionsName="DEFAULT_COMMAND_CLIENT_OPTIONS";generate(){const e=Array.from(this.context.contextAggregates.values()).reduce((o,r)=>o+r.size,0);this.context.logger.info("--- Generating Command Clients ---"),this.context.logger.progress(`Generating command clients for ${e} aggregates`);let t=0;for(const[,o]of this.context.contextAggregates)o.forEach(r=>{t++,this.context.logger.progressWithCount(t,e,`Processing command client for aggregate: ${r.aggregate.aggregateName}`),this.processAggregate(r)});this.context.logger.success("Command client generation completed")}processAggregate(e){this.context.logger.info(`Processing command client for aggregate: ${e.aggregate.aggregateName} in context: ${e.aggregate.contextAlias}`);const t=he(this.context.project,this.context.outputDir,e.aggregate,"commandClient");this.context.logger.info(`Processing command endpoint paths for ${e.commands.size} commands`);const o=this.processCommandEndpointPaths(t,e);this.processCommandTypes(t,e),this.context.logger.info(`Creating default command client options: ${this.defaultCommandClientOptionsName}`),t.addVariableStatement({declarationKind:C.VariableDeclarationKind.Const,declarations:[{name:this.defaultCommandClientOptionsName,type:"ApiMetadata",initializer:`{
|
|
14
|
+
}`;function ue(n){P(n,tt,nt)}function F(n,e,t=[],o=[],r){return e.addClass({name:n,isExported:!0,typeParameters:o,extends:r,decorators:[{name:"api",arguments:t}]})}function le(n,e){n.addImplements("ApiMetadataCapable"),n.addConstructor({parameters:[{name:"apiMetadata",type:"ApiMetadata",hasQuestionToken:e===void 0,scope:C.Scope.Public,isReadonly:!0,initializer:e}]})}const rt="@ahoo-wang/fetcher-eventstream";function de(n){P(n,rt,["JsonEventStreamResultExtractor","type JsonServerSentEventStream"])}function it(n){let e=0,t=0;return n.commands.forEach(o=>{o.path.startsWith(z.ResourceAttributionPathSpec.TENANT)&&(e+=1),o.path.startsWith(z.ResourceAttributionPathSpec.OWNER)&&(t+=1)}),e===0&&t===0?"ResourceAttributionPathSpec.NONE":e>t?"ResourceAttributionPathSpec.TENANT":"ResourceAttributionPathSpec.OWNER"}function me(n,e,t,o){const r=`${t.contextAlias}/${t.aggregateName}/${o}.ts`;return ce(n,e,r)}function y(n,e){return`${R(n.aggregateName)}${e}`}function j(n){return n==="delete"?"del":n}const st="x-fetcher-method";function at(n,e){const t=n[st];if(t)return t;if(!n.operationId)return;const o=N(n.operationId);for(let r=o.length-1;r>=0;r--){const i=h(o.slice(r));if(!e(i))return i}return h(o)}class ct{constructor(e){this.context=e,this.apiMetadataCtorInitializer=this.context.currentContextAlias?`{basePath:${D(this.context.currentContextAlias)}}`:void 0}defaultParameterRequestType="ParameterRequest";defaultReturnType=ot;apiMetadataCtorInitializer;generate(){this.context.logger.info("Starting API client generation");const e=this.resolveApiTags();this.context.logger.info(`Resolved ${e.size} API client tags: ${Array.from(e.keys()).join(", ")}`);const t=this.groupOperations(e);this.context.logger.info(`Grouped operations into ${t.size} tag groups`),this.generateApiClients(e,t),this.context.logger.success("API client generation completed")}generateApiClients(e,t){this.context.logger.info(`Generating ${t.size} API client classes`);let o=0;for(const[r,i]of t){o++,this.context.logger.progressWithCount(o,t.size,`Generating API client for tag: ${r}`);const s=e.get(r);this.generateApiClient(s,i)}}createApiClientFile(e){let t=e.path;return this.context.currentContextAlias&&(t=f.combineURLs(this.context.currentContextAlias,t)),t=f.combineURLs(t,`${e.name}ApiClient.ts`),this.context.logger.info(`Creating API client file: ${t}`),this.context.getOrCreateSourceFile(t)}generateApiClient(e,t){const o=d(e.name);this.context.logger.info(`Generating API client class: ${o.name}ApiClient with ${t.size} operations`);const r=this.createApiClientFile(o);ue(r),de(r);const i=F(o.name+"ApiClient",r);$(i,[e.description]),le(i,this.apiMetadataCtorInitializer),this.context.logger.info(`Processing ${t.size} operations for ${o.name}ApiClient`),t.forEach(s=>{this.processOperation(e,r,i,s)}),this.context.logger.success(`Completed API client: ${o.name}ApiClient`)}getMethodName(e,t){const o=at(t,r=>e.getMethod(r)!==void 0);if(!o)throw new Error(`Unable to resolve method name for apiClientClass:${e.getName()}.`);return o}resolveRequestType(e,t){if(!t.requestBody)return this.context.logger.info(`No request body found for operation ${t.operationId}, using default: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType;let o;if(g(t.requestBody)?(this.context.logger.info(`Extracting request body from reference for operation: ${t.operationId}`),o=H(t.requestBody,this.context.openAPI.components)):o=t.requestBody,!o)return this.context.logger.info(`Request body extraction failed for operation ${t.operationId}, using default: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType;if(o.content["multipart/form-data"])return this.context.logger.info(`Detected multipart/form-data content for operation ${t.operationId}, using ParameterRequest<FormData>`),"ParameterRequest<FormData>";if(o.content["application/json"]){const r=o.content["application/json"].schema;if(g(r)){const i=E(r);this.context.logger.info(`Adding import for request body model: ${i.name} from ${i.path}`),m(e,this.context.outputDir,i);const s=`ParameterRequest<${i.name}>`;return this.context.logger.info(`Resolved request type for operation ${t.operationId}: ${s}`),s}}return this.context.logger.info(`Using default request type for operation ${t.operationId}: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType}resolveParameters(e,t,o){const r=Ne(o,this.context.openAPI.components).filter(a=>!this.context.isIgnoreApiClientPathParameters(e.name,a.name));this.context.logger.info(`Found ${r.length} path parameters for operation ${o.operationId}`);const i=r.map(a=>{const c=re(a);return this.context.logger.info(`Adding path parameter: ${a.name} (type: ${c})`),{name:a.name,type:c,hasQuestionToken:!1,decorators:[{name:"path",arguments:[`'${a.name}'`]}]}}),s=this.resolveRequestType(t,o);return this.context.logger.info(`Adding httpRequest parameter: ${s}`),i.push({name:"httpRequest",hasQuestionToken:s===this.defaultParameterRequestType,type:`${s}`,decorators:[{name:"request",arguments:[]}]}),this.context.logger.info("Adding attributes parameter: Record<string, any>"),i.push({name:"attributes",hasQuestionToken:!0,type:"Record<string, any>",decorators:[{name:"attribute",arguments:[]}]}),i}resolveSchemaReturnType(e,t){const o="Promise<any>";if(g(t)){const r=E(t);this.context.logger.info(`Adding import for response model: ${r.name} from ${r.path}`),m(e,this.context.outputDir,r);const i=`Promise<${r.name}>`;return this.context.logger.info(`Resolved reference return type: ${i}`),i}if(!t.type)return this.context.logger.info(`Schema has no type, using default return type: ${o}`),o;if(te(t.type)){const i=`Promise<${w(t.type)}>`;return this.context.logger.info(`Resolved primitive return type: ${i}`),i}return this.context.logger.info(`Using default return type: ${o}`),o}resolveReturnType(e,t){const o=G(t);if(!o)return this.context.logger.info(`No OK response found for operation ${t.operationId}, using default return type: ${this.defaultReturnType.type}`),this.defaultReturnType;const r=ee(o)||Pe(o);if(r){const s=this.resolveSchemaReturnType(e,r);return this.context.logger.info(`Resolved JSON/wildcard response return type for operation ${t.operationId}: ${s}`),{type:s,metadata:s===V.type?V.metadata:void 0}}const i=Ce(o);if(i){if(g(i)){const a=S(i,this.context.openAPI.components);if(b(a)&&g(a.items)){const c=E(a.items);this.context.logger.info(`Adding import for event stream model: ${c.name} from ${c.path}`),m(e,this.context.outputDir,c);const p=`Promise<JsonServerSentEventStream<${c.name.includes("ServerSentEvent")?`${c.name}['data']`:c.name}>>`;return this.context.logger.info(`Resolved event stream return type for operation ${t.operationId}: ${p}`),{type:p,metadata:q}}}const s="Promise<JsonServerSentEventStream<any>>";return this.context.logger.info(`Resolved generic event stream return type for operation ${t.operationId}: ${s}`),{type:s,metadata:q}}return this.context.logger.info(`Using default return type for operation ${t.operationId}: ${this.defaultReturnType.type}`),this.defaultReturnType}processOperation(e,t,o,r){this.context.logger.info(`Processing operation: ${r.operation.operationId} (${r.method} ${r.path})`);const i=this.getMethodName(o,r.operation);this.context.logger.info(`Generated method name: ${i}`);const s=this.resolveParameters(e,t,r.operation),a=this.resolveReturnType(t,r.operation),c=a.metadata?{name:j(r.method),arguments:[`'${r.path}'`,a.metadata]}:{name:j(r.method),arguments:[`'${r.path}'`]};this.context.logger.info(`Creating method with ${s.length} parameters, return type: ${a.type}`);const u=o.addMethod({name:i,decorators:[c],parameters:s,returnType:a.type,statements:[`throw autoGeneratedError(${s.map(p=>p.name).join(",")});`]});$(u,[r.operation.summary,r.operation.description,`- operationId: \`${r.operation.operationId}\``,`- path: \`${r.path}\``]),this.context.logger.success(`Operation method generated: ${i}`)}groupOperations(e){this.context.logger.info("Grouping operations by API client tags");const t=new Map,o=ne(this.context.openAPI.paths).filter(i=>{if(!i.operation.operationId)return!1;const s=i.operation.tags;return!s||s.length==0?!1:s.every(a=>e.has(a))});let r=0;for(const i of o)i.operation.tags.forEach(s=>{t.has(s)||t.set(s,new Set),t.get(s).add(i),r++});return this.context.logger.info(`Grouped ${r} operations into ${t.size} tag groups`),t}shouldIgnoreTag(e){return e==="wow"||e==="Actuator"||this.isAggregateTag(e)}resolveApiTags(){this.context.logger.info("Resolving API client tags from OpenAPI specification");const e=new Map,t=this.context.openAPI.tags?.length||0;for(const r of Object.values(this.context.openAPI.paths))oe(r).forEach(i=>{i.operation.tags?.forEach(s=>{!this.shouldIgnoreTag(s)&&!e.has(s)&&e.set(s,{name:s,description:""})})});let o=0;return this.context.openAPI.tags?.forEach(r=>{this.shouldIgnoreTag(r.name)?this.context.logger.info(`Excluded tag: ${r.name} (wow/Actuator/aggregate)`):(e.set(r.name,r),o++,this.context.logger.info(`Included API client tag: ${r.name}`))}),this.context.logger.info(`Resolved ${o} API client tags from ${t} total tags`),e}isAggregateTag(e){for(const t of this.context.contextAggregates.values())for(const o of t)if(o.aggregate.tag.name===e)return!0;return!1}}class gt{constructor(e){this.context=e}commandEndpointPathsSuffix="CommandEndpointPaths";defaultCommandClientOptionsName="DEFAULT_COMMAND_CLIENT_OPTIONS";generate(){const e=Array.from(this.context.contextAggregates.values()).reduce((o,r)=>o+r.size,0);this.context.logger.info("--- Generating Command Clients ---"),this.context.logger.progress(`Generating command clients for ${e} aggregates`);let t=0;for(const[,o]of this.context.contextAggregates)o.forEach(r=>{t++,this.context.logger.progressWithCount(t,e,`Processing command client for aggregate: ${r.aggregate.aggregateName}`),this.processAggregate(r)});this.context.logger.success("Command client generation completed")}processAggregate(e){this.context.logger.info(`Processing command client for aggregate: ${e.aggregate.aggregateName} in context: ${e.aggregate.contextAlias}`);const t=me(this.context.project,this.context.outputDir,e.aggregate,"commandClient");this.context.logger.info(`Processing command endpoint paths for ${e.commands.size} commands`);const o=this.processCommandEndpointPaths(t,e);this.processCommandTypes(t,e),this.context.logger.info(`Creating default command client options: ${this.defaultCommandClientOptionsName}`),t.addVariableStatement({declarationKind:C.VariableDeclarationKind.Const,declarations:[{name:this.defaultCommandClientOptionsName,type:"ApiMetadata",initializer:`{
|
|
15
15
|
basePath: ${D(e.aggregate.contextAlias)}
|
|
16
|
-
}`}],isExported:!1}),this.context.logger.info(`Adding imports from ${x}: CommandRequest, CommandResult, CommandResultEventStream, CommandBody, DeleteAggregateCommand, RecoverAggregateCommand`),t.addImportDeclaration({moduleSpecifier:x,namedImports:["CommandRequest","CommandResult","CommandResultEventStream","CommandBody","DeleteAggregateCommand","RecoverAggregateCommand"],isTypeOnly:!0}),this.context.logger.info("Adding import from @ahoo-wang/fetcher-eventstream: JsonEventStreamResultExtractor"),
|
|
16
|
+
}`}],isExported:!1}),this.context.logger.info(`Adding imports from ${x}: CommandRequest, CommandResult, CommandResultEventStream, CommandBody, DeleteAggregateCommand, RecoverAggregateCommand`),t.addImportDeclaration({moduleSpecifier:x,namedImports:["CommandRequest","CommandResult","CommandResultEventStream","CommandBody","DeleteAggregateCommand","RecoverAggregateCommand"],isTypeOnly:!0}),this.context.logger.info("Adding import from @ahoo-wang/fetcher-eventstream: JsonEventStreamResultExtractor"),de(t),this.context.logger.info("Adding import from @ahoo-wang/fetcher: ContentTypeValues"),P(t,"@ahoo-wang/fetcher",["ContentTypeValues"]),this.context.logger.info("Adding imports from @ahoo-wang/fetcher-decorator: ApiMetadata types and decorators"),ue(t),this.context.logger.info("Generating standard command client class"),this.processCommandClient(t,e,o),this.context.logger.info("Generating stream command client class"),this.processStreamCommandClient(t,e),this.context.logger.success(`Command client generation completed for aggregate: ${e.aggregate.aggregateName}`)}resolveAggregateCommandEndpointPathsName(e){return y(e,this.commandEndpointPathsSuffix)}processCommandEndpointPaths(e,t){const o=this.resolveAggregateCommandEndpointPathsName(t.aggregate);this.context.logger.info(`Creating command endpoint paths enum: ${o}`);const r=e.addEnum({name:o,isExported:!0});return t.commands.forEach(i=>{this.context.logger.info(`Adding command endpoint: ${i.name.toUpperCase()} = '${i.path}'`),r.addMember({name:i.name.toUpperCase(),initializer:`'${i.path}'`})}),this.context.logger.success(`Command endpoint paths enum created with ${t.commands.size} entries`),o}resolveCommandTypeName(e){const t=d(e.schema.key);return[t,t.name+"Command"]}resolveCommandType(e,t){const[o,r]=this.resolveCommandTypeName(t);if(o.path===x)return;m(e,this.context.outputDir,o);let i=`${o.name}`;const s=we(t.schema.schema).map(a=>`'${a}'`).join(" | ");s!==""&&(i=`PartialBy<${i},${s}>`),i=`CommandBody<${i}>`,e.addTypeAlias({name:r,type:`${i}`,isExported:!0})}processCommandTypes(e,t){t.commands.forEach(o=>{this.resolveCommandType(e,o)})}getEndpointPath(e,t){return`${e}.${t.name.toUpperCase()}`}processCommandClient(e,t,o){const r=y(t.aggregate,"CommandClient"),i=F(r,e,[],["R = CommandResult"]);le(i,this.defaultCommandClientOptionsName),t.commands.forEach(s=>{this.processCommandMethod(t,i,s,o)})}processStreamCommandClient(e,t){const o=y(t.aggregate,"CommandClient"),r=y(t.aggregate,"StreamCommandClient");F(r,e,["''",q],[],`${o}<CommandResultEventStream>`).addConstructor({parameters:[{name:"apiMetadata",type:"ApiMetadata",initializer:this.defaultCommandClientOptionsName}],statements:"super(apiMetadata);"})}resolveParameters(e,t){const[o,r]=this.resolveCommandTypeName(t);this.context.logger.info(`Adding import for command model: ${o.name} from path: ${o.path}`);const i=t.pathParameters.filter(s=>!this.context.isIgnoreCommandClientPathParameters(e.name,s.name)).map(s=>{const a=re(s);return this.context.logger.info(`Adding path parameter: ${s.name} (type: ${a})`),{name:s.name,type:a,hasQuestionToken:!1,decorators:[{name:"path",arguments:[`'${s.name}'`]}]}});return this.context.logger.info(`Adding command request parameter: commandRequest (type: CommandRequest<${r}>)`),i.push({name:"commandRequest",hasQuestionToken:Se(t.schema.schema),type:`CommandRequest<${r}>`,decorators:[{name:"request",arguments:[]}]}),this.context.logger.info("Adding attributes parameter: attributes (type: Record<string, any>)"),i.push({name:"attributes",hasQuestionToken:!0,type:"Record<string, any>",decorators:[{name:"attribute",arguments:[]}]}),i}processCommandMethod(e,t,o,r){this.context.logger.info(`Generating command method: ${h(o.name)} for command: ${o.name}`),this.context.logger.info(`Command method details: HTTP ${o.method}, path: ${o.path}`);const i=this.resolveParameters(e.aggregate.tag,o),s=t.addMethod({name:h(o.name),decorators:[{name:j(o.method),arguments:[`${this.getEndpointPath(r,o)}`]}],parameters:i,returnType:"Promise<R>",statements:`throw autoGeneratedError(${i.map(a=>a.name).join(",")});`});this.context.logger.info(`Adding JSDoc documentation for method: ${h(o.name)}`),$(s,[o.summary,o.description,`- operationId: \`${o.operation.operationId}\``,`- path: \`${o.path}\``]),this.context.logger.success(`Command method generated: ${h(o.name)}`)}}class pt{constructor(e){this.context=e}domainEventTypeSuffix="DomainEventType";domainEventTypeMapTitleSuffix="DomainEventTypeMapTitle";generate(){const e=Array.from(this.context.contextAggregates.values()).reduce((o,r)=>o+r.size,0);this.context.logger.info("--- Generating Query Clients ---"),this.context.logger.progress(`Generating query clients for ${e} aggregates`);let t=0;for(const[,o]of this.context.contextAggregates)o.forEach(r=>{t++,this.context.logger.progressWithCount(t,e,`Processing query client for aggregate: ${r.aggregate.aggregateName}`),this.processQueryClient(r)});this.context.logger.success("Query client generation completed")}createClientFilePath(e,t){return me(this.context.project,this.context.outputDir,e,t)}processQueryClient(e){const t=this.createClientFilePath(e.aggregate,"queryClient");this.context.logger.info(`Processing query client for aggregate: ${e.aggregate.aggregateName} in context: ${e.aggregate.contextAlias}`),this.context.logger.info(`Adding imports from ${x}: QueryClientFactory, QueryClientOptions, ResourceAttributionPathSpec`),t.addImportDeclaration({moduleSpecifier:x,namedImports:["QueryClientFactory","QueryClientOptions","ResourceAttributionPathSpec"]});const o="DEFAULT_QUERY_CLIENT_OPTIONS";this.context.logger.info(`Creating default query client options: ${o}`),t.addVariableStatement({declarationKind:C.VariableDeclarationKind.Const,declarations:[{name:o,type:"QueryClientOptions",initializer:`{
|
|
17
17
|
contextAlias: ${D(e.aggregate.contextAlias)},
|
|
18
18
|
aggregateName: '${e.aggregate.aggregateName}',
|
|
19
|
-
resourceAttribution: ${
|
|
20
|
-
}`}],isExported:!1}),this.processAggregateDomainEventTypes(e,t);const r=this.processAggregateDomainEventType(e,t),i=`${h(e.aggregate.aggregateName)}QueryClientFactory`,s=
|
|
19
|
+
resourceAttribution: ${it(e)},
|
|
20
|
+
}`}],isExported:!1}),this.processAggregateDomainEventTypes(e,t);const r=this.processAggregateDomainEventType(e,t),i=`${h(e.aggregate.aggregateName)}QueryClientFactory`,s=d(e.state.key),a=d(e.fields.key);this.context.logger.info(`Adding import for state model: ${s.name} from path: ${s.path}`),m(t,this.context.outputDir,s),this.context.logger.info(`Adding import for fields model: ${a.name} from path: ${a.path}`),m(t,this.context.outputDir,a),this.context.logger.info(`Creating query client factory: ${i}`),t.addVariableStatement({declarationKind:C.VariableDeclarationKind.Const,declarations:[{name:i,initializer:`new QueryClientFactory<${s.name}, ${a.name} | string, ${r}>(${o})`}],isExported:!0}),this.context.logger.success(`Query client generation completed for aggregate: ${e.aggregate.aggregateName}`)}processAggregateDomainEventType(e,t){const o=[];this.context.logger.info(`Processing ${e.events.size} domain events for aggregate: ${e.aggregate.aggregateName}`);for(const s of e.events.values()){const a=d(s.schema.key);this.context.logger.info(`Adding import for event model: ${a.name} from path: ${a.path}`),m(t,this.context.outputDir,a),o.push(a)}const r=y(e.aggregate,this.domainEventTypeSuffix),i=o.map(s=>s.name).join(" | ");return this.context.logger.info(`Creating domain event types union: ${r} = ${i}`),t.addTypeAlias({isExported:!0,name:r,type:i}),r}processAggregateDomainEventTypes(e,t){const o=y(e.aggregate,this.domainEventTypeMapTitleSuffix),r=t.addEnum({name:o,isExported:!0});for(const i of e.events.values())r.addMember({name:i.name,initializer:`'${i.title}'`})}}class ut{constructor(e){this.context=e,this.queryClientGenerator=new pt(e),this.commandClientGenerator=new gt(e),this.apiClientGenerator=new ct(e)}queryClientGenerator;commandClientGenerator;apiClientGenerator;generate(){this.context.logger.info("--- Generating Clients ---"),this.context.logger.progress(`Generating clients for ${this.context.contextAggregates.size} bounded contexts`);let e=0;for(const[t]of this.context.contextAggregates)e++,this.context.logger.progressWithCount(e,this.context.contextAggregates.size,`Processing bounded context: ${t}`,1);this.queryClientGenerator.generate(),this.commandClientGenerator.generate(),this.apiClientGenerator.generate(),this.context.logger.success("Client generation completed")}}class lt{project;openAPI;outputDir;contextAggregates;logger;config;defaultIgnorePathParameters=["tenantId","ownerId"];currentContextAlias;constructor(e){this.project=e.project,this.openAPI=e.openAPI,this.outputDir=e.outputDir,this.contextAggregates=e.contextAggregates,this.logger=e.logger,this.config=e.config??{},this.currentContextAlias=this.openAPI.info["x-wow-context-alias"]}getOrCreateSourceFile(e){return ce(this.project,this.outputDir,e)}isIgnoreApiClientPathParameters(e,t){return(this.config.apiClients?.[e]?.ignorePathParameters??this.defaultIgnorePathParameters).includes(t)}isIgnoreCommandClientPathParameters(e,t){return this.defaultIgnorePathParameters.includes(t)}}const fe="./fetcher-generator.config.json";class dt{constructor(e){this.options=e,this.project=new C.Project(e),this.options.logger.info(`Project instance created with tsConfigFilePath: ${this.options.tsConfigFilePath}`)}project;async generate(){this.options.logger.info("Starting code generation from OpenAPI specification"),this.options.logger.info(`Input path: ${this.options.inputPath}`),this.options.logger.info(`Output directory: ${this.options.outputDir}`),this.options.logger.info("Parsing OpenAPI specification");const e=await qe(this.options.inputPath);this.options.logger.info("OpenAPI specification parsed successfully"),this.options.logger.info("Resolving bounded context aggregates");const o=new Ye(e).resolve();this.options.logger.info(`Resolved ${o.size} bounded context aggregates`);const r=this.options.configPath??fe;let i={};try{this.options.logger.info(`Parsing configuration file: ${r}`),i=await Fe(r)}catch(p){this.options.logger.info(`Configuration file parsing failed: ${p}`)}const s=new lt({openAPI:e,project:this.project,outputDir:this.options.outputDir,contextAggregates:o,logger:this.options.logger,config:i});this.options.logger.info("Generating models"),new et(s).generate(),this.options.logger.info("Models generated successfully"),this.options.logger.info("Generating clients"),new ut(s).generate(),this.options.logger.info("Clients generated successfully");const u=this.project.getDirectory(this.options.outputDir);if(!u){this.options.logger.info("Output directory not found.");return}this.options.logger.info("Generating index files"),this.generateIndex(u),this.options.logger.info("Index files generated successfully"),this.options.logger.info("Optimizing source files"),this.optimizeSourceFiles(u),this.options.logger.info("Source files optimized successfully"),this.options.logger.info("Saving project to disk"),await this.project.save(),this.options.logger.info("Code generation completed successfully")}generateIndex(e){this.options.logger.info(`Generating index files for output directory: ${this.options.outputDir}`),this.processDirectory(e),this.generateIndexForDirectory(e),this.options.logger.info("Index file generation completed")}processDirectory(e){const t=e.getDirectories();this.options.logger.info(`Processing ${t.length} subdirectories`);for(const o of t)this.options.logger.info(`Processing subdirectory: ${o.getPath()}`),this.generateIndexForDirectory(o),this.processDirectory(o)}generateIndexForDirectory(e){const t=e.getPath();this.options.logger.info(`Generating index for directory: ${t}`);const o=e.getSourceFiles().filter(a=>a.getBaseName().endsWith(".ts")&&a.getBaseName()!=="index.ts"),r=e.getDirectories();if(this.options.logger.info(`Found ${o.length} TypeScript files and ${r.length} subdirectories in ${t}`),o.length===0&&r.length===0){this.options.logger.info(`No files or subdirectories to export in ${t}, skipping index generation`);return}const i=`${t}/index.ts`,s=this.project.getSourceFile(i)||this.project.createSourceFile(i,"",{overwrite:!0});s.removeText();for(const a of o){const c=`./${a.getBaseNameWithoutExtension()}`;s.addExportDeclaration({moduleSpecifier:c,isTypeOnly:!1,namedExports:[]})}for(const a of r){const c=`./${a.getBaseName()}`;s.addExportDeclaration({moduleSpecifier:c,isTypeOnly:!1,namedExports:[]})}this.options.logger.info(`Index file generated for ${t} with ${o.length+r.length} exports`)}optimizeSourceFiles(e){const t=e.getDescendantSourceFiles();this.options.logger.info(`Optimizing ${t.length} source files in ${e.getPath()}`),t.forEach((o,r)=>{this.options.logger.info(`Optimizing file [${o.getFilePath()}] - ${r+1}/${t.length}`),o.formatText(),o.organizeImports(),o.fixMissingImports()}),this.options.logger.info("All source files optimized")}}exports.CodeGenerator=dt;exports.DEFAULT_CONFIG_PATH=fe;
|
|
21
21
|
//# sourceMappingURL=index.cjs.map
|