@keq-request/cli 5.0.0-alpha.28 → 5.0.0-alpha.30

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