@keq-request/cli 5.0.0-alpha.29 → 5.0.0-alpha.31

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.
Files changed (83) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/chunk-7HHTHYRA.cjs +2895 -0
  3. package/dist/chunk-7HHTHYRA.cjs.map +1 -0
  4. package/dist/chunk-DZ2SC5HL.js +2895 -0
  5. package/dist/chunk-DZ2SC5HL.js.map +1 -0
  6. package/dist/chunk-HN7ZZFKC.js +19 -0
  7. package/dist/chunk-HN7ZZFKC.js.map +1 -0
  8. package/dist/chunk-JX74ZR2O.cjs +670 -0
  9. package/dist/chunk-JX74ZR2O.cjs.map +1 -0
  10. package/dist/chunk-OC36G3PF.cjs +19 -0
  11. package/dist/chunk-OC36G3PF.cjs.map +1 -0
  12. package/dist/chunk-XRZLO2PB.js +670 -0
  13. package/dist/chunk-XRZLO2PB.js.map +1 -0
  14. package/dist/cli.cjs +171 -2757
  15. package/dist/cli.cjs.map +1 -1
  16. package/dist/cli.js +161 -2724
  17. package/dist/cli.js.map +1 -1
  18. package/dist/compiler/compiler.d.ts +2 -0
  19. package/dist/compiler/compiler.d.ts.map +1 -1
  20. package/dist/index.cjs +8 -2777
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.js +15 -2738
  23. package/dist/index.js.map +1 -1
  24. package/dist/plugins/body-fallback/constants/metadata-storage.d.ts +1 -0
  25. package/dist/plugins/body-fallback/constants/metadata-storage.d.ts.map +1 -1
  26. package/dist/plugins/body-fallback/index.d.ts.map +1 -1
  27. package/dist/plugins/chinese-to-pinyin/chinese-to-pinyin.plugin.d.ts.map +1 -1
  28. package/dist/plugins/chinese-to-pinyin/constants/metadata-storage.d.ts +1 -0
  29. package/dist/plugins/chinese-to-pinyin/constants/metadata-storage.d.ts.map +1 -1
  30. package/dist/plugins/download-http-file/constants/metadata-storage.d.ts +1 -0
  31. package/dist/plugins/download-http-file/constants/metadata-storage.d.ts.map +1 -1
  32. package/dist/plugins/download-http-file/download-http-file.plugin.d.ts.map +1 -1
  33. package/dist/plugins/download-local-file/constants/metadata-storage.d.ts +1 -0
  34. package/dist/plugins/download-local-file/constants/metadata-storage.d.ts.map +1 -1
  35. package/dist/plugins/download-local-file/download-local-file.plugin.d.ts.map +1 -1
  36. package/dist/plugins/eslint/constants/metadata-storage.d.ts +1 -0
  37. package/dist/plugins/eslint/constants/metadata-storage.d.ts.map +1 -1
  38. package/dist/plugins/eslint/eslint.plugin.d.ts.map +1 -1
  39. package/dist/plugins/generate-declaration/constants/metadata-storage.d.ts +2 -1
  40. package/dist/plugins/generate-declaration/constants/metadata-storage.d.ts.map +1 -1
  41. package/dist/plugins/generate-declaration/generate-declaration.plugin.d.ts.map +1 -1
  42. package/dist/plugins/generate-micro-function/constants/metadata-storage.d.ts +1 -0
  43. package/dist/plugins/generate-micro-function/constants/metadata-storage.d.ts.map +1 -1
  44. package/dist/plugins/generate-micro-function/generate-micro-function.plugin.d.ts.map +1 -1
  45. package/dist/plugins/generate-nestjs-module/constants/metadata-storage.d.ts +1 -0
  46. package/dist/plugins/generate-nestjs-module/constants/metadata-storage.d.ts.map +1 -1
  47. package/dist/plugins/generate-nestjs-module/generate-nestjs-module.d.ts.map +1 -1
  48. package/dist/plugins/index.d.ts +1 -0
  49. package/dist/plugins/index.d.ts.map +1 -1
  50. package/dist/plugins/prettier/constants/metadata-storage.d.ts +1 -0
  51. package/dist/plugins/prettier/constants/metadata-storage.d.ts.map +1 -1
  52. package/dist/plugins/prettier/prettier.plugin.d.ts.map +1 -1
  53. package/dist/plugins/shaking/constants/metadata-storage.d.ts +1 -0
  54. package/dist/plugins/shaking/constants/metadata-storage.d.ts.map +1 -1
  55. package/dist/plugins/shaking/shaking.plugin.d.ts.map +1 -1
  56. package/dist/plugins/terminal-select/constants/metadata-storage.d.ts +1 -0
  57. package/dist/plugins/terminal-select/constants/metadata-storage.d.ts.map +1 -1
  58. package/dist/plugins/terminal-select/terminal-select.plugin.d.ts.map +1 -1
  59. package/dist/plugins/use-valibot/constants/index.d.ts +2 -0
  60. package/dist/plugins/use-valibot/constants/index.d.ts.map +1 -0
  61. package/dist/plugins/use-valibot/constants/metadata-storage.d.ts +6 -0
  62. package/dist/plugins/use-valibot/constants/metadata-storage.d.ts.map +1 -0
  63. package/dist/plugins/use-valibot/index.d.ts +3 -0
  64. package/dist/plugins/use-valibot/index.d.ts.map +1 -0
  65. package/dist/plugins/use-valibot/use-valibot.plugin.d.ts +12 -0
  66. package/dist/plugins/use-valibot/use-valibot.plugin.d.ts.map +1 -0
  67. package/dist/plugins.cjs +3 -2532
  68. package/dist/plugins.cjs.map +1 -1
  69. package/dist/plugins.js +31 -2500
  70. package/dist/plugins.js.map +1 -1
  71. package/dist/transformers/json-schema/json-schema.transformer.d.ts +2 -0
  72. package/dist/transformers/json-schema/json-schema.transformer.d.ts.map +1 -1
  73. package/dist/transformers/json-schema/valibot.renderer.d.ts +26 -0
  74. package/dist/transformers/json-schema/valibot.renderer.d.ts.map +1 -0
  75. package/dist/transformers/schema-definition/schema-definition.transformer.d.ts +5 -0
  76. package/dist/transformers/schema-definition/schema-definition.transformer.d.ts.map +1 -1
  77. package/dist/translators.cjs +8 -2047
  78. package/dist/translators.cjs.map +1 -1
  79. package/dist/translators.js +7 -2008
  80. package/dist/translators.js.map +1 -1
  81. package/dist/utils/scan-generated-files.d.ts +15 -0
  82. package/dist/utils/scan-generated-files.d.ts.map +1 -0
  83. package/package.json +3 -3
package/dist/cli.js CHANGED
@@ -1,2748 +1,77 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ Compiler
4
+ } from "./chunk-XRZLO2PB.js";
5
+ import "./chunk-HN7ZZFKC.js";
6
+ import {
7
+ SupportedMethods,
8
+ logger
9
+ } from "./chunk-DZ2SC5HL.js";
2
10
 
3
11
  // src/cli.ts
12
+ import * as path2 from "path";
4
13
  import semver from "semver";
5
14
  import { Argument, Command, Option } from "commander";
6
15
 
7
- // src/constants/supported-methods.ts
8
- var SupportedMethods = [
9
- "get",
10
- "post",
11
- "put",
12
- "delete",
13
- "patch",
14
- "head",
15
- "options"
16
- ];
17
-
18
- // src/utils/logger.ts
19
- import chalk from "chalk";
20
- var logger = {
21
- log: (str) => console.log(chalk.green(str)),
22
- warn: (str) => console.warn(chalk.yellow(str)),
23
- error: (str) => console.error(chalk.red(str))
24
- };
25
-
26
- // src/compiler/compiler.ts
27
- import { Listr } from "listr2";
28
- import { AsyncParallelHook, AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } from "tapable";
29
-
30
- // src/compiler/tasks/setup/index.ts
31
- import fs4 from "fs-extra";
32
- import path10 from "path";
33
- import { cosmiconfig } from "cosmiconfig";
34
-
35
- // src/utils/ignore-matcher.ts
36
- import * as R from "ramda";
16
+ // src/utils/scan-generated-files.ts
17
+ import * as path from "path";
37
18
  import fs from "fs-extra";
38
- var IgnoreMatcher = class _IgnoreMatcher {
39
- rules;
40
- constructor(rules) {
41
- this.rules = rules;
42
- }
43
- static async read(filepath) {
44
- let content = await fs.readFile(filepath, "utf-8");
45
- content = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/#.*$/gm, "").replace(/\n+/g, "\n").trim();
46
- let rules = content.split("\n").map((line) => line.trim()).filter((line) => line.length > 0).map((line) => {
47
- const matched = line.match(/^(!)?\s*([^\s/]+)\s+([^\s/]+)\s+([^\s]+)$/);
48
- if (!matched) throw new Error(`Invalid ignore rule: "${line}"`);
49
- const [, flag, moduleName, operationMethod, operationPathname] = matched;
50
- return {
51
- persist: true,
52
- ignore: !flag,
53
- moduleName,
54
- operationMethod: operationMethod.toLowerCase(),
55
- operationPathname
56
- };
57
- });
58
- rules = R.sortBy(
59
- R.prop("ignore"),
60
- rules
61
- );
62
- rules = R.uniqWith(
63
- (a, b) => a.moduleName === b.moduleName && a.operationMethod === b.operationMethod && a.operationPathname === b.operationPathname,
64
- rules
65
- );
66
- return new _IgnoreMatcher(rules);
67
- }
68
- async write(filepath) {
69
- const ruleGroups = R.compose(
70
- R.groupBy((rule) => rule.moduleName),
71
- R.reverse,
72
- R.uniqWith(
73
- (a, b) => a.moduleName === b.moduleName && a.operationMethod === b.operationMethod && a.operationPathname === b.operationPathname
74
- ),
75
- R.filter((rule) => rule.persist)
76
- )(this.rules);
77
- const content = Object.entries(ruleGroups).sort((a, b) => {
78
- const aModuleName = a[0];
79
- const bModuleName = b[0];
80
- if (aModuleName === "*") return -1;
81
- if (bModuleName === "*") return 1;
82
- return aModuleName.localeCompare(bModuleName);
83
- }).map(([, rules]) => (rules || []).sort((a, b) => {
84
- if (a.ignore !== b.ignore) return a.ignore ? -1 : 1;
85
- if (a.operationMethod === "*") return -1;
86
- if (b.operationMethod === "*") return 1;
87
- if (a.operationPathname === "*") return -1;
88
- if (b.operationPathname === "*") return 1;
89
- if (a.operationMethod !== b.operationMethod) return a.operationMethod.localeCompare(b.operationMethod);
90
- if (a.operationPathname !== b.operationPathname) return a.operationPathname.localeCompare(b.operationPathname);
91
- return 0;
92
- }).map((rule) => `${rule.ignore ? "" : "! "}${rule.moduleName} ${rule.operationMethod.toUpperCase()} ${rule.operationPathname}`).join("\n")).join("\n\n");
93
- await fs.writeFile(filepath, content, "utf-8");
94
- }
95
- append(rule) {
96
- this.rules.unshift(rule);
97
- }
98
- // if operation is ignored, return true
99
- isOperationIgnored(operationDefinition) {
100
- const moduleName = operationDefinition.module.name;
101
- const operationMethod = operationDefinition.method.toLowerCase();
102
- const operationPathname = operationDefinition.pathname;
103
- for (const rule of this.rules) {
104
- if (rule.moduleName !== "*" && rule.moduleName !== moduleName) continue;
105
- if (rule.operationMethod !== "*" && rule.operationMethod !== operationMethod) continue;
106
- if (rule.operationPathname !== "*" && rule.operationPathname !== operationPathname) continue;
107
- return rule.ignore;
108
- }
109
- return false;
110
- }
111
- isModuleIgnored(moduleDefinition) {
112
- const moduleName = moduleDefinition.name;
113
- for (const rule of this.rules) {
114
- if (!rule.ignore) {
115
- if (rule.moduleName === "*" || rule.moduleName === moduleName) return false;
116
- continue;
117
- }
118
- if (rule.operationMethod !== "*") continue;
119
- if (rule.operationPathname !== "*") continue;
120
- if (rule.moduleName === "*" || rule.moduleName === moduleName) return true;
121
- }
122
- return false;
123
- }
124
- };
125
-
126
- // src/compiler/tasks/setup/utils/find-nearest-package-json.ts
127
- import fs2 from "fs";
128
- import path from "path";
129
- function findNearestPackageJson(startDir = process.cwd()) {
130
- let dir = startDir;
131
- while (true) {
132
- const pkgPath = path.join(dir, "package.json");
133
- if (fs2.existsSync(pkgPath)) {
134
- const json = JSON.parse(fs2.readFileSync(pkgPath, "utf8"));
135
- return { json, path: pkgPath };
136
- }
137
- const parent = path.dirname(dir);
138
- if (parent === dir) break;
139
- dir = parent;
140
- }
141
- return null;
142
- }
143
-
144
- // src/compiler/tasks/setup/utils/get-project-module-system.ts
145
- function getProjectModuleSystem(pkgInfo) {
146
- if (!pkgInfo?.json) return "cjs";
147
- const { json } = pkgInfo;
148
- if (json.type === "module") return "esm";
149
- return "cjs";
150
- }
151
-
152
- // src/compiler/tasks/setup/utils/parse-runtime-config.ts
153
- import { Value } from "@sinclair/typebox/value";
154
-
155
- // src/types/address.ts
156
- import { Type } from "@sinclair/typebox";
157
- var Address = Type.Object({
158
- url: Type.String(),
159
- headers: Type.Optional(Type.Record(Type.String(), Type.String(), { default: {} })),
160
- encoding: Type.Optional(
161
- Type.Union([
162
- Type.Literal("utf8"),
163
- Type.Literal("ascii")
164
- ], { default: "utf8" })
165
- )
166
- });
167
-
168
- // src/types/runtime-config.ts
169
- import * as R2 from "ramda";
170
- import { Type as Type2 } from "@sinclair/typebox";
171
-
172
- // src/constants/file-naming-style.ts
173
- var FileNamingStyle = /* @__PURE__ */ ((FileNamingStyle2) => {
174
- FileNamingStyle2["camelCase"] = "camelCase";
175
- FileNamingStyle2["capitalCase"] = "capitalCase";
176
- FileNamingStyle2["constantCase"] = "constantCase";
177
- FileNamingStyle2["dotCase"] = "dotCase";
178
- FileNamingStyle2["headerCase"] = "headerCase";
179
- FileNamingStyle2["noCase"] = "noCase";
180
- FileNamingStyle2["paramCase"] = "paramCase";
181
- FileNamingStyle2["pascalCase"] = "pascalCase";
182
- FileNamingStyle2["pathCase"] = "pathCase";
183
- FileNamingStyle2["sentenceCase"] = "sentenceCase";
184
- FileNamingStyle2["snakeCase"] = "snakeCase";
185
- return FileNamingStyle2;
186
- })(FileNamingStyle || {});
187
-
188
- // src/utils/is-valid-url.ts
189
- var URL_REGEX = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/(?:[^\s@]+@)?[^\s/:?#]*(?::\d+)?(?:\/[^\s?#]*)?(?:\?[^\s#]*)?(?:#[^\s]*)?$/;
190
- function isValidURL(url) {
191
- return URL_REGEX.test(url);
192
- }
193
-
194
- // src/types/runtime-config.ts
195
- var Modules = Type2.Transform(
196
- Type2.Record(
197
- Type2.String(),
198
- Type2.Union([Type2.String(), Address])
199
- )
200
- ).Decode((value) => {
201
- const keys2 = Object.keys(value);
202
- for (const key of keys2) {
203
- if (!/^[A-Za-z_][A-Za-z0-9_$]*$/.test(key)) {
204
- throw new Error(`Module name "${key}" is not valid. It must start with a letter or underscore, and can only contain letters, numbers, and underscores.`);
205
- }
206
- }
207
- const keysGroupByLowerCase = R2.groupBy(R2.toLower, keys2);
208
- for (const groupKey in keysGroupByLowerCase) {
209
- const keys3 = keysGroupByLowerCase[groupKey] || [];
210
- if (keys3.length > 1) {
211
- throw new Error(`Module names ${keys3.map((name) => `"${name}"`).join(", ")} are case-insensitively duplicated.`);
212
- }
213
- }
214
- for (const key in value) {
215
- const url = typeof value[key] === "string" ? value[key] : value[key].url;
216
- if (isValidURL(url)) continue;
217
- throw new Error(`The ${JSON.stringify(url)} of module "${key}" is not a valid URL.`);
218
- }
219
- return R2.map(
220
- (item) => typeof item !== "string" ? item : { url: item, headers: {}, encoding: "utf8" },
221
- value
222
- );
223
- }).Encode((value) => value);
224
- var RawConfig = Type2.Object({
225
- /**
226
- * Whether to generate ES Module code
227
- *
228
- * If not specified, the module system will be inferred from the nearest package.json "type" field
229
- * or defaults to "cjs" if no package.json is found.
230
- */
231
- esm: Type2.Optional(Type2.Boolean({ default: false })),
232
- /**
233
- * Output directory for generated files
234
- */
235
- outdir: Type2.String({ default: `${process.cwd()}/api` }),
236
- /**
237
- * File naming style for generated files
238
- */
239
- fileNamingStyle: Type2.Enum(FileNamingStyle, { default: "snakeCase" /* snakeCase */ }),
240
- /**
241
- * OpenAPI/Swagger document sources
242
- *
243
- * A map of module names to their document URLs or Address objects.
244
- * The module name must be a valid JavaScript identifier.
245
- */
246
- modules: Modules,
247
- /**
248
- * Enable debug mode to output detailed logs during compilation
249
- */
250
- debug: Type2.Optional(Type2.Boolean({ default: false })),
251
- /**
252
- * Whether to tolerate wrong openapi/swagger structure
253
- */
254
- tolerant: Type2.Optional(Type2.Boolean({ default: false })),
255
- /**
256
- * Translators to transform generated code
257
- *
258
- * Used to customize the code generation process for different frameworks or patterns.
259
- * Can be a single translator or an array of translators.
260
- */
261
- translators: Type2.Optional(
262
- Type2.Transform(
263
- Type2.Union([
264
- Type2.Unsafe(Type2.Any()),
265
- Type2.Array(Type2.Unsafe(Type2.Any()))
266
- ], { default: [] })
267
- ).Decode((value) => {
268
- if (value === void 0) return [];
269
- if (Array.isArray(value)) return value;
270
- return [value];
271
- }).Encode((value) => value)
272
- ),
273
- /**
274
- * Plugins to extend code generation functionality
275
- *
276
- * An array of plugin instances that can hook into various stages of the compilation process,
277
- * such as code transformation, formatting, linting, or custom file generation.
278
- */
279
- plugins: Type2.Optional(Type2.Array(Type2.Unsafe(Type2.Any()), { default: [] }))
280
- });
281
-
282
- // src/compiler/tasks/setup/utils/parse-runtime-config.ts
283
- function parseRuntimeConfig(data) {
284
- try {
285
- const originalPlugins = typeof data === "object" && data !== null && "plugins" in data ? data.plugins : void 0;
286
- const originTranslators = typeof data === "object" && data !== null && "translators" in data ? data.translators : void 0;
287
- const parsed = Value.Parse(RawConfig, data);
288
- if (originalPlugins !== void 0) {
289
- parsed.plugins = originalPlugins;
290
- }
291
- if (originTranslators !== void 0) {
292
- parsed.translators = originTranslators;
293
- }
294
- return parsed;
295
- } catch (error) {
296
- if (error instanceof Error) {
297
- error.message = `Invalid Config: ${error.message}`;
298
- }
299
- throw error;
300
- }
301
- }
302
-
303
- // src/plugins/eslint/eslint.plugin.ts
304
- import { ESLint } from "eslint";
305
-
306
- // src/plugins/prettier/prettier.plugin.ts
307
- import { exec } from "child_process";
308
- import { promisify } from "util";
309
- var execAsync = promisify(exec);
310
-
311
- // src/plugins/body-fallback/index.ts
312
- import * as R21 from "ramda";
313
-
314
- // src/utils/json-schema-utils/is-array.ts
315
- function isArray(schema) {
316
- return schema.type === "array";
317
- }
318
-
319
- // src/utils/json-schema-utils/is-mixed.ts
320
- function isMixed(schema) {
321
- return Array.isArray(schema.type);
322
- }
323
-
324
- // src/utils/json-schema-utils/is-non-array.ts
325
- function isNonArray(schema) {
326
- return typeof schema.type === "string" && schema.type !== "array";
327
- }
328
-
329
- // src/utils/json-schema-utils/is-ref.ts
330
- function isRef(schema) {
331
- return "$ref" in schema;
332
- }
333
-
334
- // src/utils/json-schema-utils/index.ts
335
- var JsonSchemaUtils = class {
336
- static isRef = isRef;
337
- static isArray = isArray;
338
- static isNonArray = isNonArray;
339
- static isMixed = isMixed;
340
- };
341
-
342
- // src/plugins/generate-micro-function/generate-micro-function.plugin.ts
343
- import { AsyncSeriesWaterfallHook as AsyncSeriesWaterfallHook2 } from "tapable";
344
-
345
- // src/plugins/generate-micro-function/constants/metadata-storage.ts
346
- var MetadataStorage3 = /* @__PURE__ */ new WeakMap();
347
-
348
- // src/plugins/generate-micro-function/generators/micro_function/micro-function.generator.ts
349
- import * as R20 from "ramda";
350
- import * as path8 from "path";
351
- import * as changeCase6 from "change-case";
352
-
353
- // src/models/artifact.ts
354
- import * as path2 from "path";
355
-
356
- // src/models/anchor.ts
357
- var AnchorBlock = class {
358
- constructor(artifact) {
359
- this.artifact = artifact;
360
- }
361
- /**
362
- * Append content to the end of the anchor block.
363
- */
364
- append(anchorName, content) {
365
- const lines = this.artifact.content.split("\n");
366
- const anchor = `@anchor:${anchorName}:end`;
367
- const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
368
- if (anchorIndex === -1) {
369
- throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
370
- }
371
- lines.splice(anchorIndex, 0, content);
372
- this.artifact.content = lines.join("\n");
373
- }
374
- prepend(anchorName, content) {
375
- const lines = this.artifact.content.split("\n");
376
- const anchor = `@anchor:${anchorName}:start`;
377
- const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
378
- if (anchorIndex === -1) {
379
- throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
380
- }
381
- lines.splice(anchorIndex + 1, 0, content);
382
- this.artifact.content = lines.join("\n");
383
- }
384
- replace(anchorName, content) {
385
- const lines = this.artifact.content.split("\n");
386
- const startIndex = lines.findIndex((line) => line.includes(`/* @anchor:${anchorName}:start */`));
387
- const endIndex = lines.findIndex((line) => line.includes(`/* @anchor:${anchorName}:end */`));
388
- if (startIndex === -1 || endIndex === -1 || endIndex <= startIndex) {
389
- throw new Error(`"@anchor:${anchorName}:start" or "@anchor:${anchorName}:end" not found in artifact "${this.artifact.filepath}".`);
390
- }
391
- lines.splice(startIndex + 1, endIndex - startIndex - 1, content);
392
- this.artifact.content = lines.join("\n");
393
- }
394
- };
395
- var Anchor = class {
396
- constructor(artifact) {
397
- this.artifact = artifact;
398
- this.block = new AnchorBlock(artifact);
399
- }
400
- block;
401
- append(anchorName, content) {
402
- const lines = this.artifact.content.split("\n");
403
- const anchor = `@anchor:${anchorName}`;
404
- const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
405
- if (anchorIndex === -1) {
406
- throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
407
- }
408
- lines.splice(anchorIndex + 1, 0, content);
409
- this.artifact.content = lines.join("\n");
410
- }
411
- prepend(anchorName, content) {
412
- const lines = this.artifact.content.split("\n");
413
- const anchor = `@anchor:${anchorName}`;
414
- const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
415
- if (anchorIndex === -1) {
416
- throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
417
- }
418
- lines.splice(anchorIndex, 0, content);
419
- this.artifact.content = lines.join("\n");
420
- }
421
- };
422
-
423
- // src/models/artifact.ts
424
- var HeaderComment = [
425
- "// Code generated by keq-cli. DO NOT EDIT.",
426
- "// Code generated by keq-cli. DO NOT EDIT.",
427
- "// Code generated by keq-cli. DO NOT EDIT.",
428
- "",
429
- ""
430
- ].join("\n");
431
- var Artifact = class {
432
- id;
433
- filepath;
434
- content;
435
- extensionName;
436
- anchor = new Anchor(this);
437
- constructor(options) {
438
- this.id = options.id;
439
- this.filepath = options.filepath;
440
- this.extensionName = options.extensionName || path2.extname(options.filepath);
441
- this.content = options.content;
442
- }
443
- get dirname() {
444
- return path2.dirname(this.filepath);
445
- }
446
- renderer() {
447
- return `${HeaderComment}${this.content}`;
448
- }
449
- };
450
-
451
- // src/models/api-document_v3_1.ts
452
- import * as R5 from "ramda";
453
-
454
- // src/models/module-definition.ts
455
- var ModuleDefinition = class _ModuleDefinition {
456
- name;
457
- address;
458
- constructor(name, address) {
459
- this.name = name;
460
- if (typeof address === "string") {
461
- this.address = { url: address, headers: {}, encoding: "utf8" };
462
- } else {
463
- this.address = address;
464
- }
465
- }
466
- static unknown() {
467
- return new _ModuleDefinition("", { url: "", headers: {}, encoding: "utf8" });
468
- }
469
- };
470
-
471
- // src/models/operation-definition.ts
472
- import * as R4 from "ramda";
473
-
474
- // src/utils/is-keywords.ts
475
- var keywords = [
476
- "break",
477
- "case",
478
- "catch",
479
- "continue",
480
- "default",
481
- "delete",
482
- "do",
483
- "else",
484
- "finally",
485
- "for",
486
- "function",
487
- "if",
488
- "in",
489
- "instanceof",
490
- "new",
491
- "return",
492
- "switch",
493
- "this",
494
- "throw",
495
- "try",
496
- "typeof",
497
- "var",
498
- "void",
499
- "while",
500
- "with"
501
- ];
502
- function isKeywords(str) {
503
- return keywords.includes(str);
504
- }
505
-
506
- // src/utils/is-reserved-word.ts
507
- var reservedWords = [
508
- "abstract",
509
- "boolean",
510
- "byte",
511
- "char",
512
- "class",
513
- "const",
514
- "debugger",
515
- "double",
516
- "enum",
517
- "export",
518
- "extends",
519
- "final",
520
- "float",
521
- "goto",
522
- "implements",
523
- "import",
524
- "int",
525
- "interface",
526
- "long",
527
- "native",
528
- "package",
529
- "private",
530
- "protected",
531
- "public",
532
- "short",
533
- "static",
534
- "super",
535
- "synchronized",
536
- "throws",
537
- "transient",
538
- "volatile"
539
- ];
540
- function isReservedWord(str) {
541
- return reservedWords.includes(str);
542
- }
543
-
544
- // src/models/operation-definition.ts
545
- import { JSONPath as JSONPath2 } from "jsonpath-plus";
546
-
547
- // src/models/schema-definition.ts
548
- import * as R3 from "ramda";
549
- import { JSONPath } from "jsonpath-plus";
550
- var SchemaDefinition = class _SchemaDefinition {
551
- name;
552
- schema;
553
- module;
554
- document;
555
- get id() {
556
- return `${this.module.address}#/components/schemas/${this.name}`;
557
- }
558
- constructor(args) {
559
- this.module = args.module;
560
- this.name = args.name;
561
- this.schema = args.schema;
562
- this.document = args.document;
563
- }
564
- getDependencies() {
565
- const refs = R3.uniq(JSONPath({
566
- path: "$..*['$ref']",
567
- json: this.schema
568
- }));
569
- return refs.filter((ref) => typeof ref === "string" && !!ref.trim()).map((ref) => {
570
- const definition = this.document.dereference(ref);
571
- if (definition) return definition;
572
- return _SchemaDefinition.unknown();
573
- });
574
- }
575
- static unknown() {
576
- return new _SchemaDefinition({
577
- name: "",
578
- schema: {},
579
- module: ModuleDefinition.unknown(),
580
- document: ApiDocumentV3_1.unknown()
581
- });
582
- }
583
- static isUnknown(definition) {
584
- return definition.name === "";
585
- }
586
- };
587
-
588
- // src/models/operation-definition.ts
589
- var OperationDefinition = class {
590
- module;
591
- operationId;
592
- method;
593
- pathname;
594
- operation;
595
- document;
596
- get id() {
597
- return `${this.module.address}#/paths/${this.pathname}/${this.method}`;
598
- }
599
- constructor(args) {
600
- this.module = args.module;
601
- this.method = args.method.toLowerCase();
602
- this.pathname = args.pathname;
603
- this.document = args.document;
604
- this.operationId = this.formatOperationId(args.method, args.pathname, args.operation);
605
- this.operation = {
606
- ...args.operation,
607
- operationId: this.operationId
608
- };
609
- }
610
- formatOperationId(method, pathname, operation) {
611
- const operationId = operation.operationId;
612
- if (operationId && operationId !== "index" && !isKeywords(operationId) && !isReservedWord(operationId)) {
613
- return operationId;
614
- }
615
- return `${method}_${pathname}`.replace(/\//g, "_").replace(/-/g, "_").replace(/:/g, "$$").replace(/{(.+)}/, "$$$1");
616
- }
617
- getDependencies() {
618
- const refs = R4.uniq([
619
- ...JSONPath2({
620
- path: "$.requestBody.content..schema..$ref",
621
- json: this.operation
622
- }),
623
- ...JSONPath2({
624
- path: "$.responses..content..schema..$ref",
625
- json: this.operation
626
- }),
627
- ...JSONPath2({
628
- path: "$.parameters..schema..$ref",
629
- json: this.operation
630
- })
631
- ]);
632
- const dependencies = refs.filter((ref) => typeof ref === "string" && ref).map((ref) => {
633
- const schemaDefinition = this.document.dereference(ref);
634
- if (schemaDefinition) return schemaDefinition;
635
- return SchemaDefinition.unknown();
636
- });
637
- return dependencies;
638
- }
639
- };
640
-
641
- // src/models/api-document_v3_1.ts
642
- var ApiDocumentV3_1 = class _ApiDocumentV3_1 {
643
- module;
644
- specification;
645
- constructor(specification, module) {
646
- this.module = module;
647
- this.specification = specification;
648
- }
649
- get schemas() {
650
- const module = this.module;
651
- return Object.entries(this.specification.components?.schemas || {}).map(([name, schema]) => new SchemaDefinition({
652
- name,
653
- schema,
654
- module,
655
- document: this
656
- }));
657
- }
658
- get operations() {
659
- const module = this.module;
660
- return Object.entries(this.specification.paths || {}).flatMap(([pathname, pathItem]) => Object.entries(pathItem || {}).filter(([method]) => SupportedMethods.includes(method.toLowerCase())).map(([method, operation]) => new OperationDefinition({
661
- method,
662
- pathname,
663
- operation,
664
- module,
665
- document: this
666
- })));
667
- }
668
- isEmpty() {
669
- return R5.isEmpty(this.specification.paths);
670
- }
671
- dereference($ref) {
672
- if ($ref.startsWith("#/")) {
673
- return this.schemas.find((schema) => schema.id.endsWith($ref));
674
- }
675
- logger.warn(`The $ref(${$ref}) is not defined in ${this.module.name} openapi/swagger.`);
676
- }
677
- isRefDefined($ref) {
678
- if ($ref.startsWith("#/")) {
679
- const path12 = $ref.replace("#/", "").split("/");
680
- return R5.path(path12, this.specification) !== void 0;
681
- }
682
- return false;
683
- }
684
- static unknown() {
685
- return new _ApiDocumentV3_1({}, ModuleDefinition.unknown());
686
- }
687
- };
688
-
689
- // src/models/asset.ts
690
- var Asset = class {
691
- path;
692
- constructor(path12) {
693
- this.path = path12;
694
- }
695
- };
696
-
697
- // src/plugins/generate-declaration/generate-declaration.plugin.ts
698
- import { AsyncSeriesWaterfallHook } from "tapable";
699
-
700
- // src/plugins/generate-declaration/generators/operation-declaration/operation.generator.ts
701
- import * as path7 from "path";
702
- import * as changeCase5 from "change-case";
703
-
704
- // src/transformers/json-schema/comment.renderer.ts
705
- var CommentRenderer = class {
706
- constructor(schema) {
707
- this.schema = schema;
708
- }
709
- render() {
710
- const schema = this.schema;
711
- const lines = ["/**"];
712
- if (schema.description) {
713
- const description = schema.description.replace("*/", "*\\/");
714
- lines.push(...description.split("\n").map((line) => ` * ${line}`));
715
- }
716
- if (schema.deprecated) {
717
- lines.push(" * @deprecated");
718
- }
719
- if (schema.readOnly) {
720
- lines.push(" * @readonly");
721
- }
722
- if (schema.format) {
723
- lines.push(` * @format ${schema.format}`);
724
- }
725
- lines.push(" */");
726
- if (lines.length === 2) return "";
727
- return lines.join("\n");
728
- }
729
- };
730
-
731
- // src/transformers/json-schema/declaration.renderer.ts
732
- import * as R7 from "ramda";
733
-
734
- // src/utils/indent.ts
735
- function indent(space, text) {
736
- if (text === "") return "";
737
- const indentation = " ".repeat(space);
738
- return text.split("\n").map((line) => line ? `${indentation}${line}` : line).join("\n");
739
- }
740
-
741
- // src/transformers/json-schema/reference.transformer.ts
742
- import * as R6 from "ramda";
743
- var ReferenceTransformer = class {
744
- static toDeclaration(schema, alias2 = R6.identity) {
745
- if (!schema.$ref || !schema.$ref.startsWith("#")) return `unknown /* ${schema.$ref.replace("*/", "*\\/")} */`;
746
- const parts = schema.$ref.split("/");
747
- return alias2(parts[parts.length - 1]) || "unknown";
748
- }
749
- };
750
-
751
- // src/transformers/json-schema/declaration.renderer.ts
752
- var DeclarationRenderer = class {
753
- constructor(schema, options = {}) {
754
- this.schema = schema;
755
- this.options = options;
756
- }
757
- render() {
758
- return this.renderSchema(this.schema);
759
- }
760
- renderSchema(schema) {
761
- if (typeof schema === "boolean") return "unknown";
762
- if (JsonSchemaUtils.isRef(schema)) return this.renderReference(schema);
763
- if (JsonSchemaUtils.isMixed(schema)) return this.renderMixed(schema);
764
- if (JsonSchemaUtils.isArray(schema)) return this.renderArray(schema);
765
- if (schema.type === "object") return this.renderObject(schema);
766
- if (schema.enum) return this.renderEnum(schema);
767
- if (schema.oneOf) return this.renderOneOf(schema);
768
- if (schema.anyOf) return this.renderAnyOf(schema);
769
- if (schema.allOf) return this.renderAllOf(schema);
770
- if (schema.type === "string") return this.renderString(schema);
771
- if (schema.type === "number") return this.renderNumber(schema);
772
- if (schema.type === "boolean") return this.renderBoolean(schema);
773
- if (schema.type === "null") return this.renderNull(schema);
774
- if (schema.type === "integer") return this.renderInteger(schema);
775
- return "unknown";
776
- }
777
- renderMixed(schema) {
778
- if (Array.isArray(schema.type)) {
779
- schema.type.map((type) => ({ ...schema, type })).map((schema2) => this.renderSchema(schema2)).join(" | ");
780
- }
781
- return "unknown";
782
- }
783
- renderReference(schema) {
784
- if (!this.options.referenceTransformer) {
785
- return ReferenceTransformer.toDeclaration(schema);
786
- }
787
- return this.options.referenceTransformer(schema);
788
- }
789
- renderArray(schema) {
790
- if (schema.items && Array.isArray(schema.items)) {
791
- const items = schema.items.map((s) => this.renderSchema(s)).join(", ");
792
- return `[${items}]`;
793
- }
794
- if (schema.items && typeof schema.items === "object") {
795
- return `${this.renderSchema(schema.items)}[]`;
796
- }
797
- return "any[]";
798
- }
799
- renderObject(schema) {
800
- if ((!schema.properties || R7.isEmpty(schema.properties)) && (!schema.additionalProperties || R7.isEmpty(schema.additionalProperties))) {
801
- return "object";
802
- }
803
- const $properties = Object.entries(schema.properties || {}).map(([propertyName, propertySchema]) => {
804
- let $comment = new CommentRenderer(propertySchema).render();
805
- if ($comment) $comment += "\n";
806
- const $key = `"${propertyName}"${schema.required?.includes(propertyName) ? "" : "?"}`;
807
- const $value = this.renderSchema(propertySchema);
808
- return indent(2, `${$comment}${$key}: ${$value}`);
809
- });
810
- if (schema.additionalProperties) {
811
- const $value = schema.additionalProperties === true ? "any" : this.renderSchema(schema.additionalProperties);
812
- $properties.push(indent(2, `[key: string]: ${$value}`));
813
- }
814
- return [
815
- "{",
816
- ...$properties,
817
- "}"
818
- ].join("\n");
819
- }
820
- renderOneOf(schema) {
821
- if (!schema.oneOf) return "unknown";
822
- return schema.oneOf.map((s) => this.renderSchema(s)).join(" | ");
823
- }
824
- renderAnyOf(schema) {
825
- if (!schema.anyOf) return "unknown";
826
- return schema.anyOf.map((s) => this.renderSchema(s)).join(" | ");
827
- }
828
- renderAllOf(schema) {
829
- if (!schema.allOf) return "unknown";
830
- return schema.allOf.map((s) => this.renderSchema(s)).join(" & ");
831
- }
832
- renderEnum(schema) {
833
- if (!schema.enum) return "unknown";
834
- return schema.enum.map((v) => JSON.stringify(v)).join(" | ");
835
- }
836
- renderString(schema) {
837
- if (schema.contentMediaType === "application/octet-stream") return "Blob | Buffer";
838
- if (schema.format === "binary") return "Blob | Buffer";
839
- return "string";
840
- }
841
- renderNumber(schema) {
842
- return "number";
843
- }
844
- renderBoolean(schema) {
845
- return "boolean";
846
- }
847
- renderNull(schema) {
848
- return "null";
849
- }
850
- renderInteger(schema) {
851
- return "number";
852
- }
853
- };
854
-
855
- // src/transformers/json-schema/json-schema.transformer.ts
856
- var JsonSchemaTransformer = class {
857
- static toComment(schema) {
858
- return new CommentRenderer(schema).render();
859
- }
860
- static toDeclaration(schema, options) {
861
- return new DeclarationRenderer(schema, options).render();
862
- }
863
- };
864
-
865
- // src/transformers/schema-definition/schema-definition.transformer.ts
866
- import * as R8 from "ramda";
867
- var SchemaDefinitionTransformer = class {
868
- static toDeclaration(schemaDefinition, options) {
869
- const dependencies = schemaDefinition.getDependencies();
870
- let $dependencies = dependencies.filter((dep) => !SchemaDefinition.isUnknown(dep)).map((dep) => {
871
- const filepath = options.getDependentSchemaDefinitionFilepath(dep);
872
- return `import type { ${dep.name} } from "${filepath}"`;
873
- }).map((str) => str.replace(/ from "(\.\.?\/.+?)(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?"/, options.esm ? ' from "$1.js"' : ' from "$1"')).join("\n");
874
- if ($dependencies) $dependencies += "\n";
875
- let $comment = JsonSchemaTransformer.toComment(schemaDefinition.schema);
876
- if ($comment) $comment += "\n";
877
- if (typeof schemaDefinition.schema === "boolean") {
878
- return [
879
- "/* @anchor:file:start */",
880
- "",
881
- $dependencies,
882
- $comment || void 0,
883
- `type ${schemaDefinition.name} = unknown`,
884
- "",
885
- "/* @anchor:file:end */"
886
- ].filter(R8.isNotNil).join("\n");
887
- }
888
- if (JsonSchemaUtils.isNonArray(schemaDefinition.schema) && schemaDefinition.schema.type === "object") {
889
- const $schema = JsonSchemaTransformer.toDeclaration(schemaDefinition.schema);
890
- const $declaration = $schema.startsWith("{") ? `export interface ${schemaDefinition.name} ${$schema}` : `export type ${schemaDefinition.name} = ${$schema}`;
891
- return [
892
- "/* @anchor:file:start */",
893
- "",
894
- $dependencies,
895
- $comment || void 0,
896
- $declaration,
897
- "",
898
- "/* @anchor:file:end */"
899
- ].filter(R8.isNotNil).join("\n");
900
- }
901
- return [
902
- "/* @anchor:file:start */",
903
- "",
904
- $dependencies,
905
- $comment || void 0,
906
- `export type ${schemaDefinition.name} = ${JsonSchemaTransformer.toDeclaration(schemaDefinition.schema)}`,
907
- "",
908
- "/* @anchor:file:end */"
909
- ].filter(R8.isNotNil).join("\n");
910
- }
911
- };
912
-
913
- // src/transformers/operation-definition/comment.renderer.ts
914
- import * as R9 from "ramda";
915
- var CommentRenderer2 = class {
916
- constructor(operationDefinition) {
917
- this.operationDefinition = operationDefinition;
918
- }
919
- render() {
920
- const operation = this.operationDefinition.operation;
921
- if (!operation.summary && !operation.description) return "";
922
- const lines = ["/**"];
923
- if (operation.summary && typeof operation.summary === "string") {
924
- lines.push(` * ${R9.trim(operation.summary)}`);
925
- lines.push(" *");
926
- }
927
- if (operation.description && typeof operation.description === "string") {
928
- lines.push(` * @description ${R9.trim(operation.description)}`);
929
- }
930
- lines.push(" */");
931
- return lines.join("\n");
932
- }
933
- };
934
-
935
- // src/transformers/operation-definition/declaration.renderer.ts
936
- import * as R14 from "ramda";
937
-
938
- // src/transformers/operation-definition/utils/type-name-factory.ts
939
- import * as changeCase from "change-case";
940
- function typeNameFactory(operationDefinition) {
941
- const pascalCaseOperationId = changeCase.pascalCase(operationDefinition.operationId);
942
- return (name) => `${pascalCaseOperationId}${name}`;
943
- }
944
-
945
- // src/utils/openapi-utils/dereference.ts
946
- function dereference($ref, swagger) {
947
- let value;
948
- for (const key of $ref.split("/")) {
949
- if (key === "#") {
950
- value = swagger;
951
- } else {
952
- value = value[key];
953
- }
954
- if (!value) break;
955
- }
956
- return value;
957
- }
958
-
959
- // src/utils/openapi-utils/dereference-operation.ts
960
- import * as R12 from "ramda";
961
- import jsonpointer2 from "jsonpointer";
962
- import { JSONPath as JSONPath4 } from "jsonpath-plus";
963
-
964
- // src/utils/openapi-utils/remove-undefined-ref.ts
965
- import * as R11 from "ramda";
966
- import jsonpointer from "jsonpointer";
967
- import { JSONPath as JSONPath3 } from "jsonpath-plus";
968
-
969
- // src/utils/openapi-utils/is-ref-defined.ts
970
- import * as R10 from "ramda";
971
- function isRefDefined($ref, swagger) {
972
- if ($ref.startsWith("#/")) {
973
- const path12 = $ref.replace("#/", "").split("/");
974
- return R10.path(path12, swagger) !== void 0;
975
- }
976
- return false;
977
- }
978
-
979
- // src/utils/openapi-utils/remove-undefined-ref.ts
980
- function removeUndefinedRef(swagger) {
981
- const shadow = R11.clone(swagger);
982
- const matches = JSONPath3({
983
- path: "$..*['$ref']^",
984
- json: swagger,
985
- resultType: "all"
986
- });
987
- for (const match of matches) {
988
- if (match.value.$ref && !isRefDefined(match.value.$ref, swagger)) {
989
- jsonpointer.set(shadow, match.pointer, R11.omit(["$ref"], match.value));
990
- }
991
- }
992
- return shadow;
993
- }
994
-
995
- // src/utils/openapi-utils/dereference-operation.ts
996
- function dereferencePathObject(swagger) {
997
- const matches = JSONPath4({
998
- path: "$.paths.*.$ref^",
999
- json: swagger,
1000
- resultType: "all"
1001
- });
1002
- for (const match of matches) {
1003
- const value = dereference(match.value.$ref, swagger);
1004
- jsonpointer2.set(swagger, match.pointer, value);
1005
- }
1006
- }
1007
- function dereferenceRequestBody(swagger) {
1008
- const matches = JSONPath4({
1009
- path: "$.paths.*.*.requestBody.$ref^",
1010
- json: swagger,
1011
- resultType: "all"
1012
- });
1013
- for (const match of matches) {
1014
- const value = dereference(match.value.$ref, swagger);
1015
- jsonpointer2.set(swagger, match.pointer, value);
1016
- }
1017
- }
1018
- function dereferenceResponses(swagger) {
1019
- const matches = [
1020
- ...JSONPath4({
1021
- path: "$.paths.*.*.responses.*.$ref^",
1022
- json: swagger,
1023
- resultType: "all"
1024
- }),
1025
- ...JSONPath4({
1026
- path: "$.paths.*.*.responses.*.headers.*.$ref^",
1027
- json: swagger,
1028
- resultType: "all"
1029
- })
1030
- ];
1031
- for (const match of matches) {
1032
- const value = dereference(match.value.$ref, swagger);
1033
- jsonpointer2.set(swagger, match.pointer, value);
1034
- }
1035
- }
1036
- function dereferenceParameters(swagger) {
1037
- const matches = JSONPath4({
1038
- path: "$.paths.*.*.parameters.*.$ref^",
1039
- json: swagger,
1040
- resultType: "all"
1041
- });
1042
- for (const match of matches) {
1043
- const value = dereference(match.value.$ref, swagger);
1044
- jsonpointer2.set(swagger, match.pointer, value);
1045
- }
1046
- }
1047
- function dereferenceOperation(swagger) {
1048
- const shadow = R12.clone(swagger);
1049
- dereferencePathObject(shadow);
1050
- dereferenceRequestBody(shadow);
1051
- dereferenceResponses(shadow);
1052
- dereferenceParameters(shadow);
1053
- return removeUndefinedRef(shadow);
1054
- }
1055
-
1056
- // src/utils/openapi-utils/dereference-deep.ts
1057
- function dereferenceDeep($ref, swagger) {
1058
- const stack = [$ref];
1059
- let value;
1060
- while (true) {
1061
- const last2 = stack[stack.length - 1];
1062
- value = dereference(last2, swagger);
1063
- if (JsonSchemaUtils.isRef(value)) {
1064
- if (!stack.includes(value.$ref)) {
1065
- stack.push(value.$ref);
1066
- continue;
1067
- } else {
1068
- throw new Error(`Circular reference detected: ${stack.join(" -> ")} -> ${value.$ref}`);
1069
- }
1070
- }
1071
- break;
1072
- }
1073
- return value;
1074
- }
1075
-
1076
- // src/utils/openapi-utils/to-3_1.ts
1077
- import { upgrade } from "@scalar/openapi-parser";
1078
- function To3_1(openapi) {
1079
- const { specification } = upgrade(openapi);
1080
- return specification;
1081
- }
1082
-
1083
- // src/utils/openapi-utils/map-operation.ts
1084
- import * as R13 from "ramda";
1085
- function mapOperation(specification, mapper) {
1086
- const shadow = R13.clone(specification);
1087
- for (const [pathname, pathItem] of Object.entries(shadow.paths || {})) {
1088
- for (const m in pathItem) {
1089
- const method = m.toLowerCase();
1090
- if (!SupportedMethods.includes(method)) continue;
1091
- if (typeof pathItem[m] !== "object" || Array.isArray(pathItem[m]) || pathItem[m] === null) continue;
1092
- const operation = pathItem[m];
1093
- pathItem[m] = mapper(method, pathname, operation);
1094
- }
1095
- }
1096
- return shadow;
1097
- }
1098
-
1099
- // src/utils/openapi-utils/map-parameter.ts
1100
- function mapParameter(specification, mapper) {
1101
- return mapOperation(specification, (method, pathname, operation) => {
1102
- if (!operation.parameters) return operation;
1103
- operation.parameters = operation.parameters.map((parameter) => mapper(method, pathname, operation, parameter));
1104
- return operation;
1105
- });
1106
- }
1107
-
1108
- // src/utils/openapi-utils/index.ts
1109
- var OpenapiUtils = class {
1110
- static isRefDefined = isRefDefined;
1111
- static dereference = dereference;
1112
- static dereferenceDeep = dereferenceDeep;
1113
- static removeUndefinedRef = removeUndefinedRef;
1114
- static dereferenceOperation = dereferenceOperation;
1115
- static mapOperation = mapOperation;
1116
- static mapParameter = mapParameter;
1117
- // static updateOperationId = updateOperationId
1118
- static to3_1 = To3_1;
1119
- };
1120
-
1121
- // src/transformers/operation-definition/declaration.renderer.ts
1122
- var alias = (name) => `${name}Schema`;
1123
- var DeclarationRenderer2 = class {
1124
- constructor(operationDefinition, options) {
1125
- this.operationDefinition = operationDefinition;
1126
- this.options = options;
1127
- this.typeName = typeNameFactory(operationDefinition);
1128
- }
1129
- typeName;
1130
- renderResponseBodies(operation, options) {
1131
- if (!operation.responses || R14.isEmpty(operation.responses)) {
1132
- return `export interface ${this.typeName("ResponseBodies")} {}`;
1133
- }
1134
- const $responses = Object.entries(operation.responses).map(([statusCode, response]) => {
1135
- if (!JsonSchemaUtils.isRef(response)) {
1136
- const $value = Object.entries(response.content || {}).map(([mediaType, mediaTypeObject]) => [mediaType, mediaTypeObject.schema]).map(([mediaType, schema]) => {
1137
- if (mediaType.includes("text/event-stream")) return "ReadableStream<ServerSentEvent>";
1138
- if (mediaType.includes("multipart/form-data")) return "FormData";
1139
- if (!schema) return "unknown";
1140
- return JsonSchemaTransformer.toDeclaration(schema, options);
1141
- }).join(" | ");
1142
- return indent(2, `${statusCode}: ${$value || "void"}`);
1143
- }
1144
- }).join("\n");
1145
- return [
1146
- `export interface ${this.typeName("ResponseBodies")} {`,
1147
- $responses,
1148
- "}"
1149
- ].join("\n");
1150
- }
1151
- renderRequestBodies(operation, options) {
1152
- let $requestBodies = `export interface ${this.typeName("RequestBodies")} {}`;
1153
- if (operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody)) {
1154
- const $mediaTypes = Object.entries(operation.requestBody.content || {}).map(([mediaType, mediaTypeObject]) => [mediaType, mediaTypeObject.schema]).map(([mediaType, schema]) => {
1155
- if (!schema) return `${JSON.stringify(mediaType)}: unknown`;
1156
- return `${JSON.stringify(mediaType)}: ${JsonSchemaTransformer.toDeclaration(schema, options)}`;
1157
- }).map((pair) => indent(2, pair));
1158
- $requestBodies = [
1159
- `export interface ${this.typeName("RequestBodies")} {`,
1160
- ...$mediaTypes,
1161
- "}"
1162
- ].join("\n");
1163
- }
1164
- return $requestBodies;
1165
- }
1166
- renderParameterBodies(operationDefinition, options) {
1167
- const { operation } = operationDefinition;
1168
- let parameterBodies = "";
1169
- if (operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody)) {
1170
- const $mediaTypes = Object.entries(operation.requestBody.content || {}).map(([mediaType, mediaTypeObject]) => [mediaType, mediaTypeObject.schema]).map(([mediaType, schemaOrRef]) => {
1171
- if (!schemaOrRef) return `${JSON.stringify(mediaType)}: unknown`;
1172
- const schema = JsonSchemaUtils.isRef(schemaOrRef) ? OpenapiUtils.dereferenceDeep(schemaOrRef.$ref, operationDefinition.document.specification) : schemaOrRef;
1173
- if (schema.type === "object" || schema.properties) {
1174
- return `${JSON.stringify(mediaType)}: ${JsonSchemaTransformer.toDeclaration(schemaOrRef, options)} & { [key: string]: any }`;
1175
- }
1176
- return `${JSON.stringify(mediaType)}: { [key: string]: any }`;
1177
- }).map((pair) => indent(2, pair));
1178
- parameterBodies = [
1179
- `interface ${this.typeName("ParameterBodies")} {`,
1180
- ...$mediaTypes,
1181
- "}",
1182
- ""
1183
- ].join("\n");
1184
- }
1185
- return parameterBodies;
1186
- }
1187
- renderRequestParameters(operation, options) {
1188
- const mediaTypes = operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody) ? Object.keys(operation.requestBody.content || {}) : [];
1189
- const base = `${this.typeName("RequestQuery")} & ${this.typeName("RouteParameters")} & ${this.typeName("RequestHeaders")}`;
1190
- if (mediaTypes.length === 1) {
1191
- return `export type ${this.typeName("RequestParameters")} = ${base} & ${this.typeName("RequestBodies")}[${JSON.stringify(mediaTypes[0])}]`;
1192
- }
1193
- if (mediaTypes.length > 1) {
1194
- const unions = mediaTypes.map((mediaType) => `(${base} & ${this.typeName("RequestBodies")}[${JSON.stringify(mediaType)}] & { "content-type": ${JSON.stringify(mediaType)} })`).join("\n| ");
1195
- return `export type ${this.typeName("RequestParameters")} = ${unions}`;
1196
- }
1197
- return `export type ${this.typeName("RequestParameters")} = ${base}`;
1198
- }
1199
- rendererParameters(name, parameters, options) {
1200
- if (parameters.length === 0) {
1201
- return `export type ${name} = {}`;
1202
- }
1203
- const $parameters = parameters.map((parameter) => {
1204
- const parameterName = `"${parameter.name}"`;
1205
- const $key = parameter.required ? parameterName : `${parameterName}?`;
1206
- const $value = JsonSchemaTransformer.toDeclaration(parameter.schema || { type: "any" }, options);
1207
- return indent(2, `${$key}: ${$value}`);
1208
- }).join("\n");
1209
- return [
1210
- `export type ${name} = {`,
1211
- $parameters,
1212
- "}"
1213
- ].filter(Boolean).join("\n");
1214
- }
1215
- renderDependencies() {
1216
- const schemaDefinitions = this.operationDefinition.getDependencies().filter((schemaDefinition) => !SchemaDefinition.isUnknown(schemaDefinition));
1217
- const $schemaDefinitions = schemaDefinitions.map((schemaDefinition) => {
1218
- const filepath = this.options.getDependentSchemaDefinitionFilepath(schemaDefinition);
1219
- const schemaName = schemaDefinition.name;
1220
- return `import type { ${schemaName} as ${alias(schemaName)} } from "${filepath}"`;
1221
- }).map((str) => str.replace(/ from "(\.\.?\/.+?)(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?"/, this.options.esm ? ' from "$1.js"' : ' from "$1"'));
1222
- return [
1223
- 'import type { KeqOperation, KeqPathParameterInit, KeqQueryInit, ServerSentEvent } from "keq"',
1224
- ...$schemaDefinitions
1225
- ].join("\n");
1226
- }
1227
- render() {
1228
- const { operation } = this.operationDefinition;
1229
- if (!operation.responses) return "";
1230
- const jsonSchemaDeclarationRendererOptions = {
1231
- referenceTransformer: (schema) => {
1232
- return ReferenceTransformer.toDeclaration(schema, alias);
1233
- }
1234
- };
1235
- const $dependencies = this.renderDependencies();
1236
- const $responseBodies = this.renderResponseBodies(operation, jsonSchemaDeclarationRendererOptions);
1237
- const $requestBodies = this.renderRequestBodies(operation, jsonSchemaDeclarationRendererOptions);
1238
- const $parameterBodies = this.renderParameterBodies(this.operationDefinition, jsonSchemaDeclarationRendererOptions);
1239
- const $requestParameters = this.renderRequestParameters(operation, jsonSchemaDeclarationRendererOptions);
1240
- const $requestQuery = this.rendererParameters(
1241
- `${this.typeName("RequestQuery")}`,
1242
- operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "query") || [],
1243
- jsonSchemaDeclarationRendererOptions
1244
- );
1245
- const $routeParameters = this.rendererParameters(
1246
- `${this.typeName("RouteParameters")}`,
1247
- operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "path") || [],
1248
- jsonSchemaDeclarationRendererOptions
1249
- );
1250
- const $requestHeaders = this.rendererParameters(
1251
- `${this.typeName("RequestHeaders")}`,
1252
- operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "header") || [],
1253
- jsonSchemaDeclarationRendererOptions
1254
- );
1255
- return [
1256
- "/* @anchor:file:start */",
1257
- "",
1258
- $dependencies,
1259
- "",
1260
- $responseBodies,
1261
- "",
1262
- $requestBodies,
1263
- "",
1264
- $requestQuery,
1265
- "",
1266
- $routeParameters,
1267
- "",
1268
- $requestHeaders,
1269
- "",
1270
- $parameterBodies || void 0,
1271
- $requestParameters,
1272
- "",
1273
- `export interface ${this.typeName("Operation")}<STATUS extends keyof ${this.typeName("ResponseBodies")}, CONTENT_TYPE extends ${$parameterBodies ? `keyof ${this.typeName("ParameterBodies")}` : "string"} > extends KeqOperation {`,
1274
- ` requestParams: ${this.typeName("RouteParameters")} & { [key: string]: KeqPathParameterInit }`,
1275
- ` requestQuery: ${this.typeName("RequestQuery")} & { [key: string]: KeqQueryInit }`,
1276
- ` requestHeaders: ${this.typeName("RequestHeaders")} & { [key: string]: string | number }`,
1277
- ` requestBody: ${$parameterBodies ? `${this.typeName("ParameterBodies")}[CONTENT_TYPE] | ` : "object | "}BodyInit`,
1278
- ` responseBody: ${this.typeName("ResponseBodies")}[STATUS]`,
1279
- "}",
1280
- "",
1281
- "/* @anchor:file:end */"
1282
- ].filter(R14.isNotNil).join("\n");
1283
- }
1284
- };
1285
-
1286
- // src/transformers/operation-definition/micro-function.renderer.ts
1287
- import * as R16 from "ramda";
1288
-
1289
- // src/exception.ts
1290
- import { CustomError } from "ts-custom-error";
1291
- import wrap from "word-wrap";
1292
- var Exception = class extends CustomError {
1293
- constructor(module, message) {
1294
- const moduleName = typeof module === "string" ? module : module.name;
1295
- const msg = wrap(message, { width: 60, indent: " " });
1296
- super(`${moduleName} module failed to compile:
1297
- ${msg}`);
1298
- Object.defineProperty(this, "name", { value: "KeqCLI_Exception" });
1299
- }
1300
- };
1301
-
1302
- // src/transformers/operation-definition/typescript-snippet.ts
1303
- import * as R15 from "ramda";
1304
-
1305
- // src/constants/qs-array-format.ts
1306
- var QsArrayFormat = /* @__PURE__ */ ((QsArrayFormat2) => {
1307
- QsArrayFormat2["brackets"] = "brackets";
1308
- QsArrayFormat2["indices"] = "indices";
1309
- QsArrayFormat2["repeat"] = "repeat";
1310
- QsArrayFormat2["comma"] = "comma";
1311
- QsArrayFormat2["space"] = "space";
1312
- QsArrayFormat2["pipe"] = "pipe";
1313
- return QsArrayFormat2;
1314
- })(QsArrayFormat || {});
1315
-
1316
- // src/transformers/operation-definition/typescript-snippet.ts
1317
- var OperationDefinitionSnippet = class {
1318
- constructor(operationDefinition, options) {
1319
- this.operationDefinition = operationDefinition;
1320
- this.options = options;
1321
- this.typeName = typeNameFactory(operationDefinition);
1322
- }
1323
- typeName;
1324
- getQsParameters(parameter) {
1325
- let arrayFormat;
1326
- let allowDots;
1327
- let indices;
1328
- const style = parameter.style || "form";
1329
- const explode = parameter.explode ?? true;
1330
- if ("x-qs-array-format" in parameter) {
1331
- arrayFormat = parameter["x-qs-array-format"];
1332
- } else {
1333
- if (style === "deepObject") {
1334
- arrayFormat = "brackets" /* brackets */;
1335
- } else if (explode) {
1336
- arrayFormat = "repeat" /* repeat */;
1337
- } else {
1338
- if (style === "form") {
1339
- arrayFormat = "comma" /* comma */;
1340
- } else if (style === "spaceDelimited") {
1341
- arrayFormat = "space" /* space */;
1342
- } else if (style === "pipeDelimited") {
1343
- arrayFormat = "pipe" /* pipe */;
1344
- }
1345
- }
1346
- }
1347
- if ("x-qs-allow-dots" in parameter) {
1348
- allowDots = Boolean(parameter["x-qs-allow-dots"]);
1349
- }
1350
- if ("x-qs-indices" in parameter) {
1351
- indices = Boolean(parameter["x-qs-indices"]);
1352
- }
1353
- if (arrayFormat || allowDots !== void 0 || indices !== void 0) {
1354
- return {
1355
- ...arrayFormat ? { arrayFormat } : {},
1356
- ...allowDots !== void 0 ? { allowDots } : {},
1357
- ...indices !== void 0 ? { indices } : {}
1358
- };
1359
- }
1360
- return void 0;
1361
- }
1362
- // render: "if (args && 'Authorization' in args) req.header('Authorization', args['Authorization'])"
1363
- renderRequestHeaders() {
1364
- const { operation } = this.operationDefinition;
1365
- const $headers = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "header").map((p) => `if (args && ${JSON.stringify(p.name)} in args) req.header(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}])`).join("\n");
1366
- return $headers;
1367
- }
1368
- // render: "if (args && 'id' in args) req.query('id', args['id'], options)"
1369
- renderRequestQuery() {
1370
- const { operation } = this.operationDefinition;
1371
- const $query = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "query").map((p) => {
1372
- const option = this.getQsParameters(p);
1373
- const $option = !option || R15.isEmpty(option) ? "" : `, ${JSON.stringify(option)}`;
1374
- return `if (args && ${JSON.stringify(p.name)} in args) req.query(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}]${$option})`;
1375
- }).join("\n");
1376
- return $query;
1377
- }
1378
- // render: "if (args && 'id' in args) req.params('id', args['id'])"
1379
- renderRequestPathParameters() {
1380
- const { operation } = this.operationDefinition;
1381
- const $pathParameters = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "path").map((p) => `if (args && ${JSON.stringify(p.name)} in args) req.params(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}])`).join("\n");
1382
- return $pathParameters;
1383
- }
1384
- getRequestMediaTypes() {
1385
- const { operation } = this.operationDefinition;
1386
- const requestBodyContent = operation.requestBody?.content || {};
1387
- return Object.keys(requestBodyContent);
1388
- }
1389
- // render "req.type("application/json")"
1390
- renderMediaType() {
1391
- const mediaTypes = this.getRequestMediaTypes();
1392
- if (mediaTypes.length === 1 && !mediaTypes[0].endsWith("/*")) {
1393
- return `req.type("${mediaTypes[0]}")
1394
- `;
1395
- } else if (mediaTypes.some((mediaType) => mediaType === "*/*")) {
1396
- } else if (mediaTypes.some((mediaType) => mediaType.endsWith("/*"))) {
1397
- return 'if(args?.["content-type"]) req.type(args["content-type"])\n';
1398
- } else if (mediaTypes.length > 1) {
1399
- return 'if(args?.["content-type"]) req.type(args["content-type"])\n';
1400
- }
1401
- return "";
1402
- }
1403
- // render body
1404
- requestBodyFormDataPropertyRenderer(propertyName, propertySchema, mediaType) {
19
+ async function findAllFiles(dir, extensions) {
20
+ const results = [];
21
+ async function scan(currentDir) {
22
+ let entries;
1405
23
  try {
1406
- const $propertyName = JSON.stringify(propertyName);
1407
- const schema = JsonSchemaUtils.isRef(propertySchema) ? OpenapiUtils.dereferenceDeep(propertySchema.$ref, this.operationDefinition.document.specification) : propertySchema;
1408
- if (schema.type === "string" && schema.format === "binary" || schema.contentMediaType === "application/octet-stream") {
1409
- return `if (args && ${$propertyName} in args && args[${$propertyName}]) req.attach(${$propertyName}, args[${$propertyName}])`;
1410
- } else if (schema.type === "string" || schema.type === "array" && schema.items && schema.items.type === "string") {
1411
- return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, args[${$propertyName}])`;
1412
- } else if (schema.type === "number" || schema.type === "integer") {
1413
- return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, String(args[${$propertyName}]))`;
1414
- }
1415
- return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, String(args[${$propertyName}]) /* type is non-string in schema; triggers type coercion here */)`;
24
+ entries = await fs.readdir(currentDir);
1416
25
  } catch (err) {
1417
- return this.renderErrorComment(err, mediaType);
1418
- }
1419
- }
1420
- requestBodyPropertyRenderer(propertyName, propertySchema, mediaType) {
1421
- if (mediaType === "application/json") {
1422
- const $propertyName = JSON.stringify(propertyName);
1423
- return `if (args && ${$propertyName} in args) req.send({ ${$propertyName}: args[${$propertyName}] })`;
1424
- } else if (mediaType === "multipart/form-data") {
1425
- return this.requestBodyFormDataPropertyRenderer(propertyName, propertySchema, mediaType);
1426
- } else {
1427
- throw new Error(`Unsupported media type: ${mediaType}`);
26
+ return;
1428
27
  }
1429
- }
1430
- renderRequestBody() {
1431
- const { operation } = this.operationDefinition;
1432
- const requestBodyContent = operation.requestBody?.content || {};
1433
- const $requestBody = Object.entries(requestBodyContent).map(([mediaType, mediaTypeObject]) => {
1434
- if (!mediaTypeObject.schema) return;
28
+ for (const entry of entries) {
29
+ if (entry === "node_modules" || entry === ".git") {
30
+ continue;
31
+ }
32
+ const fullPath = path.join(currentDir, entry);
33
+ let stat;
1435
34
  try {
1436
- const schema = JsonSchemaUtils.isRef(mediaTypeObject.schema) ? OpenapiUtils.dereferenceDeep(mediaTypeObject.schema.$ref, this.operationDefinition.document.specification) : mediaTypeObject.schema;
1437
- if (schema.type !== "object") return;
1438
- const properties = schema.properties || {};
1439
- return Object.entries(properties).map(([propertyName, propertySchema]) => this.requestBodyPropertyRenderer(propertyName, propertySchema, mediaType)).join("\n");
35
+ stat = await fs.stat(fullPath);
1440
36
  } catch (err) {
1441
- return this.renderErrorComment(err, mediaType);
37
+ continue;
1442
38
  }
1443
- }).filter(R15.isNotNil).join("\n");
1444
- return $requestBody;
1445
- }
1446
- renderErrorComment(err, mediaType) {
1447
- const $err = String(err).split("\n").map(((line) => ` * ${line}`)).join("\n");
1448
- return [
1449
- "/**",
1450
- ` * Unable to dereference schema for media type ${mediaType}`,
1451
- $err,
1452
- " */"
1453
- ].join("\n");
1454
- }
1455
- };
1456
-
1457
- // src/transformers/operation-definition/micro-function.renderer.ts
1458
- var OperationDefinitionMicroFunctionRenderer = class {
1459
- constructor(operationDefinition, options) {
1460
- this.operationDefinition = operationDefinition;
1461
- this.options = options;
1462
- this.typeName = typeNameFactory(operationDefinition);
1463
- this.helper = new OperationDefinitionSnippet(operationDefinition, options);
1464
- }
1465
- helper;
1466
- typeName;
1467
- render() {
1468
- const { operation, operationId, method, pathname } = this.operationDefinition;
1469
- if (!operation.responses) return "";
1470
- const $dependencies = this.renderDependencies();
1471
- const $comment = new CommentRenderer2(this.operationDefinition).render();
1472
- const moduleName = this.operationDefinition.module.name;
1473
- const $method = method.toLowerCase();
1474
- const $queryParameters = this.helper.renderRequestQuery();
1475
- const $headerParameters = this.helper.renderRequestHeaders();
1476
- const $pathParameters = this.helper.renderRequestPathParameters();
1477
- const $mediaType = this.helper.renderMediaType();
1478
- const $requestBody = this.helper.renderRequestBody();
1479
- const $operationDeclaration = this.renderOperationDeclaration();
1480
- return [
1481
- "/* @anchor:file:start */",
1482
- "",
1483
- $dependencies,
1484
- "",
1485
- `const moduleName = "${moduleName}"`,
1486
- `const method = "${method}"`,
1487
- `const pathname = "${pathname}"`,
1488
- "",
1489
- $comment || void 0,
1490
- `export ${$operationDeclaration} {`,
1491
- ` const req = request.${$method}<${this.typeName("ResponseBodies")}[STATUS]>("${pathname}")`,
1492
- " .option('module', { name: moduleName, pathname, method })",
1493
- "",
1494
- $mediaType ? indent(2, $mediaType) : void 0,
1495
- " /* @anchor:query:start */",
1496
- $queryParameters ? indent(2, $queryParameters) : void 0,
1497
- " /* @anchor:query:end */",
1498
- "",
1499
- " /* @anchor:headers:start */",
1500
- $headerParameters ? indent(2, $headerParameters) : void 0,
1501
- " /* @anchor:headers:end */",
1502
- "",
1503
- " /* @anchor:path-parameters:start */",
1504
- $pathParameters ? indent(2, $pathParameters) : void 0,
1505
- " /* @anchor:path-parameters:end */",
1506
- "",
1507
- " /* @anchor:body:start */",
1508
- $requestBody ? indent(2, $requestBody) : void 0,
1509
- " /* @anchor:body:end */",
1510
- "",
1511
- " /* @anchor:operation-return */",
1512
- ` return req as ReturnType<typeof ${operationId}<STATUS${$operationDeclaration.includes("CONTENT_TYPE") ? ", CONTENT_TYPE" : ""}>>`,
1513
- "}",
1514
- "",
1515
- `${operationId}.pathname = pathname`,
1516
- `${operationId}.method = method`,
1517
- "/* @anchor:file:end */"
1518
- ].filter(R16.isNotNil).join("\n");
1519
- }
1520
- renderDependencies() {
1521
- const declarationFilepath = this.options.getOperationDefinitionDeclarationFilepath(this.operationDefinition);
1522
- const requestFilepath = this.options.getRequestFilepath();
1523
- return [
1524
- 'import { Keq } from "keq"',
1525
- `import { request } from "${requestFilepath}"`,
1526
- `import type { ${this.typeName("Operation")}, ${this.typeName("ResponseBodies")}, ${this.typeName("RequestParameters")} } from "${declarationFilepath}"`,
1527
- `export type { ${this.typeName("RequestQuery")}, ${this.typeName("RequestHeaders")}, ${this.typeName("RequestBodies")} } from "${declarationFilepath}"`
1528
- ].map((str) => str.replace(/ from "(\.\.?\/.+?)(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?"/, this.options.esm ? ' from "$1.js"' : ' from "$1"')).join("\n");
1529
- }
1530
- renderOperationDeclaration() {
1531
- const { operationId } = this.operationDefinition;
1532
- const mediaTypes = this.helper.getRequestMediaTypes();
1533
- if (mediaTypes.length === 0) {
1534
- return `function ${operationId}<STATUS extends keyof ${this.typeName("ResponseBodies")}, CONTENT_TYPE extends never = never>(args?: ${this.typeName("RequestParameters")}): Keq<${this.typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1535
- } else if (mediaTypes.length === 1) {
1536
- return `function ${operationId}<STATUS extends keyof ${this.typeName("ResponseBodies")}, CONTENT_TYPE extends ${JSON.stringify(mediaTypes[0])} = ${JSON.stringify(mediaTypes[0])}>(args?: ${this.typeName("RequestParameters")}): Keq<${this.typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1537
- } else if (mediaTypes.length > 1) {
1538
- return `function ${operationId}<STATUS extends keyof ${this.typeName("ResponseBodies")}, CONTENT_TYPE extends ${this.typeName("RequestParameters")}["content-type"]>(args?: Extract<${this.typeName("RequestParameters")}, { "content-type": CONTENT_TYPE }>): Keq<${this.typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1539
- }
1540
- throw new Exception(this.operationDefinition.module, "[operationDeclarationRenderer] Unreachable");
1541
- }
1542
- };
1543
-
1544
- // src/transformers/operation-definition/nestjs-method.renderer.ts
1545
- import * as R17 from "ramda";
1546
- var OperationDefinitionNestjsMethodRenderer = class {
1547
- constructor(operationDefinition, options) {
1548
- this.operationDefinition = operationDefinition;
1549
- this.options = options;
1550
- this.typeName = typeNameFactory(operationDefinition);
1551
- this.helper = new OperationDefinitionSnippet(operationDefinition, options);
1552
- }
1553
- helper;
1554
- typeName;
1555
- render() {
1556
- const pathname = this.operationDefinition.pathname;
1557
- const $comment = new CommentRenderer2(this.operationDefinition).render();
1558
- const $method = this.operationDefinition.method.toLowerCase();
1559
- const $mediaType = this.helper.renderMediaType();
1560
- const $operationDeclaration = this.renderOperationDeclaration(this.operationDefinition);
1561
- const $queryParameters = this.helper.renderRequestQuery();
1562
- const $headerParameters = this.helper.renderRequestHeaders();
1563
- const $pathParameters = this.helper.renderRequestPathParameters();
1564
- const $requestBody = this.helper.renderRequestBody();
1565
- return [
1566
- $comment,
1567
- `${$operationDeclaration} {`,
1568
- ` const req = this.request.${$method}<${this.typeName("ResponseBodies")}[STATUS]>(${JSON.stringify(pathname)})`,
1569
- " .option(",
1570
- ' "module",',
1571
- " {",
1572
- ` name: ${JSON.stringify(this.operationDefinition.module.name)},`,
1573
- ` pathname: ${JSON.stringify(pathname)},`,
1574
- ` method: ${JSON.stringify($method)},`,
1575
- " },",
1576
- " )",
1577
- "",
1578
- $mediaType ? indent(2, $mediaType) : void 0,
1579
- "",
1580
- " /* @anchor:query:start */",
1581
- $queryParameters ? indent(2, $queryParameters) : void 0,
1582
- " /* @anchor:query:end */",
1583
- "",
1584
- " /* @anchor:headers:start */",
1585
- $headerParameters ? indent(2, $headerParameters) : void 0,
1586
- " /* @anchor:headers:end */",
1587
- "",
1588
- " /* @anchor:path-parameters:start */",
1589
- $pathParameters ? indent(2, $pathParameters) : void 0,
1590
- " /* @anchor:path-parameters:end */",
1591
- "",
1592
- " /* @anchor:body:start */",
1593
- $requestBody ? indent(2, $requestBody) : void 0,
1594
- " /* @anchor:body:end */",
1595
- "",
1596
- " return req",
1597
- "}"
1598
- ].filter(R17.isNotNil).join("\n");
1599
- }
1600
- renderOperationDeclaration(operationDefinition) {
1601
- const { operationId } = operationDefinition;
1602
- const typeName = typeNameFactory(operationDefinition);
1603
- const mediaTypes = this.helper.getRequestMediaTypes();
1604
- if (mediaTypes.length === 0) {
1605
- return `${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends never = never>(args?: ${typeName("RequestParameters")}): Keq<${typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1606
- } else if (mediaTypes.length === 1) {
1607
- return `${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends ${JSON.stringify(mediaTypes[0])} = ${JSON.stringify(mediaTypes[0])}>(args?: ${typeName("RequestParameters")}): Keq<${typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1608
- } else if (mediaTypes.length > 1) {
1609
- return `${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends ${typeName("RequestParameters")}["content-type"]>(args?: Extract<${typeName("RequestParameters")}, { "content-type": CONTENT_TYPE }>): Keq<${typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1610
- }
1611
- throw new Exception(operationDefinition.module, "[operationDeclarationRenderer] Unreachable");
1612
- }
1613
- };
1614
-
1615
- // src/transformers/operation-definition/operation-definition.transformer.ts
1616
- var OperationDefinitionTransformer = class {
1617
- static toDeclaration(operationDefinition, options) {
1618
- return new DeclarationRenderer2(operationDefinition, options).render();
1619
- }
1620
- static toMicroFunction(operationDefinition, options) {
1621
- return new OperationDefinitionMicroFunctionRenderer(operationDefinition, options).render();
1622
- }
1623
- static toNestjsMethod(operationDefinition, options) {
1624
- return new OperationDefinitionNestjsMethodRenderer(operationDefinition, options).render();
1625
- }
1626
- static toComment(operationDefinition) {
1627
- return new CommentRenderer2(operationDefinition).render();
1628
- }
1629
- };
1630
-
1631
- // src/transformers/entrypoint/entrypoint.transformer.ts
1632
- import * as path5 from "path";
1633
- var EntrypointTransformer = class {
1634
- static toTypescript(exports, options) {
1635
- const $exports = exports.map((exportArtifact) => {
1636
- const relativePath = path5.relative(
1637
- options.dirpath,
1638
- exportArtifact.filepath
1639
- ).replace(/(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?$/, options.esm ? ".js" : "");
1640
- return relativePath.startsWith(".") ? `export * from '${relativePath}'` : `export * from './${relativePath}'`;
1641
- });
1642
- return [
1643
- "/* @anchor:file:start */",
1644
- "",
1645
- ...$exports,
1646
- "",
1647
- "/* @anchor:file:end */"
1648
- ].join("\n");
1649
- }
1650
- };
1651
-
1652
- // src/transformers/api-document/nestjs-client.renderer.ts
1653
- import * as R18 from "ramda";
1654
- import * as changeCase2 from "change-case";
1655
-
1656
- // src/transformers/api-document/nestjs-module.renderer.ts
1657
- import * as changeCase3 from "change-case";
1658
-
1659
- // src/plugins/generate-declaration/generators/schema-declaration/schema.generator.ts
1660
- import * as R19 from "ramda";
1661
- import * as path6 from "path";
1662
- import * as changeCase4 from "change-case";
1663
-
1664
- // src/plugins/generate-declaration/constants/metadata-storage.ts
1665
- var MetadataStorage4 = /* @__PURE__ */ new WeakMap();
1666
-
1667
- // src/plugins/generate-declaration/generators/schema-declaration/schema.generator.ts
1668
- var SCHEMA_GENERATOR = "schemaGenerator";
1669
- var SchemaDeclarationGenerator = class _SchemaDeclarationGenerator {
1670
- async compile(compiler, task) {
1671
- const context = compiler.context;
1672
- const metadata = MetadataStorage4.get(compiler);
1673
- const rc = context.rc;
1674
- const documents = context.documents;
1675
- const schemaDefinitions = documents.flatMap((document) => document.schemas);
1676
- const artifactMap = new Map(
1677
- await Promise.all(
1678
- schemaDefinitions.map(async (schemaDefinition) => [
1679
- schemaDefinition,
1680
- await metadata.hooks.afterSchemaDeclarationArtifactGenerated.promise(
1681
- this.generateSchemaDefinitionsArtifact(schemaDefinition, rc),
1682
- schemaDefinition,
1683
- task
1684
- )
1685
- ])
1686
- )
1687
- );
1688
- const entrypoints = R19.collectBy(
1689
- (schemaDefinition) => schemaDefinition.module.name,
1690
- schemaDefinitions
1691
- ).map((schemaDefinitions2) => [
1692
- schemaDefinitions2[0].module,
1693
- schemaDefinitions2.map((schemaDefinition) => artifactMap.get(schemaDefinition)).filter((artifact) => Boolean(artifact))
1694
- ]).map(([moduleDefinition, artifacts]) => this.generateEntrypointArtifact(
1695
- moduleDefinition,
1696
- artifacts,
1697
- rc
1698
- ));
1699
- return [...artifactMap.values(), ...entrypoints];
1700
- }
1701
- generateSchemaDefinitionsArtifact(schemaDefinition, rc) {
1702
- const filepath = _SchemaDeclarationGenerator.getSchemaDefinitionArtifactFilepath(schemaDefinition, rc.fileNamingStyle);
1703
- const dirpath = path6.dirname(filepath);
1704
- const artifact = new Artifact({
1705
- id: _SchemaDeclarationGenerator.getSchemaDefinitionArtifactId(schemaDefinition),
1706
- filepath,
1707
- content: SchemaDefinitionTransformer.toDeclaration(
1708
- schemaDefinition,
1709
- {
1710
- esm: rc.esm,
1711
- getDependentSchemaDefinitionFilepath(dependentSchemaDefinition) {
1712
- const relativePath = path6.relative(
1713
- dirpath,
1714
- _SchemaDeclarationGenerator.getSchemaDefinitionArtifactFilepath(dependentSchemaDefinition, rc.fileNamingStyle)
1715
- );
1716
- return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
39
+ if (stat.isDirectory()) {
40
+ await scan(fullPath);
41
+ } else if (stat.isFile()) {
42
+ if (!extensions) {
43
+ results.push(fullPath);
44
+ } else {
45
+ const ext = path.extname(fullPath);
46
+ if (extensions.includes(ext)) {
47
+ results.push(fullPath);
1717
48
  }
1718
49
  }
1719
- ),
1720
- extensionName: ".schema.ts"
1721
- });
1722
- return artifact;
1723
- }
1724
- generateEntrypointArtifact(moduleDefinition, exports, rc) {
1725
- const filepath = _SchemaDeclarationGenerator.getEntrypointArtifactFilepath(moduleDefinition, rc.fileNamingStyle);
1726
- const dirpath = path6.dirname(filepath);
1727
- const artifact = new Artifact({
1728
- id: _SchemaDeclarationGenerator.getEntrypointArtifactId(moduleDefinition),
1729
- filepath,
1730
- content: EntrypointTransformer.toTypescript(exports, { dirpath })
1731
- });
1732
- return artifact;
1733
- }
1734
- static getEntrypointArtifactFilepath(moduleDefinition, fileNamingStyle) {
1735
- return [
1736
- ".",
1737
- changeCase4[fileNamingStyle](moduleDefinition.name),
1738
- "types",
1739
- "components",
1740
- "schemas",
1741
- "index.ts"
1742
- ].join("/");
1743
- }
1744
- static getEntrypointArtifactId(moduleDefinition) {
1745
- return `${moduleDefinition.address.url}/components/schemas/entrypoint?generator=${SCHEMA_GENERATOR}`;
1746
- }
1747
- static getSchemaDefinitionArtifactFilepath(schemaDefinition, fileNamingStyle) {
1748
- const filename = `${changeCase4[fileNamingStyle](schemaDefinition.name)}.schema.ts`;
1749
- return [
1750
- ".",
1751
- changeCase4[fileNamingStyle](schemaDefinition.module.name),
1752
- "types",
1753
- "components",
1754
- "schemas",
1755
- filename
1756
- ].join("/");
1757
- }
1758
- static getSchemaDefinitionArtifactId(schemaDefinition) {
1759
- return `${schemaDefinition.id}?generator=${SCHEMA_GENERATOR}`;
1760
- }
1761
- };
1762
-
1763
- // src/plugins/generate-declaration/generators/operation-declaration/operation.generator.ts
1764
- var OPERATION_GENERATOR = "operationDeclarationGenerator";
1765
- var OperationDeclarationGenerator = class _OperationDeclarationGenerator {
1766
- async compile(compiler, task) {
1767
- const context = compiler.context;
1768
- const metadata = MetadataStorage4.get(compiler);
1769
- const rc = context.rc;
1770
- const documents = context.documents;
1771
- const operationDefinitions = documents.flatMap((document) => document.operations);
1772
- const artifactMap = new Map(
1773
- await Promise.all(
1774
- operationDefinitions.map(async (operationDefinition) => [
1775
- operationDefinition,
1776
- await metadata.hooks.afterOperationDeclarationArtifactGenerated.promise(
1777
- this.generateOperationDefinitionArtifact(operationDefinition, rc),
1778
- operationDefinition,
1779
- task
1780
- )
1781
- ])
1782
- )
1783
- );
1784
- return Array.from(artifactMap.values());
1785
- }
1786
- generateOperationDefinitionArtifact(operationDefinition, rc) {
1787
- const filepath = _OperationDeclarationGenerator.getOperationDefinitionArtifactFilepath(operationDefinition, rc.fileNamingStyle);
1788
- const dirpath = path7.dirname(filepath);
1789
- const artifact = new Artifact({
1790
- id: _OperationDeclarationGenerator.getOperationDefinitionArtifactId(operationDefinition),
1791
- filepath,
1792
- content: OperationDefinitionTransformer.toDeclaration(
1793
- operationDefinition,
1794
- {
1795
- esm: rc.esm,
1796
- getDependentSchemaDefinitionFilepath(dependentSchemaDefinition) {
1797
- const relativePath = path7.relative(
1798
- dirpath,
1799
- SchemaDeclarationGenerator.getSchemaDefinitionArtifactFilepath(dependentSchemaDefinition, rc.fileNamingStyle)
1800
- );
1801
- return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
1802
- }
1803
- }
1804
- ),
1805
- extensionName: ".type.ts"
1806
- });
1807
- return artifact;
1808
- }
1809
- generateEntrypointArtifact(moduleDefinition, exports, rc) {
1810
- const filepath = _OperationDeclarationGenerator.getEntrypointArtifactFilepath(moduleDefinition, rc.fileNamingStyle);
1811
- const dirpath = path7.dirname(filepath);
1812
- const artifact = new Artifact({
1813
- id: _OperationDeclarationGenerator.getEntrypointArtifactId(moduleDefinition),
1814
- filepath,
1815
- content: EntrypointTransformer.toTypescript(exports, { dirpath })
1816
- });
1817
- return artifact;
1818
- }
1819
- static getOperationDefinitionArtifactFilepath(operationDefinition, fileNamingStyle) {
1820
- const filename = `${changeCase5[fileNamingStyle](operationDefinition.operationId)}.type.ts`;
1821
- const filepath = [
1822
- ".",
1823
- changeCase5[fileNamingStyle](operationDefinition.module.name),
1824
- "types",
1825
- "operations",
1826
- filename
1827
- ].join("/");
1828
- return filepath;
1829
- }
1830
- static getOperationDefinitionArtifactId(operationDefinition) {
1831
- return `${operationDefinition.id}?generator=${OPERATION_GENERATOR}`;
1832
- }
1833
- static getEntrypointArtifactFilepath(moduleDefinition, fileNamingStyle) {
1834
- return [
1835
- ".",
1836
- changeCase5[fileNamingStyle](moduleDefinition.name),
1837
- "types",
1838
- "operations",
1839
- "index.ts"
1840
- ].join("/");
1841
- }
1842
- static getEntrypointArtifactId(moduleDefinition) {
1843
- return `${moduleDefinition.address.url}/paths/entrypoint?generator=${OPERATION_GENERATOR}`;
1844
- }
1845
- };
1846
-
1847
- // src/plugins/generate-declaration/generate-declaration.plugin.ts
1848
- var DECLARATION_GENERATOR = "declarationGenerator";
1849
- var GenerateDeclarationPlugin = class _GenerateDeclarationPlugin {
1850
- name = DECLARATION_GENERATOR;
1851
- operationGenerator = new OperationDeclarationGenerator();
1852
- schemaGenerator = new SchemaDeclarationGenerator();
1853
- constructor() {
1854
- }
1855
- apply(compiler) {
1856
- if (MetadataStorage4.has(compiler)) return;
1857
- _GenerateDeclarationPlugin.register(compiler);
1858
- compiler.hooks.compile.tapPromise(_GenerateDeclarationPlugin.name, async (task) => {
1859
- compiler.context.artifacts?.push(
1860
- ...await this.schemaGenerator.compile(compiler, task),
1861
- ...await this.operationGenerator.compile(compiler, task)
1862
- );
1863
- });
1864
- }
1865
- static register(compiler) {
1866
- if (!MetadataStorage4.has(compiler)) {
1867
- MetadataStorage4.set(compiler, {
1868
- hooks: {
1869
- afterEntrypointArtifactGenerated: new AsyncSeriesWaterfallHook(["artifact", "task"]),
1870
- afterSchemaDeclarationArtifactGenerated: new AsyncSeriesWaterfallHook(["artifact", "schemaDefinition", "task"]),
1871
- afterOperationDeclarationArtifactGenerated: new AsyncSeriesWaterfallHook(["artifact", "operationDefinition", "task"])
1872
- }
1873
- });
1874
- }
1875
- return MetadataStorage4.get(compiler);
1876
- }
1877
- static of(compiler) {
1878
- return this.register(compiler);
1879
- }
1880
- };
1881
-
1882
- // src/plugins/generate-micro-function/generators/request/request.generator.ts
1883
- var MICRO_FUNCTION_REQUEST_GENERATOR = "microFunctionRequestGenerator";
1884
- var RequestGenerator = class _RequestGenerator {
1885
- generateRequestArtifact() {
1886
- const content = [
1887
- "/* @anchor:file:start */",
1888
- "",
1889
- 'import { KeqRequest } from "keq"',
1890
- "",
1891
- "/* @anchor:request-declaration */",
1892
- "export const request = new KeqRequest()",
1893
- "",
1894
- "/* @anchor:file:end */"
1895
- ].join("\n");
1896
- return new Artifact({
1897
- id: _RequestGenerator.getRequestArtifactId(),
1898
- filepath: _RequestGenerator.getRequestArtifactFilepath(),
1899
- content
1900
- });
1901
- }
1902
- // eslint-disable-next-line @typescript-eslint/require-await
1903
- async compile(compiler, task) {
1904
- return [
1905
- this.generateRequestArtifact()
1906
- ];
1907
- }
1908
- static getRequestArtifactFilepath() {
1909
- return "./request.ts";
1910
- }
1911
- static getRequestArtifactId() {
1912
- return `request?generator=${MICRO_FUNCTION_REQUEST_GENERATOR}`;
1913
- }
1914
- };
1915
-
1916
- // src/plugins/generate-micro-function/generators/micro_function/micro-function.generator.ts
1917
- var MICRO_FUNCTION_GENERATOR = "microFunctionGenerator";
1918
- var MicroFunctionGenerator = class _MicroFunctionGenerator {
1919
- async compile(compiler, task) {
1920
- const metadata = MetadataStorage3.get(compiler);
1921
- const context = compiler.context;
1922
- const rc = context.rc;
1923
- const documents = context.documents;
1924
- const operationDefinitions = documents.flatMap((document) => document.operations);
1925
- const artifactMap = new Map(
1926
- await Promise.all(
1927
- operationDefinitions.map(async (operationDefinition) => [
1928
- operationDefinition,
1929
- await metadata.hooks.afterMicroFunctionArtifactGenerated.promise(
1930
- this.generateOperationDefinitionArtifact(operationDefinition, rc),
1931
- operationDefinition,
1932
- task
1933
- )
1934
- ])
1935
- )
1936
- );
1937
- const entrypoints = await Promise.all(
1938
- R20.collectBy(
1939
- (operationDefinition) => operationDefinition.module.name,
1940
- operationDefinitions
1941
- ).map((operationDefinitions2) => [
1942
- operationDefinitions2[0].module,
1943
- operationDefinitions2.map((operationDefinition) => artifactMap.get(operationDefinition)).filter((artifact) => Boolean(artifact))
1944
- ]).map(async ([moduleDefinition, artifacts]) => await metadata.hooks.afterEntrypointArtifactGenerated.promise(
1945
- this.generateEntrypointArtifact(
1946
- moduleDefinition,
1947
- artifacts,
1948
- rc
1949
- ),
1950
- task
1951
- ))
1952
- );
1953
- return [...entrypoints, ...artifactMap.values()];
1954
- }
1955
- generateOperationDefinitionArtifact(operationDefinition, rc) {
1956
- const filepath = _MicroFunctionGenerator.getOperationDefinitionArtifactFilepath(operationDefinition, rc.fileNamingStyle);
1957
- const dirpath = path8.dirname(filepath);
1958
- const artifact = new Artifact({
1959
- id: _MicroFunctionGenerator.getOperationDefinitionArtifactId(operationDefinition),
1960
- filepath,
1961
- content: OperationDefinitionTransformer.toMicroFunction(operationDefinition, {
1962
- esm: rc.esm,
1963
- getOperationDefinitionDeclarationFilepath(operationDefinition2) {
1964
- const relativePath = path8.relative(
1965
- dirpath,
1966
- OperationDeclarationGenerator.getOperationDefinitionArtifactFilepath(operationDefinition2, rc.fileNamingStyle)
1967
- );
1968
- return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
1969
- },
1970
- getRequestFilepath() {
1971
- const relativePath = path8.relative(
1972
- dirpath,
1973
- RequestGenerator.getRequestArtifactFilepath()
1974
- );
1975
- return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
1976
- }
1977
- }),
1978
- extensionName: ".type.ts"
1979
- });
1980
- return artifact;
1981
- }
1982
- generateEntrypointArtifact(moduleDefinition, exports, rc) {
1983
- const filepath = _MicroFunctionGenerator.getEntrypointArtifactFilepath(moduleDefinition, rc.fileNamingStyle);
1984
- const dirpath = filepath.substring(0, filepath.lastIndexOf("/"));
1985
- const artifact = new Artifact({
1986
- id: _MicroFunctionGenerator.getEntrypointArtifactId(moduleDefinition),
1987
- filepath,
1988
- content: EntrypointTransformer.toTypescript(exports, { dirpath })
1989
- });
1990
- return artifact;
1991
- }
1992
- static getOperationDefinitionArtifactFilepath(operationDefinition, fileNamingStyle) {
1993
- const filename = `${changeCase6[fileNamingStyle](operationDefinition.operationId)}.fn.ts`;
1994
- const filepath = [
1995
- ".",
1996
- changeCase6[fileNamingStyle](operationDefinition.module.name),
1997
- "operations",
1998
- filename
1999
- ].join("/");
2000
- return filepath;
2001
- }
2002
- static getOperationDefinitionArtifactId(operationDefinition) {
2003
- return `${operationDefinition.id}?generator=${MICRO_FUNCTION_GENERATOR}`;
2004
- }
2005
- static getEntrypointArtifactFilepath(moduleDefinition, fileNamingStyle) {
2006
- return [
2007
- ".",
2008
- changeCase6[fileNamingStyle](moduleDefinition.name),
2009
- "operations",
2010
- "index.ts"
2011
- ].join("/");
2012
- }
2013
- static getEntrypointArtifactId(moduleDefinition) {
2014
- return `${moduleDefinition.address}/paths/entrypoint?generator=${MICRO_FUNCTION_GENERATOR}`;
2015
- }
2016
- };
2017
-
2018
- // src/plugins/generate-micro-function/generate-micro-function.plugin.ts
2019
- var GenerateMicroFunctionPlugin = class _GenerateMicroFunctionPlugin {
2020
- microFunctionGenerator = new MicroFunctionGenerator();
2021
- requestGenerator = new RequestGenerator();
2022
- apply(compiler) {
2023
- if (MetadataStorage3.has(compiler)) return;
2024
- _GenerateMicroFunctionPlugin.register(compiler);
2025
- compiler.hooks.compile.tapPromise(_GenerateMicroFunctionPlugin.name, async (task) => {
2026
- const artifacts = [
2027
- ...await this.requestGenerator.compile(compiler, task),
2028
- ...await this.microFunctionGenerator.compile(compiler, task)
2029
- ];
2030
- compiler.context.artifacts.push(...artifacts);
2031
- });
2032
- }
2033
- static register(compiler) {
2034
- if (!MetadataStorage3.has(compiler)) {
2035
- MetadataStorage3.set(compiler, {
2036
- hooks: {
2037
- afterEntrypointArtifactGenerated: new AsyncSeriesWaterfallHook2(["artifact", "task"]),
2038
- afterMicroFunctionArtifactGenerated: new AsyncSeriesWaterfallHook2(["artifact", "operationDefinition", "task"])
2039
- }
2040
- });
2041
- }
2042
- return MetadataStorage3.get(compiler);
2043
- }
2044
- static of(compiler) {
2045
- return this.register(compiler);
2046
- }
2047
- };
2048
-
2049
- // src/plugins/generate-nestjs-module/generate-nestjs-module.ts
2050
- import { AsyncSeriesWaterfallHook as AsyncSeriesWaterfallHook3 } from "tapable";
2051
-
2052
- // src/plugins/generate-nestjs-module/generators/nestjs-module.generator.ts
2053
- import * as changeCase7 from "change-case";
2054
-
2055
- // src/plugins/chinese-to-pinyin/chinese-to-pinyin.plugin.ts
2056
- import { fixSwagger } from "swagger-fix";
2057
-
2058
- // src/plugins/download-http-file/constants/metadata-storage.ts
2059
- var MetadataStorage8 = /* @__PURE__ */ new WeakMap();
2060
-
2061
- // src/plugins/download-http-file/download-http-file.plugin.ts
2062
- var DownloadHttpFilePlugin = class _DownloadHttpFilePlugin {
2063
- apply(compiler) {
2064
- if (MetadataStorage8.has(compiler)) return;
2065
- _DownloadHttpFilePlugin.register(compiler);
2066
- compiler.hooks.download.tapPromise(_DownloadHttpFilePlugin.name, async (address, task) => {
2067
- const { url } = address;
2068
- if (!url.startsWith("http://") && !url.startsWith("https://")) return void 0;
2069
- const content = await this.download(address);
2070
- const spec = this.deserialize(content);
2071
- return JSON.stringify(spec);
2072
- });
2073
- }
2074
- async download(address) {
2075
- const { url, headers } = address;
2076
- try {
2077
- const res = await fetch(url, { headers });
2078
- if (res.status >= 400) throw new Error(`failed with status code ${res.status}`);
2079
- return await res.text();
2080
- } catch (e) {
2081
- if (e instanceof Error) {
2082
- e.message = `Unable get the openapi/swagger file from ${url}: ${e.message}`;
2083
- }
2084
- throw e;
2085
- }
2086
- }
2087
- deserialize(content) {
2088
- const json = JSON.parse(content);
2089
- const spec = OpenapiUtils.to3_1(json);
2090
- return spec;
2091
- }
2092
- static register(compiler) {
2093
- if (!MetadataStorage8.has(compiler)) {
2094
- MetadataStorage8.set(compiler, {
2095
- hooks: {}
2096
- });
2097
- }
2098
- return MetadataStorage8.get(compiler);
2099
- }
2100
- static of(compiler) {
2101
- return this.register(compiler);
2102
- }
2103
- };
2104
-
2105
- // src/plugins/download-local-file/download-local-file.plugin.ts
2106
- import * as path9 from "path";
2107
- import * as fs3 from "fs/promises";
2108
- import * as yaml from "js-yaml";
2109
- import { fileURLToPath } from "url";
2110
-
2111
- // src/plugins/download-local-file/constants/metadata-storage.ts
2112
- var MetadataStorage9 = /* @__PURE__ */ new WeakMap();
2113
-
2114
- // src/plugins/download-local-file/download-local-file.plugin.ts
2115
- var DownloadLocalFilePlugin = class _DownloadLocalFilePlugin {
2116
- apply(compiler) {
2117
- if (MetadataStorage9.has(compiler)) return;
2118
- _DownloadLocalFilePlugin.register(compiler);
2119
- compiler.hooks.download.tapPromise(_DownloadLocalFilePlugin.name, async (address, task) => {
2120
- const { url, encoding } = address;
2121
- if (!url.startsWith("file://")) return void 0;
2122
- const filepath = fileURLToPath(url);
2123
- const fileExt = path9.extname(filepath);
2124
- const content = await fs3.readFile(filepath, encoding);
2125
- const str = typeof content === "string" ? content : content.toString(encoding);
2126
- if ([".yml", ".yaml"].includes(fileExt)) {
2127
- const value = yaml.load(str);
2128
- return JSON.stringify(OpenapiUtils.to3_1(value));
2129
- } else if (fileExt === ".json") {
2130
- return JSON.stringify(OpenapiUtils.to3_1(JSON.parse(str)));
2131
50
  }
2132
- });
2133
- }
2134
- static register(compiler) {
2135
- if (!MetadataStorage9.has(compiler)) {
2136
- MetadataStorage9.set(compiler, {
2137
- hooks: {}
2138
- });
2139
51
  }
2140
- return MetadataStorage9.get(compiler);
2141
52
  }
2142
- static of(compiler) {
2143
- return this.register(compiler);
2144
- }
2145
- };
2146
-
2147
- // src/plugins/shaking/shaking.plugin.ts
2148
- import { openapiShakingSync } from "@opendoc/openapi-shaking";
2149
-
2150
- // src/plugins/shaking/constants/metadata-storage.ts
2151
- var MetadataStorage10 = /* @__PURE__ */ new WeakMap();
2152
-
2153
- // src/plugins/shaking/shaking.plugin.ts
2154
- var ShakingPlugin = class _ShakingPlugin {
2155
- apply(compiler) {
2156
- if (MetadataStorage10.has(compiler)) return;
2157
- _ShakingPlugin.register(compiler);
2158
- compiler.hooks.beforeCompile.tap(_ShakingPlugin.name, (task) => {
2159
- const matcher = compiler.context.matcher;
2160
- const documents = compiler.context.documents;
2161
- compiler.context.documents = documents.map((document) => this.shaking(compiler, document)).filter((document) => !document.isEmpty()).filter((document) => !matcher.isModuleIgnored(document.module));
2162
- });
2163
- }
2164
- shaking(compiler, document) {
2165
- const rc = compiler.context.rc;
2166
- const matcher = compiler.context.matcher;
2167
- const isAccepted = (pathname, method, operation) => {
2168
- if (!SupportedMethods.includes(method)) return false;
2169
- return !matcher.isOperationIgnored(new OperationDefinition({
2170
- method,
2171
- pathname,
2172
- operation,
2173
- module: document.module,
2174
- document
2175
- }));
2176
- };
2177
- const sharkedSwagger = openapiShakingSync(
2178
- document.specification,
2179
- isAccepted,
2180
- { tolerant: rc.tolerant }
2181
- );
2182
- return new ApiDocumentV3_1(
2183
- sharkedSwagger,
2184
- new ModuleDefinition(
2185
- document.module.name,
2186
- {
2187
- url: `memory://${document.module.name}.v3_1.sharked.json`,
2188
- headers: {},
2189
- encoding: "utf8"
2190
- }
2191
- )
2192
- );
2193
- }
2194
- static register(compiler) {
2195
- if (!MetadataStorage10.has(compiler)) {
2196
- MetadataStorage10.set(compiler, {
2197
- hooks: {}
2198
- });
2199
- }
2200
- return MetadataStorage10.get(compiler);
2201
- }
2202
- static of(compiler) {
2203
- return this.register(compiler);
2204
- }
2205
- };
2206
-
2207
- // src/plugins/terminal-select/utils/select-operation-definitions.ts
2208
- import { select } from "inquirer-select-pro";
2209
- import { ListrInquirerPromptAdapter } from "@listr2/prompt-adapter-inquirer";
2210
- async function selectOperationDefinitions(task, operationDefinitions) {
2211
- const selectedOperationDefinitions = await task.prompt(ListrInquirerPromptAdapter).run(
2212
- select,
2213
- {
2214
- message: "Select Pathname",
2215
- defaultValue: [],
2216
- options: (input) => {
2217
- const items = operationDefinitions.map((op) => ({ name: `${op.module.name} ${op.method.toUpperCase()} ${op.pathname}`, value: op }));
2218
- if (!input) return items;
2219
- const keys2 = input.trim().toLowerCase().split(/\s+/);
2220
- return items.filter((i) => {
2221
- const name = i.name.toLowerCase();
2222
- return keys2.every((q) => name.includes(q));
2223
- });
2224
- }
2225
- }
2226
- );
2227
- return selectedOperationDefinitions;
53
+ await scan(dir);
54
+ return results;
2228
55
  }
2229
-
2230
- // src/plugins/terminal-select/constants/metadata-storage.ts
2231
- var MetadataStorage11 = /* @__PURE__ */ new WeakMap();
2232
-
2233
- // src/plugins/terminal-select/terminal-select.plugin.ts
2234
- var TerminalSelectPlugin = class _TerminalSelectPlugin {
2235
- constructor(options) {
2236
- this.options = options;
2237
- }
2238
- apply(compiler) {
2239
- if (MetadataStorage11.has(compiler)) return;
2240
- _TerminalSelectPlugin.register(compiler);
2241
- compiler.hooks.afterDownload.tapPromise(_TerminalSelectPlugin.name, async (task) => {
2242
- const context = compiler.context;
2243
- const matcher = context.matcher;
2244
- const documents = context.documents;
2245
- const operationDefinitions = documents.flatMap((document) => document.operations);
2246
- const selectedOperationDefinitions = await selectOperationDefinitions(task, operationDefinitions);
2247
- if (this.options.clear) {
2248
- matcher.append({
2249
- persist: false,
2250
- ignore: true,
2251
- moduleName: "*",
2252
- operationMethod: "*",
2253
- operationPathname: "*"
2254
- });
2255
- }
2256
- for (const op of selectedOperationDefinitions) {
2257
- matcher.append({
2258
- persist: !!this.options.persist,
2259
- ignore: this.options.mode === "add",
2260
- moduleName: op.module.name,
2261
- operationMethod: op.method,
2262
- operationPathname: op.pathname
2263
- });
2264
- }
2265
- });
2266
- }
2267
- static register(compiler) {
2268
- if (!MetadataStorage11.has(compiler)) {
2269
- MetadataStorage11.set(compiler, {
2270
- hooks: {}
2271
- });
2272
- }
2273
- return MetadataStorage11.get(compiler);
2274
- }
2275
- static of(compiler) {
2276
- return this.register(compiler);
2277
- }
2278
- };
2279
-
2280
- // src/plugins/initialize/initialize.plugin.ts
2281
- import * as R22 from "ramda";
2282
- var InitializePlugin = class _InitializePlugin {
2283
- constructor(options) {
2284
- this.options = options;
56
+ async function scanAllFiles(outdir) {
57
+ const absoluteOutdir = path.resolve(outdir);
58
+ if (!await fs.exists(absoluteOutdir)) {
59
+ return [];
2285
60
  }
2286
- apply(compiler) {
2287
- compiler.hooks.setup.tap(_InitializePlugin.name, (task) => {
2288
- const plugins = [
2289
- new DownloadHttpFilePlugin(),
2290
- new DownloadLocalFilePlugin()
2291
- ];
2292
- if (this.options.build) {
2293
- plugins.push(new ShakingPlugin());
2294
- }
2295
- if (this.options.interactive) {
2296
- plugins.push(
2297
- new TerminalSelectPlugin(
2298
- typeof this.options.interactive === "object" ? this.options.interactive : { mode: "except" }
2299
- )
2300
- );
2301
- }
2302
- const rc = compiler.context.rc;
2303
- plugins.push(
2304
- ...R22.unnest(
2305
- (rc.translators || []).map((translator) => {
2306
- const plugins2 = translator.apply();
2307
- return plugins2;
2308
- })
2309
- )
2310
- );
2311
- if (rc.plugins && rc.plugins.length) {
2312
- plugins.push(...rc.plugins);
2313
- }
2314
- for (const plugin of plugins) {
2315
- plugin.apply(compiler);
2316
- }
2317
- });
2318
- if (this.options.includes && this.options.includes.length) {
2319
- const modulesIncludes = this.options.includes;
2320
- compiler.hooks.afterSetup.tap(_InitializePlugin.name, (task) => {
2321
- const rc = compiler.context.rc;
2322
- const matcher = compiler.context.matcher;
2323
- const notExistModules = modulesIncludes.filter((moduleName) => !(moduleName in rc.modules));
2324
- if (notExistModules.length) {
2325
- throw new Error(`Cannot find module(s) ${notExistModules.join(", ")} in config file.`);
2326
- }
2327
- const ignoredModules = R22.difference(R22.keys(rc.modules), modulesIncludes);
2328
- for (const moduleName of ignoredModules) {
2329
- matcher.append({
2330
- persist: false,
2331
- ignore: true,
2332
- moduleName,
2333
- operationMethod: "*",
2334
- operationPathname: "*"
2335
- });
2336
- }
2337
- });
2338
- }
2339
- }
2340
- };
2341
-
2342
- // src/plugins/overwrite-query-options/overwrite-query-options.plugin.ts
2343
- var QsArrayFormatUnion = Object.values(QsArrayFormat);
2344
-
2345
- // src/translators/micro-function.translator.ts
2346
- var MicroFunctionTranslator = class {
2347
- apply() {
2348
- return [
2349
- new GenerateDeclarationPlugin(),
2350
- new GenerateMicroFunctionPlugin()
2351
- ];
2352
- }
2353
- };
2354
-
2355
- // src/compiler/tasks/setup/index.ts
2356
- var explore = cosmiconfig("keq");
2357
- function main(compiler, options) {
2358
- return {
2359
- task: async (context, task) => {
2360
- const result = options?.config ? await explore.load(options.config) : await explore.search();
2361
- if (!result || "isEmpty" in result && result.isEmpty) {
2362
- throw new Error("Cannot find config file.");
2363
- }
2364
- const rc = parseRuntimeConfig(result.config);
2365
- if (options?.debug) {
2366
- await fs4.ensureDir(".keq");
2367
- rc.debug = true;
2368
- }
2369
- rc.tolerant = Boolean(rc.tolerant);
2370
- if (!rc.translators || !rc.translators.length) {
2371
- rc.translators = [new MicroFunctionTranslator()];
2372
- }
2373
- const packageJsonInfo = findNearestPackageJson();
2374
- if (packageJsonInfo) {
2375
- const moduleSystem = getProjectModuleSystem(packageJsonInfo);
2376
- rc.esm = moduleSystem === "esm";
2377
- }
2378
- context.rc = rc;
2379
- let matcher = new IgnoreMatcher([]);
2380
- if (result.filepath) {
2381
- const ignoreFilepath = path10.resolve(path10.dirname(result.filepath), ".keqignore");
2382
- if (await fs4.exists(ignoreFilepath)) {
2383
- matcher = await IgnoreMatcher.read(ignoreFilepath);
2384
- }
2385
- }
2386
- const ignoreRules = options.ignore === false ? [] : options.ignore?.rules || [];
2387
- for (const rule of ignoreRules) {
2388
- matcher.append({
2389
- persist: !!rule.persist,
2390
- ignore: rule.ignore,
2391
- moduleName: rule.moduleName,
2392
- operationMethod: rule.operationMethod,
2393
- operationPathname: rule.operationPathname
2394
- });
2395
- }
2396
- context.matcher = matcher;
2397
- await compiler.hooks.setup.promise(task);
2398
- }
2399
- };
2400
- }
2401
- function createSetupTask(compiler, options) {
2402
- return {
2403
- title: "Setup",
2404
- enabled: options?.enabled,
2405
- skip: options?.skip,
2406
- task: (context, task) => task.newListr(
2407
- [
2408
- main(compiler, options),
2409
- {
2410
- task: (context2, task2) => compiler.hooks.afterSetup.promise(task2)
2411
- }
2412
- ],
2413
- {
2414
- concurrent: false
2415
- }
2416
- )
2417
- };
2418
- }
2419
-
2420
- // src/compiler/tasks/download/index.ts
2421
- import { PRESET_TIMER } from "listr2";
2422
- import { validate } from "@scalar/openapi-parser";
2423
- function main2(compiler, options) {
2424
- return {
2425
- task: (context, task) => {
2426
- if (!context.rc || !context.matcher) {
2427
- throw new Error("Please run setup task first.");
2428
- }
2429
- const rc = context.rc;
2430
- const matcher = context.matcher;
2431
- context.documents = [];
2432
- return task.newListr(
2433
- Object.entries(rc.modules).map(([moduleName, address]) => new ModuleDefinition(moduleName, address)).map((moduleDefinition) => ({
2434
- title: moduleDefinition.name,
2435
- task: async (ctx, task2) => {
2436
- if (options?.skipIgnoredModules && matcher.isModuleIgnored(moduleDefinition)) {
2437
- task2.skip(`(${moduleDefinition.name}) is ignored`);
2438
- return;
2439
- }
2440
- task2.output = `Downloaded from ${moduleDefinition.address.url}`;
2441
- const content = await compiler.hooks.download.promise(moduleDefinition.address, moduleDefinition, task2);
2442
- if (!content) {
2443
- throw new Exception(moduleDefinition, `Cannot download document from ${moduleDefinition.address.url}`);
2444
- }
2445
- const spec = JSON.parse(content);
2446
- const { valid, errors } = await validate(spec);
2447
- if (!valid) {
2448
- const message = `${moduleDefinition.name} module openapi/swagger file does not conform to the openapi specifications or have grammatical errors, which may cause unexpected errors:
2449
- ${errors?.map((e) => ` - ${e.message}`).join("\n")}`;
2450
- task2.output = message;
2451
- }
2452
- OpenapiUtils.dereferenceOperation(spec);
2453
- const document = new ApiDocumentV3_1(
2454
- spec,
2455
- moduleDefinition
2456
- );
2457
- ctx.documents?.push(document);
2458
- }
2459
- })),
2460
- {
2461
- concurrent: true,
2462
- exitOnError: false,
2463
- collectErrors: "minimal",
2464
- rendererOptions: {
2465
- collapseSubtasks: false,
2466
- // collapseSkips: false,
2467
- suffixSkips: true,
2468
- timer: PRESET_TIMER
2469
- }
2470
- }
2471
- );
2472
- }
2473
- };
2474
- }
2475
- function createDownloadTask(compiler, options) {
2476
- return {
2477
- title: "Download",
2478
- enabled: options?.enabled,
2479
- skip: options?.skip,
2480
- task: (_, task) => task.newListr(
2481
- [
2482
- main2(compiler, options),
2483
- {
2484
- task: (context, task2) => compiler.hooks.afterDownload.promise(task2)
2485
- }
2486
- ],
2487
- {
2488
- concurrent: false
2489
- }
2490
- )
2491
- };
2492
- }
2493
-
2494
- // src/compiler/tasks/persist/index.ts
2495
- import * as path11 from "path";
2496
- import fs5 from "fs-extra";
2497
- function createPersistArtifactTask() {
2498
- return {
2499
- title: "Write files",
2500
- task: async (context, task) => {
2501
- if (!context.rc) throw new Error("Please run setup task first.");
2502
- if (!context.artifacts || context.artifacts.length === 0) {
2503
- task.skip("No compiled artifacts to persist.");
2504
- return;
2505
- }
2506
- const rc = context.rc;
2507
- const artifacts = context.artifacts;
2508
- const total = artifacts.length;
2509
- let completed = 0;
2510
- const files = await Promise.all(artifacts.map(async (artifact) => {
2511
- const realpath = `./${path11.join(rc.outdir, artifact.filepath)}`;
2512
- await fs5.ensureFile(realpath);
2513
- await fs5.writeFile(realpath, artifact.renderer());
2514
- completed += 1;
2515
- task.output = `Persisted ${completed}/${total} files`;
2516
- return new Asset(path11.resolve(realpath));
2517
- }));
2518
- context.assets = files;
2519
- }
2520
- };
2521
- }
2522
- function createPersistIgnoreTask() {
2523
- return {
2524
- title: "Update .keqignore",
2525
- task: async (context, task) => {
2526
- if (!context.matcher) throw new Error("Please run setup task first.");
2527
- const matcher = context.matcher;
2528
- await matcher.write(".keqignore");
2529
- }
2530
- };
2531
- }
2532
- function main3() {
2533
- return {
2534
- task: (context, task) => task.newListr(
2535
- [
2536
- createPersistArtifactTask(),
2537
- createPersistIgnoreTask()
2538
- ],
2539
- {
2540
- concurrent: true,
2541
- rendererOptions: {
2542
- collapseSubtasks: true
2543
- }
2544
- }
2545
- )
2546
- };
2547
- }
2548
- function createPersistTask(compiler, options) {
2549
- return {
2550
- title: "Persist",
2551
- enabled: options?.enabled,
2552
- skip: options?.skip,
2553
- task: (context, task) => task.newListr(
2554
- [
2555
- main3(),
2556
- {
2557
- task: (context2, task2) => compiler.hooks.afterPersist.promise(task2)
2558
- }
2559
- ],
2560
- {
2561
- concurrent: false
2562
- }
2563
- )
2564
- };
61
+ const files = await findAllFiles(absoluteOutdir);
62
+ return files.map((file) => ({
63
+ absolutePath: file,
64
+ relativePath: path.relative(absoluteOutdir, file)
65
+ }));
2565
66
  }
2566
-
2567
- // src/compiler/tasks/compile/index.ts
2568
- function main4(compiler) {
2569
- return {
2570
- task: async (context, task) => {
2571
- if (!context.rc) throw new Error("Please run setup task first.");
2572
- if (!context.documents) throw new Error("Please run shaking task first.");
2573
- context.artifacts = [];
2574
- await compiler.hooks.compile.promise(task);
2575
- }
2576
- };
2577
- }
2578
- function createCompileTask(compiler, options) {
2579
- return {
2580
- title: "Compile",
2581
- enabled: options?.enabled,
2582
- skip: options?.skip,
2583
- task: (context, task) => task.newListr(
2584
- [
2585
- {
2586
- task: (context2, task2) => compiler.hooks.beforeCompile.promise(task2)
2587
- },
2588
- main4(compiler),
2589
- {
2590
- task: (context2, task2) => compiler.hooks.afterCompile.promise(task2)
2591
- }
2592
- ],
2593
- {
2594
- concurrent: false
2595
- }
2596
- )
2597
- };
2598
- }
2599
-
2600
- // src/compiler/intercepter/print-information.ts
2601
- function proxyTaskWrapper(pluginName, task) {
2602
- return new Proxy(task, {
2603
- set(target, prop2, value) {
2604
- if (prop2 !== "output") {
2605
- return Reflect.set(target, prop2, value);
2606
- }
2607
- target.output = `[Plugin: ${pluginName}] ${value}`;
2608
- return true;
2609
- }
67
+ async function findInvalidFiles(outdir, validFilePaths) {
68
+ const allFiles = await scanAllFiles(outdir);
69
+ const validPathsSet = new Set(validFilePaths.map((p) => path.normalize(p)));
70
+ return allFiles.filter((file) => {
71
+ const normalizedPath = path.normalize(file.relativePath);
72
+ return !validPathsSet.has(normalizedPath);
2610
73
  });
2611
74
  }
2612
- function printInformation(taskIndex) {
2613
- return {
2614
- register: (tap) => {
2615
- const fn = tap.fn;
2616
- if (tap.type === "promise") {
2617
- tap.fn = (...args) => {
2618
- const task = args[taskIndex];
2619
- const proxyTask = proxyTaskWrapper(tap.name, task);
2620
- args[taskIndex] = proxyTask;
2621
- proxyTask.output = "Processing...";
2622
- return fn(...args);
2623
- };
2624
- }
2625
- if (tap.type === "sync") {
2626
- tap.fn = (...args) => {
2627
- const task = args[taskIndex];
2628
- const proxyTask = proxyTaskWrapper(tap.name, task);
2629
- args[taskIndex] = proxyTask;
2630
- proxyTask.output = "Processing...";
2631
- return fn(...args);
2632
- };
2633
- }
2634
- if (tap.type === "async") {
2635
- tap.fn = (...args) => {
2636
- const task = args[taskIndex];
2637
- const proxyTask = proxyTaskWrapper(tap.name, task);
2638
- args[taskIndex] = proxyTask;
2639
- proxyTask.output = "Processing...";
2640
- return fn(...args);
2641
- };
2642
- }
2643
- return tap;
2644
- }
2645
- };
2646
- }
2647
-
2648
- // src/compiler/intercepter/perfect-error-message.ts
2649
- import * as R23 from "ramda";
2650
- function perfectErrorMessage() {
2651
- return {
2652
- register: (tap) => {
2653
- const fn = tap.fn;
2654
- function prefix(err) {
2655
- if (err instanceof Error) {
2656
- err.message = `[Plugin: ${tap.name}] ${err.message}`;
2657
- }
2658
- }
2659
- if (tap.type === "promise") {
2660
- tap.fn = async (...args) => {
2661
- try {
2662
- return await fn(...args);
2663
- } catch (err) {
2664
- prefix(err);
2665
- throw err;
2666
- }
2667
- };
2668
- }
2669
- if (tap.type === "sync") {
2670
- tap.fn = (...args) => {
2671
- try {
2672
- return fn(...args);
2673
- } catch (err) {
2674
- prefix(err);
2675
- throw err;
2676
- }
2677
- };
2678
- }
2679
- if (tap.type === "async") {
2680
- tap.fn = (...args) => {
2681
- const callback = R23.last(args);
2682
- return fn(...R23.init(args), (err, result) => {
2683
- prefix(err);
2684
- return callback(err, result);
2685
- });
2686
- };
2687
- }
2688
- return tap;
2689
- }
2690
- };
2691
- }
2692
-
2693
- // src/compiler/compiler.ts
2694
- var Compiler = class {
2695
- constructor(options) {
2696
- this.options = options;
2697
- for (const hook of Object.values(this.hooks)) {
2698
- hook.intercept(perfectErrorMessage());
2699
- }
2700
- this.hooks.afterSetup.intercept(printInformation(0));
2701
- this.hooks.afterPersist.intercept(printInformation(0));
2702
- new InitializePlugin({
2703
- build: options.build,
2704
- interactive: options.interactive,
2705
- includes: options.includes
2706
- }).apply(this);
2707
- }
2708
- context = {};
2709
- hooks = {
2710
- setup: new AsyncParallelHook(["task"]),
2711
- afterSetup: new AsyncSeriesHook(["task"]),
2712
- beforeDownload: new AsyncSeriesHook(["task"]),
2713
- download: new AsyncSeriesBailHook(["address", "moduleDefinition", "task"]),
2714
- afterDownload: new AsyncSeriesHook(["task"]),
2715
- beforeCompile: new AsyncSeriesHook(["task"]),
2716
- compile: new AsyncParallelHook(["task"]),
2717
- afterCompile: new AsyncSeriesHook(["task"]),
2718
- beforePersist: new AsyncSeriesHook(["task"]),
2719
- persist: new AsyncParallelHook(["task"]),
2720
- afterPersist: new AsyncSeriesHook(["task"]),
2721
- done: new SyncHook()
2722
- };
2723
- async run() {
2724
- const options = this.options;
2725
- const tasks = new Listr(
2726
- [
2727
- createSetupTask(this, options),
2728
- createDownloadTask(this, { skipIgnoredModules: !options.interactive }),
2729
- createCompileTask(this, { enabled: !!options.build }),
2730
- createPersistTask(this)
2731
- ],
2732
- {
2733
- concurrent: false,
2734
- renderer: "default",
2735
- rendererOptions: {
2736
- suffixSkips: true,
2737
- collapseSubtasks: false,
2738
- collapseErrors: false
2739
- }
2740
- }
2741
- );
2742
- await tasks.run(this.context);
2743
- await this.hooks.done.promise();
2744
- }
2745
- };
2746
75
 
2747
76
  // src/cli.ts
2748
77
  if (semver.lt(process.version, "20.0.0")) {
@@ -2752,6 +81,7 @@ var program = new Command();
2752
81
  program.command("build").option("-c --config <config>", "The keq-cli config file").option("--module <modules...>", "Filter module(s) to generate").option("--debug", "Print debug information").option("--tolerant", "Tolerate wrong swagger/openapi structure").option("-i --interactive", "Interactive select the scope of generation").action(async (options) => {
2753
82
  const compiler = new Compiler({
2754
83
  build: true,
84
+ persist: true,
2755
85
  config: options.config,
2756
86
  includes: options.module,
2757
87
  debug: !!options.debug,
@@ -2776,6 +106,7 @@ program.command("ignore").addArgument(
2776
106
  if (options.build) throw new Error("'--build' cannot be used with 'all' mode");
2777
107
  compiler = new Compiler({
2778
108
  build: false,
109
+ persist: true,
2779
110
  config: options.config,
2780
111
  includes: options.module,
2781
112
  debug: !!options.debug,
@@ -2797,6 +128,7 @@ program.command("ignore").addArgument(
2797
128
  }
2798
129
  compiler = new Compiler({
2799
130
  build: !!options.build,
131
+ persist: true,
2800
132
  config: options.config,
2801
133
  includes: options.module,
2802
134
  debug: !!options.debug,
@@ -2812,6 +144,7 @@ program.command("ignore").addArgument(
2812
144
  const moduleNames = options.module || ["*"];
2813
145
  compiler = new Compiler({
2814
146
  build: !!options.build,
147
+ persist: true,
2815
148
  config: options.config,
2816
149
  debug: !!options.debug,
2817
150
  includes: options.module,
@@ -2829,7 +162,111 @@ program.command("ignore").addArgument(
2829
162
  }
2830
163
  await compiler.run();
2831
164
  });
2832
- async function main5() {
165
+ program.command("list").option("-c --config <config>", "The keq-cli config file").option("--invalid", "List only invalid generated files (files not in current build)").option("--debug", "Print debug information").action(async (options) => {
166
+ const compiler = new Compiler({
167
+ build: true,
168
+ persist: false,
169
+ silent: true,
170
+ config: options.config,
171
+ includes: [],
172
+ debug: !!options.debug
173
+ });
174
+ await compiler.run();
175
+ const context = compiler.context;
176
+ if (!context.rc) {
177
+ throw new Error("Failed to load configuration");
178
+ }
179
+ if (options.invalid) {
180
+ const validFilePaths = (context.artifacts || []).map((artifact) => artifact.filepath);
181
+ const invalidFiles = await findInvalidFiles(context.rc.outdir, validFilePaths);
182
+ for (const file of invalidFiles) {
183
+ const fullPath = `./${path2.join(context.rc.outdir, file.relativePath)}`;
184
+ console.log(fullPath);
185
+ }
186
+ } else {
187
+ const artifacts = context.artifacts || [];
188
+ for (const artifact of artifacts) {
189
+ const fullPath = `./${path2.join(context.rc.outdir, artifact.filepath)}`;
190
+ console.log(fullPath);
191
+ }
192
+ }
193
+ });
194
+ program.command("apis").option("-c --config <config>", "The keq-cli config file").option("--module <modules...>", "Filter module(s) to list").addOption(
195
+ new Option("--includes <includes...>", "Include specific parts").choices(["operations", "components"])
196
+ ).option("--json", "Output in JSON format").option("--debug", "Print debug information").action(async (options) => {
197
+ const compiler = new Compiler({
198
+ build: true,
199
+ persist: false,
200
+ silent: true,
201
+ config: options.config,
202
+ includes: options.module || [],
203
+ debug: !!options.debug
204
+ });
205
+ await compiler.run();
206
+ const context = compiler.context;
207
+ const documents = context.documents || [];
208
+ const includesList = options.includes || ["operations", "components"];
209
+ const includeOperations = includesList.includes("operations");
210
+ const includeComponents = includesList.includes("components");
211
+ const result = documents.map((document) => {
212
+ const item = {
213
+ module: document.module.name
214
+ };
215
+ if (includeOperations) {
216
+ item.operations = document.operations.map((operation) => ({
217
+ method: operation.method.toUpperCase(),
218
+ path: operation.pathname,
219
+ operationId: operation.operationId
220
+ }));
221
+ }
222
+ if (includeComponents) {
223
+ item.components = {
224
+ schemas: document.schemas.map((schema) => ({
225
+ name: schema.name
226
+ }))
227
+ };
228
+ }
229
+ return item;
230
+ });
231
+ if (options.json) {
232
+ console.log(JSON.stringify(result, null, 2));
233
+ } else {
234
+ for (const item of result) {
235
+ console.log(`
236
+ Module: ${item.module}`);
237
+ console.log("\u2500".repeat(70));
238
+ if (includeOperations) {
239
+ console.log("\n APIs:");
240
+ if (!item.operations || item.operations.length === 0) {
241
+ console.log(" (No APIs)");
242
+ } else {
243
+ for (const operation of item.operations) {
244
+ const method = operation.method.padEnd(7);
245
+ console.log(` ${method} ${operation.path}`);
246
+ }
247
+ }
248
+ }
249
+ if (includeComponents) {
250
+ console.log("\n Schemas:");
251
+ if (!item.components || item.components.schemas.length === 0) {
252
+ console.log(" (No Schemas)");
253
+ } else {
254
+ for (const schema of item.components.schemas) {
255
+ console.log(` ${schema.name}`);
256
+ }
257
+ }
258
+ }
259
+ }
260
+ const totalApis = result.reduce((sum, item) => sum + (item.operations?.length || 0), 0);
261
+ const totalSchemas = result.reduce((sum, item) => sum + (item.components?.schemas.length || 0), 0);
262
+ console.log("\n" + "\u2500".repeat(70));
263
+ const parts = [`${result.length} modules`];
264
+ if (includeOperations) parts.push(`${totalApis} APIs`);
265
+ if (includeComponents) parts.push(`${totalSchemas} Schemas`);
266
+ console.log(`Total: ${parts.join(", ")}`);
267
+ }
268
+ });
269
+ async function main() {
2833
270
  program.on("command:*", function(operands) {
2834
271
  throw new Error(`Unknown command '${String(operands[0])}'`);
2835
272
  });
@@ -2843,5 +280,5 @@ async function main5() {
2843
280
  }
2844
281
  }
2845
282
  }
2846
- void main5();
283
+ void main();
2847
284
  //# sourceMappingURL=cli.js.map