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