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