@moccona/apicodegen 0.1.2 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +312 -29
- package/bin/cli.cjs +9 -6
- package/npm/index.cjs +1279 -311
- package/npm/index.cjs.map +1 -1
- package/npm/index.d.cts +293 -51
- package/npm/index.d.cts.map +1 -1
- package/npm/index.d.mts +293 -51
- package/npm/index.d.mts.map +1 -1
- package/npm/index.mjs +1271 -310
- package/npm/index.mjs.map +1 -1
- package/npm/vite/index.d.mts +27 -10
- package/npm/vite/index.d.mts.map +1 -1
- package/npm/vite/index.mjs +1259 -306
- package/npm/vite/index.mjs.map +1 -1
- package/package.json +36 -20
package/npm/vite/index.mjs
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
|
-
import path from "node:path";
|
|
1
|
+
import path, { dirname, join } from "node:path";
|
|
2
2
|
import { createScopedLogger } from "@moccona/logger";
|
|
3
3
|
import fs from "fs-extra";
|
|
4
|
-
import {
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { execaCommand } from "execa";
|
|
6
|
+
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
7
|
+
import { NodeFlags, SyntaxKind, addSyntheticLeadingComment, createPrinter, factory, isEnumDeclaration, isInterfaceDeclaration, isTypeAliasDeclaration } from "typescript";
|
|
5
8
|
import { Agent, request } from "undici";
|
|
6
|
-
import {
|
|
9
|
+
import { parse } from "yaml";
|
|
7
10
|
import { format } from "prettier";
|
|
8
11
|
import { createHash } from "node:crypto";
|
|
9
|
-
|
|
12
|
+
// src/core/interface.ts
|
|
10
13
|
let MediaTypes = /* @__PURE__ */ function(MediaTypes) {
|
|
11
14
|
MediaTypes["JSON"] = "application/json";
|
|
12
15
|
MediaTypes["TEXT"] = "text";
|
|
@@ -31,12 +34,11 @@ let Adaptors = /* @__PURE__ */ function(Adaptors) {
|
|
|
31
34
|
Adaptors["axios"] = "axios";
|
|
32
35
|
return Adaptors;
|
|
33
36
|
}({});
|
|
34
|
-
|
|
35
|
-
//#region src/core/config.ts
|
|
37
|
+
// src/core/config.ts
|
|
36
38
|
/**
|
|
37
39
|
* Strings considered truthy for boolean env vars (verbose/watch/typeCheck).
|
|
38
40
|
*/
|
|
39
|
-
const TRUTHY_STRINGS = new Set([
|
|
41
|
+
const TRUTHY_STRINGS = /* @__PURE__ */ new Set([
|
|
40
42
|
"true",
|
|
41
43
|
"1",
|
|
42
44
|
"yes",
|
|
@@ -53,7 +55,10 @@ const ENV_MAPPINGS = {
|
|
|
53
55
|
APICODEGEN_ADAPTOR: "adaptor",
|
|
54
56
|
APICODEGEN_VERBOSE: "verbose",
|
|
55
57
|
APICODEGEN_WATCH: "watch",
|
|
56
|
-
APICODEGEN_TYPE_CHECK: "typeCheck"
|
|
58
|
+
APICODEGEN_TYPE_CHECK: "typeCheck",
|
|
59
|
+
APICODEGEN_CHECK: "check",
|
|
60
|
+
APICODEGEN_ERROR_MODE: "errorMode",
|
|
61
|
+
APICODEGEN_SPLIT_BY: "splitBy"
|
|
57
62
|
};
|
|
58
63
|
/**
|
|
59
64
|
* Load config from environment variables
|
|
@@ -66,19 +71,23 @@ function loadFromEnv() {
|
|
|
66
71
|
case "verbose":
|
|
67
72
|
case "watch":
|
|
68
73
|
case "typeCheck":
|
|
74
|
+
case "check":
|
|
69
75
|
config[configKey] = TRUTHY_STRINGS.has(value.toLowerCase());
|
|
70
76
|
break;
|
|
71
77
|
case "adaptor":
|
|
72
78
|
if (Object.values(Adaptors).includes(value)) config[configKey] = value;
|
|
73
79
|
break;
|
|
80
|
+
case "errorMode":
|
|
81
|
+
if (value === "throw" || value === "result") config.errorMode = value;
|
|
82
|
+
break;
|
|
83
|
+
case "splitBy":
|
|
84
|
+
if (value === "tag") config.splitBy = value;
|
|
85
|
+
break;
|
|
74
86
|
default: config[configKey] = value;
|
|
75
87
|
}
|
|
76
88
|
}
|
|
77
89
|
return config;
|
|
78
90
|
}
|
|
79
|
-
/**
|
|
80
|
-
* Load config from a file
|
|
81
|
-
*/
|
|
82
91
|
async function loadFromFile(filePath) {
|
|
83
92
|
const ext = path.extname(filePath).toLowerCase();
|
|
84
93
|
try {
|
|
@@ -87,17 +96,16 @@ async function loadFromFile(filePath) {
|
|
|
87
96
|
return JSON.parse(content);
|
|
88
97
|
}
|
|
89
98
|
if (ext === ".js" || ext === ".cjs" || ext === ".mjs") {
|
|
90
|
-
const mod = await import(filePath);
|
|
99
|
+
const mod = await import(pathToFileURL(filePath).href);
|
|
91
100
|
return mod.default || mod;
|
|
92
101
|
}
|
|
93
|
-
if (ext === ".ts") {
|
|
102
|
+
if (ext === ".ts" || ext === ".mts" || ext === ".cts") {
|
|
94
103
|
const content = await fs.readFile(filePath, "utf-8");
|
|
95
104
|
try {
|
|
96
105
|
return JSON.parse(content);
|
|
97
|
-
} catch {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
}
|
|
106
|
+
} catch {}
|
|
107
|
+
const mod = await import(pathToFileURL(filePath).href);
|
|
108
|
+
return mod.default || mod;
|
|
101
109
|
}
|
|
102
110
|
const content = await fs.readFile(filePath, "utf-8");
|
|
103
111
|
return JSON.parse(content);
|
|
@@ -113,10 +121,13 @@ async function findConfigFile(cwd) {
|
|
|
113
121
|
"apicodegen.config.json",
|
|
114
122
|
"apicodegen.config.js",
|
|
115
123
|
"apicodegen.config.mjs",
|
|
124
|
+
"apicodegen.config.ts",
|
|
125
|
+
"apicodegen.config.mts",
|
|
116
126
|
".apicodegenrc",
|
|
117
127
|
".apicodegenrc.json",
|
|
118
128
|
".apicodegenrc.js",
|
|
119
|
-
".apicodegenrc.mjs"
|
|
129
|
+
".apicodegenrc.mjs",
|
|
130
|
+
".apicodegenrc.ts"
|
|
120
131
|
]) {
|
|
121
132
|
const filePath = path.join(cwd, fileName);
|
|
122
133
|
if (await fs.pathExists(filePath)) return filePath;
|
|
@@ -141,6 +152,35 @@ function mergeConfigs(base, ...sources) {
|
|
|
141
152
|
return result;
|
|
142
153
|
}
|
|
143
154
|
/**
|
|
155
|
+
* Validate field types before the values reach the generator.
|
|
156
|
+
*/
|
|
157
|
+
function validateConfigShape(config) {
|
|
158
|
+
const fail = (key, expected) => {
|
|
159
|
+
throw new Error(`Invalid config field "${key}": expected ${expected}`);
|
|
160
|
+
};
|
|
161
|
+
if (config.spec !== void 0 && typeof config.spec !== "string") fail("spec", "a string");
|
|
162
|
+
if (config.output !== void 0 && typeof config.output !== "string") fail("output", "a string");
|
|
163
|
+
for (const key of [
|
|
164
|
+
"verbose",
|
|
165
|
+
"watch",
|
|
166
|
+
"typeCheck",
|
|
167
|
+
"check"
|
|
168
|
+
]) if (config[key] !== void 0 && typeof config[key] !== "boolean") fail(key, "a boolean");
|
|
169
|
+
if (config.adaptor !== void 0 && !Object.values(Adaptors).includes(config.adaptor)) fail("adaptor", Object.values(Adaptors).join(" or "));
|
|
170
|
+
if (config.errorMode !== void 0 && config.errorMode !== "throw" && config.errorMode !== "result") fail("errorMode", "throw or result");
|
|
171
|
+
if (config.splitBy !== void 0 && config.splitBy !== "tag") fail("splitBy", "tag");
|
|
172
|
+
for (const key of [
|
|
173
|
+
"includeTags",
|
|
174
|
+
"excludeTags",
|
|
175
|
+
"includePaths",
|
|
176
|
+
"excludePaths"
|
|
177
|
+
]) {
|
|
178
|
+
const value = config[key];
|
|
179
|
+
if (value !== void 0 && (!Array.isArray(value) || value.some((item) => typeof item !== "string"))) fail(key, "an array of strings");
|
|
180
|
+
}
|
|
181
|
+
if (config.requestOptions !== void 0 && (typeof config.requestOptions !== "object" || config.requestOptions === null || Array.isArray(config.requestOptions))) fail("requestOptions", "an object");
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
144
184
|
* Validate config has required fields
|
|
145
185
|
*/
|
|
146
186
|
function validateConfig(config) {
|
|
@@ -148,9 +188,10 @@ function validateConfig(config) {
|
|
|
148
188
|
return true;
|
|
149
189
|
}
|
|
150
190
|
/**
|
|
151
|
-
* Load and resolve config
|
|
191
|
+
* Load and resolve every config entry. A config file may define a single
|
|
192
|
+
* object or a `specs` array for multi-spec projects.
|
|
152
193
|
*/
|
|
153
|
-
async function
|
|
194
|
+
async function loadConfigs(options = {}) {
|
|
154
195
|
const cwd = options.cwd || process.cwd();
|
|
155
196
|
const cliOptions = options.cliOptions || {};
|
|
156
197
|
const envConfig = loadFromEnv();
|
|
@@ -172,17 +213,34 @@ async function loadConfig(options = {}) {
|
|
|
172
213
|
const pkg = JSON.parse(await fs.readFile(packageJsonPath, "utf-8"));
|
|
173
214
|
if (pkg.apicodegen && typeof pkg.apicodegen === "object") inlineConfig = pkg.apicodegen;
|
|
174
215
|
} catch {}
|
|
175
|
-
const
|
|
216
|
+
const { specs, ...fileOptions } = fileConfig;
|
|
217
|
+
const entries = Array.isArray(specs) && specs.length > 0 ? specs.map((entry) => mergeConfigs({
|
|
176
218
|
spec: "",
|
|
177
219
|
output: "./output.ts"
|
|
178
|
-
},
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
220
|
+
}, fileOptions, entry)) : [fileOptions];
|
|
221
|
+
const sharedCliOptions = entries.length === 1 ? cliOptions : Object.fromEntries(Object.entries(cliOptions).filter(([key]) => key !== "spec" && key !== "output"));
|
|
222
|
+
return entries.map((entry, index) => {
|
|
223
|
+
const merged = mergeConfigs({
|
|
224
|
+
spec: "",
|
|
225
|
+
output: "./output.ts"
|
|
226
|
+
}, envConfig, inlineConfig, entry, sharedCliOptions);
|
|
227
|
+
validateConfigShape(merged);
|
|
228
|
+
validateConfig(merged);
|
|
229
|
+
const name = options.name || merged.name || merged.baseURL || merged.spec || `api-${index + 1}`;
|
|
230
|
+
return {
|
|
231
|
+
...merged,
|
|
232
|
+
configFilePath,
|
|
233
|
+
name
|
|
234
|
+
};
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Load a single config. Throws when the file defines no entries.
|
|
239
|
+
*/
|
|
240
|
+
async function loadConfig(options = {}) {
|
|
241
|
+
const config = (await loadConfigs(options))[0];
|
|
242
|
+
if (!config) throw new Error("No API configs found");
|
|
243
|
+
return config;
|
|
186
244
|
}
|
|
187
245
|
/**
|
|
188
246
|
* Convert resolved config to provider options format
|
|
@@ -195,11 +253,16 @@ function toProviderOptions(config) {
|
|
|
195
253
|
baseURL: config.baseURL,
|
|
196
254
|
importClientSource: config.importClientSource,
|
|
197
255
|
verbose: config.verbose,
|
|
198
|
-
requestOptions: config.requestOptions
|
|
256
|
+
requestOptions: config.requestOptions,
|
|
257
|
+
errorMode: config.errorMode,
|
|
258
|
+
splitBy: config.splitBy,
|
|
259
|
+
includeTags: config.includeTags,
|
|
260
|
+
excludeTags: config.excludeTags,
|
|
261
|
+
includePaths: config.includePaths,
|
|
262
|
+
excludePaths: config.excludePaths
|
|
199
263
|
};
|
|
200
264
|
}
|
|
201
|
-
|
|
202
|
-
//#region src/core/errors.ts
|
|
265
|
+
// src/core/errors.ts
|
|
203
266
|
/**
|
|
204
267
|
* Error handling utilities for api-codegen
|
|
205
268
|
*/
|
|
@@ -389,6 +452,15 @@ const createErrors = {
|
|
|
389
452
|
cause
|
|
390
453
|
});
|
|
391
454
|
},
|
|
455
|
+
writeFailed(path, cause) {
|
|
456
|
+
return new ApicodegenError({
|
|
457
|
+
code: ErrorCodes.GENERATION_FAILED,
|
|
458
|
+
message: "Failed to write generated code",
|
|
459
|
+
location: path,
|
|
460
|
+
suggestions: ["Check that the output path is writable", "Ensure the output directory can be created"],
|
|
461
|
+
cause
|
|
462
|
+
});
|
|
463
|
+
},
|
|
392
464
|
typeCheckFailed(path, _errors, cause) {
|
|
393
465
|
return new ApicodegenError({
|
|
394
466
|
code: ErrorCodes.TYPE_CHECK_FAILED,
|
|
@@ -436,16 +508,23 @@ function wrapError(error, context) {
|
|
|
436
508
|
function isApicodegenError(error) {
|
|
437
509
|
return error instanceof ApicodegenError;
|
|
438
510
|
}
|
|
439
|
-
|
|
440
|
-
//#region src/core/base/Adaptor.ts
|
|
511
|
+
// src/core/typecheck.ts
|
|
441
512
|
/**
|
|
442
|
-
*
|
|
443
|
-
*
|
|
513
|
+
* Type-check a generated file with the project's TypeScript.
|
|
514
|
+
*
|
|
515
|
+
* @param filePath - Path to the generated file.
|
|
516
|
+
* @returns Collected error messages; an empty array means success.
|
|
444
517
|
*/
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
518
|
+
async function runTypeCheck(filePath) {
|
|
519
|
+
try {
|
|
520
|
+
await execaCommand(`npx tsc ${filePath} --noEmit`, { shell: true });
|
|
521
|
+
return [];
|
|
522
|
+
} catch (error) {
|
|
523
|
+
return [error instanceof Error ? error.message : String(error)];
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
// src/core/constants/keywords.ts
|
|
527
|
+
const typescriptKeywords = /* @__PURE__ */ new Set([
|
|
449
528
|
"break",
|
|
450
529
|
"case",
|
|
451
530
|
"catch",
|
|
@@ -521,8 +600,7 @@ const typescriptKeywords = new Set([
|
|
|
521
600
|
"undefined",
|
|
522
601
|
"bigint"
|
|
523
602
|
]);
|
|
524
|
-
|
|
525
|
-
//#region src/core/base/Base.ts
|
|
603
|
+
// src/core/base/Base.ts
|
|
526
604
|
/**
|
|
527
605
|
* @file Base class implementation
|
|
528
606
|
* @author wp.l
|
|
@@ -577,6 +655,17 @@ var Base = class Base {
|
|
|
577
655
|
return name + suffix;
|
|
578
656
|
}
|
|
579
657
|
/**
|
|
658
|
+
* Converts arbitrary text into a legal TypeScript variable identifier.
|
|
659
|
+
* Keywords keep the `_` suffix that `normalize` adds, since `camelCase`
|
|
660
|
+
* would otherwise strip it and emit a reserved word.
|
|
661
|
+
* @param text - Input text.
|
|
662
|
+
* @returns - A legal identifier.
|
|
663
|
+
*/
|
|
664
|
+
static toIdentifier(text) {
|
|
665
|
+
const name = Base.camelCase(Base.normalize(text));
|
|
666
|
+
return typescriptKeywords.has(name) ? `${name}_` : name;
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
580
669
|
* Normalizes a string by replacing special characters and avoiding TypeScript keywords.
|
|
581
670
|
* @param text - Input text to normalize.
|
|
582
671
|
* @returns - The normalized string.
|
|
@@ -690,18 +779,39 @@ var Base = class Base {
|
|
|
690
779
|
if (error?.code === "ENOENT") throw createErrors.specNotFound(filePath, error);
|
|
691
780
|
throw new Error(`Failed to read OpenAPI spec from ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
692
781
|
}
|
|
782
|
+
return Base.parseDoc(raw, filePath);
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* Parses an OpenAPI document from JSON or YAML text.
|
|
786
|
+
*
|
|
787
|
+
* JSON is attempted first for a clearer syntax error on JSON files; YAML
|
|
788
|
+
* then handles `.yaml` / `.yml` specs. Any failure is reported as
|
|
789
|
+
* `E_SPEC_PARSE_FAILED` with the source path attached.
|
|
790
|
+
*
|
|
791
|
+
* @param raw - Raw spec content.
|
|
792
|
+
* @param source - Path or URL used in error messages.
|
|
793
|
+
* @returns - The parsed document.
|
|
794
|
+
*/
|
|
795
|
+
static parseDoc(raw, source) {
|
|
796
|
+
let parsed;
|
|
693
797
|
try {
|
|
694
|
-
|
|
695
|
-
} catch
|
|
696
|
-
|
|
798
|
+
parsed = JSON.parse(raw);
|
|
799
|
+
} catch {
|
|
800
|
+
try {
|
|
801
|
+
parsed = parse(raw);
|
|
802
|
+
} catch (error) {
|
|
803
|
+
throw createErrors.specParseFailed(source, void 0, void 0, error);
|
|
804
|
+
}
|
|
697
805
|
}
|
|
806
|
+
if (parsed === null || typeof parsed !== "object") throw createErrors.specParseFailed(source, void 0, void 0, /* @__PURE__ */ new Error("Spec must be a JSON or YAML object"));
|
|
807
|
+
return parsed;
|
|
698
808
|
}
|
|
699
809
|
/**
|
|
700
810
|
* Fetches documentation from a given URL.
|
|
701
811
|
*
|
|
702
812
|
* Supports three transport modes:
|
|
703
|
-
* - `file://...` URLs → read from filesystem (
|
|
704
|
-
* - absolute filesystem paths → read from filesystem (
|
|
813
|
+
* - `file://...` URLs → read from filesystem (JSON or YAML)
|
|
814
|
+
* - absolute filesystem paths → read from filesystem (JSON or YAML)
|
|
705
815
|
* - `http(s)://...` URLs (and unrecognised inputs like relative paths)
|
|
706
816
|
* → fetched via undici (existing behavior)
|
|
707
817
|
*
|
|
@@ -711,22 +821,139 @@ var Base = class Base {
|
|
|
711
821
|
*
|
|
712
822
|
* @param url - The URL or filesystem path to fetch the documentation from.
|
|
713
823
|
* @param requestInit - Additional request parameters (only used for http(s)).
|
|
824
|
+
* TLS certificates are verified by default; set `insecure: true` to opt out.
|
|
714
825
|
* @returns - A promise resolving to the fetched documentation data.
|
|
715
826
|
*/
|
|
716
827
|
static async fetchDoc(url, requestInit = {}) {
|
|
717
828
|
const { transport, source } = Base.resolveSpecURL(url);
|
|
718
829
|
if (transport === "file") return Base.readLocalDoc(source);
|
|
830
|
+
const { insecure = false, ...init } = requestInit;
|
|
719
831
|
const { body, statusCode } = await request(source, {
|
|
720
832
|
method: "GET",
|
|
721
|
-
dispatcher: new Agent({ connect: { rejectUnauthorized: false } }),
|
|
722
|
-
...
|
|
833
|
+
...insecure ? { dispatcher: new Agent({ connect: { rejectUnauthorized: false } }) } : {},
|
|
834
|
+
...init
|
|
723
835
|
});
|
|
724
836
|
if (statusCode >= 400) throw new Error(`Failed to fetch OpenAPI documentation from ${source}: HTTP ${statusCode}`);
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
837
|
+
return Base.parseDoc(await body.text(), source);
|
|
838
|
+
}
|
|
839
|
+
/**
|
|
840
|
+
* Copies external `$ref` targets (other files or remote URLs) into the root
|
|
841
|
+
* document and rewrites the refs to local ones. Objects are registered
|
|
842
|
+
* before their children are walked, so cycles keep working.
|
|
843
|
+
*
|
|
844
|
+
* External refs are placed in the component section implied by their
|
|
845
|
+
* fragment (`schemas` by default); a generated local `$ref` points at the
|
|
846
|
+
* copy.
|
|
847
|
+
*
|
|
848
|
+
* @param doc - Parsed root document (mutated in place).
|
|
849
|
+
* @param source - Absolute path or URL of the root document.
|
|
850
|
+
* @param requestInit - Request options for remote refs.
|
|
851
|
+
* @returns - The same document with external refs resolved.
|
|
852
|
+
*/
|
|
853
|
+
static async bundleExternalRefs(doc, source, requestInit = {}) {
|
|
854
|
+
const root = doc;
|
|
855
|
+
const isV2 = typeof root.swagger === "string";
|
|
856
|
+
const rootURL = Base.resolveSpecURL(source).transport === "file" ? pathToFileURL(source).href : source;
|
|
857
|
+
const docs = /* @__PURE__ */ new Map([[rootURL, root]]);
|
|
858
|
+
const registered = /* @__PURE__ */ new Map();
|
|
859
|
+
const loadDoc = async (url) => {
|
|
860
|
+
const cached = docs.get(url);
|
|
861
|
+
if (cached !== void 0) return cached;
|
|
862
|
+
const loaded = await Base.fetchDoc(url, requestInit);
|
|
863
|
+
docs.set(url, loaded);
|
|
864
|
+
return loaded;
|
|
865
|
+
};
|
|
866
|
+
const containerFor = (ref) => {
|
|
867
|
+
const section = Base.externalRefSection(ref, isV2);
|
|
868
|
+
if (isV2) {
|
|
869
|
+
root[section] ??= {};
|
|
870
|
+
return {
|
|
871
|
+
record: root[section],
|
|
872
|
+
prefix: `#/${section}/`
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
root.components ??= {};
|
|
876
|
+
root.components[section] ??= {};
|
|
877
|
+
return {
|
|
878
|
+
record: root.components[section],
|
|
879
|
+
prefix: `#/components/${section}/`
|
|
880
|
+
};
|
|
881
|
+
};
|
|
882
|
+
const register = async (absolute) => {
|
|
883
|
+
const existing = registered.get(absolute);
|
|
884
|
+
if (existing) return existing;
|
|
885
|
+
const hashIndex = absolute.indexOf("#");
|
|
886
|
+
const docURL = hashIndex === -1 ? absolute : absolute.slice(0, hashIndex);
|
|
887
|
+
const fragment = hashIndex === -1 ? "" : absolute.slice(hashIndex);
|
|
888
|
+
const externalDoc = await loadDoc(docURL);
|
|
889
|
+
const { record, prefix } = containerFor(fragment);
|
|
890
|
+
const target = Base.resolveJSONPointer(externalDoc, fragment);
|
|
891
|
+
if (target === void 0) return `${prefix}unknown`;
|
|
892
|
+
const baseName = Base.externalRefName(fragment, docURL);
|
|
893
|
+
let name = baseName;
|
|
894
|
+
let suffix = 2;
|
|
895
|
+
while (name in record) {
|
|
896
|
+
name = `${baseName}${suffix}`;
|
|
897
|
+
suffix++;
|
|
898
|
+
}
|
|
899
|
+
registered.set(absolute, prefix + name);
|
|
900
|
+
record[name] = target;
|
|
901
|
+
await walk(target, docURL);
|
|
902
|
+
return prefix + name;
|
|
903
|
+
};
|
|
904
|
+
const walk = async (value, docURL) => {
|
|
905
|
+
if (Array.isArray(value)) {
|
|
906
|
+
for (const item of value) await walk(item, docURL);
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
if (value === null || typeof value !== "object") return;
|
|
910
|
+
const object = value;
|
|
911
|
+
if (typeof object.$ref === "string") {
|
|
912
|
+
const ref = object.$ref;
|
|
913
|
+
if (ref.startsWith("#") && docURL === rootURL) return;
|
|
914
|
+
const absolute = ref.startsWith("#") ? docURL + ref : new URL(ref, docURL).href;
|
|
915
|
+
if ((docURL.startsWith("http://") || docURL.startsWith("https://")) && !absolute.startsWith("http://") && !absolute.startsWith("https://")) throw new Error(`Refusing to resolve external $ref from a remote document: ${absolute}`);
|
|
916
|
+
object.$ref = await register(absolute);
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
for (const key of Object.keys(object)) await walk(object[key], docURL);
|
|
920
|
+
};
|
|
921
|
+
await walk(root, rootURL);
|
|
922
|
+
return doc;
|
|
923
|
+
}
|
|
924
|
+
/** Component section an external ref belongs to. */
|
|
925
|
+
static externalRefSection(ref, isV2) {
|
|
926
|
+
if (isV2) {
|
|
927
|
+
if (ref.includes("/parameters/")) return "parameters";
|
|
928
|
+
if (ref.includes("/responses/")) return "responses";
|
|
929
|
+
return "definitions";
|
|
729
930
|
}
|
|
931
|
+
if (ref.includes("/parameters/")) return "parameters";
|
|
932
|
+
if (ref.includes("/responses/")) return "responses";
|
|
933
|
+
if (ref.includes("/requestBodies/")) return "requestBodies";
|
|
934
|
+
return "schemas";
|
|
935
|
+
}
|
|
936
|
+
/** Local component name derived from the ref fragment or file name. */
|
|
937
|
+
static externalRefName(fragment, docURL) {
|
|
938
|
+
let name = fragment.replace(/^#/, "").split("/").filter(Boolean).map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")).at(-1) ?? "";
|
|
939
|
+
if (!name) try {
|
|
940
|
+
name = new URL(docURL).pathname.split("/").pop() ?? "";
|
|
941
|
+
} catch {
|
|
942
|
+
name = "";
|
|
943
|
+
}
|
|
944
|
+
name = name.replace(/\.(json|ya?ml)$/i, "").replace(/[^A-Za-z0-9_.-]/g, "_");
|
|
945
|
+
return name || "External";
|
|
946
|
+
}
|
|
947
|
+
/** Resolves a `#/a/b` JSON pointer inside a parsed document. */
|
|
948
|
+
static resolveJSONPointer(doc, fragment) {
|
|
949
|
+
if (!fragment) return doc;
|
|
950
|
+
const parts = fragment.replace(/^#\/?/, "").split("/").filter(Boolean).map((part) => decodeURIComponent(part).replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
951
|
+
let current = doc;
|
|
952
|
+
for (const part of parts) {
|
|
953
|
+
if (current === null || typeof current !== "object") return void 0;
|
|
954
|
+
current = current[part];
|
|
955
|
+
}
|
|
956
|
+
return current;
|
|
730
957
|
}
|
|
731
958
|
/**
|
|
732
959
|
* Determines the media type from a given media type string.
|
|
@@ -796,8 +1023,72 @@ var Base = class Base {
|
|
|
796
1023
|
return typeof schema === "object" && schema !== null && "$ref" in schema && typeof schema.$ref === "string";
|
|
797
1024
|
}
|
|
798
1025
|
};
|
|
799
|
-
|
|
800
|
-
|
|
1026
|
+
// src/core/base/Adaptor.ts
|
|
1027
|
+
/** `options?.name` */
|
|
1028
|
+
function optionalAccess(control, name) {
|
|
1029
|
+
return factory.createPropertyAccessChain(factory.createIdentifier(control.name), factory.createToken(SyntaxKind.QuestionDotToken), factory.createIdentifier(name));
|
|
1030
|
+
}
|
|
1031
|
+
/**
|
|
1032
|
+
* `options?.signal && options?.timeout ? AbortSignal.any([...]) : ...`,
|
|
1033
|
+
* combining a caller signal with a timeout when both are present.
|
|
1034
|
+
*/
|
|
1035
|
+
function fetchSignalExpression(control) {
|
|
1036
|
+
const signal = optionalAccess(control, "signal");
|
|
1037
|
+
const timeout = optionalAccess(control, "timeout");
|
|
1038
|
+
const timeoutSignal = () => factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("AbortSignal"), factory.createIdentifier("timeout")), void 0, [timeout]);
|
|
1039
|
+
const both = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("AbortSignal"), factory.createIdentifier("any")), void 0, [factory.createArrayLiteralExpression([signal, timeoutSignal()])]);
|
|
1040
|
+
return factory.createConditionalExpression(signal, factory.createToken(SyntaxKind.QuestionToken), factory.createConditionalExpression(timeout, factory.createToken(SyntaxKind.QuestionToken), both, factory.createToken(SyntaxKind.ColonToken), signal), factory.createToken(SyntaxKind.ColonToken), factory.createConditionalExpression(timeout, factory.createToken(SyntaxKind.QuestionToken), timeoutSignal(), factory.createToken(SyntaxKind.ColonToken), factory.createIdentifier("undefined")));
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Header entries plus a spread of caller-supplied headers.
|
|
1044
|
+
*/
|
|
1045
|
+
function withRequestHeaders(entries, control) {
|
|
1046
|
+
if (!control) return entries;
|
|
1047
|
+
return [...entries, factory.createSpreadAssignment(optionalAccess(control, "headers"))];
|
|
1048
|
+
}
|
|
1049
|
+
/** `auth?.["scheme"]` */
|
|
1050
|
+
function authAccess(auth, scheme) {
|
|
1051
|
+
return factory.createElementAccessChain(factory.createIdentifier(auth.name), factory.createToken(SyntaxKind.QuestionDotToken), factory.createStringLiteral(scheme));
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* Header entries (conditional spreads) for auth schemes sent as headers.
|
|
1055
|
+
*/
|
|
1056
|
+
function authHeaderEntries(auth) {
|
|
1057
|
+
return auth.injections.filter((injection) => injection.location === "header").map((injection) => {
|
|
1058
|
+
const access = authAccess(auth, injection.scheme);
|
|
1059
|
+
const hasValue = factory.createBinaryExpression(access, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword));
|
|
1060
|
+
let value;
|
|
1061
|
+
let condition = hasValue;
|
|
1062
|
+
if (injection.kind === "basic") {
|
|
1063
|
+
condition = factory.createBinaryExpression(access, factory.createToken(SyntaxKind.AmpersandAmpersandToken), factory.createBinaryExpression(factory.createTypeOfExpression(access), factory.createToken(SyntaxKind.EqualsEqualsEqualsToken), factory.createStringLiteral("object")));
|
|
1064
|
+
const credentials = factory.createTemplateExpression(factory.createTemplateHead(""), [factory.createTemplateSpan(factory.createPropertyAccessExpression(access, "username"), factory.createTemplateMiddle(":")), factory.createTemplateSpan(factory.createPropertyAccessExpression(access, "password"), factory.createTemplateTail(""))]);
|
|
1065
|
+
value = factory.createTemplateExpression(factory.createTemplateHead("Basic "), [factory.createTemplateSpan(factory.createCallExpression(factory.createIdentifier("btoa"), void 0, [credentials]), factory.createTemplateTail(""))]);
|
|
1066
|
+
} else if (injection.kind === "bearer") value = factory.createTemplateExpression(factory.createTemplateHead("Bearer "), [factory.createTemplateSpan(factory.createCallExpression(factory.createIdentifier("String"), void 0, [access]), factory.createTemplateTail(""))]);
|
|
1067
|
+
else value = factory.createCallExpression(factory.createIdentifier("String"), void 0, [access]);
|
|
1068
|
+
return factory.createSpreadAssignment(factory.createConditionalExpression(condition, factory.createToken(SyntaxKind.QuestionToken), factory.createObjectLiteralExpression([factory.createPropertyAssignment(factory.createStringLiteral(injection.name), value)], false), factory.createToken(SyntaxKind.ColonToken), factory.createObjectLiteralExpression([], false)));
|
|
1069
|
+
});
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* Builds a `Cookie` header value from OpenAPI cookie parameters.
|
|
1073
|
+
* Undefined/null values are filtered out at runtime.
|
|
1074
|
+
*/
|
|
1075
|
+
function cookieHeaderExpression(parameters, auth) {
|
|
1076
|
+
const entries = parameters.filter((p) => p.in === "cookie").map((parameter) => {
|
|
1077
|
+
const id = factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
1078
|
+
return factory.createConditionalExpression(factory.createBinaryExpression(id, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createToken(SyntaxKind.QuestionToken), factory.createTemplateExpression(factory.createTemplateHead(`${parameter.name}=`), [factory.createTemplateSpan(factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [id])]), factory.createTemplateTail(""))]), factory.createToken(SyntaxKind.ColonToken), factory.createStringLiteral(""));
|
|
1079
|
+
});
|
|
1080
|
+
const authEntries = auth ? auth.injections.filter((injection) => injection.location === "cookie").map((injection) => {
|
|
1081
|
+
const access = authAccess(auth, injection.scheme);
|
|
1082
|
+
return factory.createConditionalExpression(factory.createBinaryExpression(access, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createToken(SyntaxKind.QuestionToken), factory.createTemplateExpression(factory.createTemplateHead(`${injection.name}=`), [factory.createTemplateSpan(factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [access])]), factory.createTemplateTail(""))]), factory.createToken(SyntaxKind.ColonToken), factory.createStringLiteral(""));
|
|
1083
|
+
}) : [];
|
|
1084
|
+
return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createArrayLiteralExpression([...entries, ...authEntries], true), factory.createIdentifier("filter")), void 0, [factory.createIdentifier("Boolean")]), factory.createIdentifier("join")), void 0, [factory.createStringLiteral("; ")]);
|
|
1085
|
+
}
|
|
1086
|
+
/**
|
|
1087
|
+
* Base adapter for tool
|
|
1088
|
+
* This abstract class serves as the foundation for implementing adapters for different code generation tools
|
|
1089
|
+
*/
|
|
1090
|
+
var Adapter = class {};
|
|
1091
|
+
// src/core/base/Provider.ts
|
|
801
1092
|
/**
|
|
802
1093
|
* Abstract Provider Class.
|
|
803
1094
|
*
|
|
@@ -841,6 +1132,8 @@ var Provider = class {
|
|
|
841
1132
|
responses = {};
|
|
842
1133
|
/** collection of request bodies indexed by name */
|
|
843
1134
|
requestBodies = {};
|
|
1135
|
+
/** security schemes declared by the document */
|
|
1136
|
+
securitySchemes = {};
|
|
844
1137
|
/** collection of API endpoints (operations) indexed by path */
|
|
845
1138
|
apis = {};
|
|
846
1139
|
/** URL for fetching API documentation */
|
|
@@ -864,17 +1157,17 @@ var Provider = class {
|
|
|
864
1157
|
this.output = initOptions.output ?? ".";
|
|
865
1158
|
this.requestOptions = initOptions.requestOptions ?? {};
|
|
866
1159
|
this.importClientSource = initOptions.importClientSource ?? "";
|
|
867
|
-
const { enums, schemas, requestBodies, responses, parameters, apis } = this.parse(doc);
|
|
1160
|
+
const { enums, schemas, requestBodies, responses, parameters, securitySchemes, apis } = this.parse(doc);
|
|
868
1161
|
this.enums = enums;
|
|
869
1162
|
this.schemas = schemas;
|
|
870
1163
|
this.responses = responses;
|
|
871
1164
|
this.parameters = parameters;
|
|
872
1165
|
this.requestBodies = requestBodies;
|
|
1166
|
+
this.securitySchemes = securitySchemes;
|
|
873
1167
|
this.apis = apis;
|
|
874
1168
|
}
|
|
875
1169
|
};
|
|
876
|
-
|
|
877
|
-
//#region src/core/generator/naming.ts
|
|
1170
|
+
// src/core/generator/naming.ts
|
|
878
1171
|
/**
|
|
879
1172
|
* Create a per-generation unique-name resolver.
|
|
880
1173
|
*
|
|
@@ -897,8 +1190,7 @@ const createUniqueNameResolver = () => {
|
|
|
897
1190
|
return next === 1 ? name : `${name}${next}`;
|
|
898
1191
|
};
|
|
899
1192
|
};
|
|
900
|
-
|
|
901
|
-
//#region src/core/generator/index.ts
|
|
1193
|
+
// src/core/generator/index.ts
|
|
902
1194
|
var Generator = class Generator {
|
|
903
1195
|
/**
|
|
904
1196
|
* Converts an array of TypeScript statements into a formatted string of code.
|
|
@@ -914,9 +1206,10 @@ var Generator = class Generator {
|
|
|
914
1206
|
}
|
|
915
1207
|
static async write(code, filepath) {
|
|
916
1208
|
try {
|
|
1209
|
+
await mkdir(dirname(filepath), { recursive: true });
|
|
917
1210
|
await writeFile(filepath, code);
|
|
918
1211
|
} catch (error) {
|
|
919
|
-
|
|
1212
|
+
throw createErrors.writeFailed(filepath, error instanceof Error ? error : new Error(String(error)));
|
|
920
1213
|
}
|
|
921
1214
|
}
|
|
922
1215
|
/**
|
|
@@ -928,22 +1221,84 @@ var Generator = class Generator {
|
|
|
928
1221
|
* @param basePath - Optional base path to prepend (default: "").
|
|
929
1222
|
* @returns A TypeScript template expressi
|
|
930
1223
|
*/
|
|
931
|
-
static toUrlTemplate(path, parameters, basePath = "") {
|
|
1224
|
+
static toUrlTemplate(path, parameters, basePath = "", auth) {
|
|
1225
|
+
const pathExpression = Generator.toPathTemplate(path, basePath);
|
|
932
1226
|
const queryParameters = parameters.filter((p) => p.in === "query");
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
1227
|
+
const hasAuthQuery = auth?.injections.some((injection) => injection.location === "query");
|
|
1228
|
+
if (queryParameters.length === 0 && !hasAuthQuery) return pathExpression;
|
|
1229
|
+
return factory.createBinaryExpression(pathExpression, factory.createToken(SyntaxKind.PlusToken), Generator.toQueryStringExpression(queryParameters, auth));
|
|
1230
|
+
}
|
|
1231
|
+
/**
|
|
1232
|
+
* Builds the path part of a URL, encoding every `{param}` interpolation.
|
|
1233
|
+
*/
|
|
1234
|
+
static toPathTemplate(path, basePath) {
|
|
937
1235
|
const pathSegments = path.replaceAll("{", "${").split("$").filter(Boolean);
|
|
938
1236
|
if (pathSegments.length === 1) return factory.createNoSubstitutionTemplateLiteral(basePath + path);
|
|
939
1237
|
return factory.createTemplateExpression(factory.createTemplateHead(basePath + pathSegments[0]), pathSegments.slice(1).map((segment, index) => {
|
|
940
1238
|
const match = /^{(.+)}(.+)?/gm.exec(segment);
|
|
941
1239
|
const isLastSegment = index === pathSegments.length - 2;
|
|
942
1240
|
if (!match) throw new Error(`Invalid path segment: ${segment}`);
|
|
943
|
-
return factory.createTemplateSpan(factory.createIdentifier(match[1]), !isLastSegment ? factory.createTemplateMiddle(match[2]) : factory.createTemplateTail(match[2] || ""));
|
|
1241
|
+
return factory.createTemplateSpan(factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.toIdentifier(match[1]))])]), !isLastSegment ? factory.createTemplateMiddle(match[2]) : factory.createTemplateTail(match[2] || ""));
|
|
944
1242
|
}));
|
|
945
1243
|
}
|
|
946
1244
|
/**
|
|
1245
|
+
* Emits an IIFE that builds a query string, omitting undefined/null
|
|
1246
|
+
* values and honouring array `explode` / delimiter styles.
|
|
1247
|
+
*/
|
|
1248
|
+
static toQueryStringExpression(parameters, auth) {
|
|
1249
|
+
const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
|
|
1250
|
+
const unique = (base) => {
|
|
1251
|
+
let name = base;
|
|
1252
|
+
let suffix = 2;
|
|
1253
|
+
while (taken.has(name)) name = `${base}${suffix++}`;
|
|
1254
|
+
taken.add(name);
|
|
1255
|
+
return name;
|
|
1256
|
+
};
|
|
1257
|
+
const qName = unique("q");
|
|
1258
|
+
const vName = unique("v");
|
|
1259
|
+
const sName = unique("s");
|
|
1260
|
+
const statements = [factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier(qName), void 0, void 0, factory.createNewExpression(factory.createIdentifier("URLSearchParams"), void 0, []))], NodeFlags.Const))];
|
|
1261
|
+
const append = (name, value) => factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier(qName), factory.createIdentifier("append")), void 0, [typeof name === "string" ? factory.createStringLiteral(name) : name, value]));
|
|
1262
|
+
const stringify = (value) => factory.createCallExpression(factory.createIdentifier("String"), void 0, [value]);
|
|
1263
|
+
const isNotNull = (value) => factory.createBinaryExpression(value, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword));
|
|
1264
|
+
for (const parameter of parameters) {
|
|
1265
|
+
const id = factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
1266
|
+
const isArray = parameter.schema?.type === "array";
|
|
1267
|
+
if (parameter.style === "deepObject" && !isArray) {
|
|
1268
|
+
const addName = unique("addDeepObject");
|
|
1269
|
+
const prefix = factory.createIdentifier("prefix");
|
|
1270
|
+
const value = factory.createIdentifier("value");
|
|
1271
|
+
const key = factory.createIdentifier("k");
|
|
1272
|
+
const entry = factory.createIdentifier("v");
|
|
1273
|
+
const path = factory.createTemplateExpression(factory.createTemplateHead(""), [factory.createTemplateSpan(prefix, factory.createTemplateMiddle("[")), factory.createTemplateSpan(key, factory.createTemplateTail("]"))]);
|
|
1274
|
+
const recurse = factory.createCallExpression(factory.createIdentifier(addName), void 0, [path, factory.createAsExpression(entry, factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), factory.createToken(SyntaxKind.UnknownKeyword)]))]);
|
|
1275
|
+
const forOf = factory.createForOfStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createArrayBindingPattern([factory.createBindingElement(void 0, void 0, key), factory.createBindingElement(void 0, void 0, entry)]))], NodeFlags.Const), factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), factory.createIdentifier("entries")), void 0, [value]), factory.createBlock([factory.createIfStatement(factory.createBinaryExpression(entry, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([factory.createIfStatement(factory.createBinaryExpression(factory.createTypeOfExpression(entry), factory.createToken(SyntaxKind.EqualsEqualsEqualsToken), factory.createStringLiteral("object")), factory.createExpressionStatement(recurse), append(path, stringify(entry)))], true))], true));
|
|
1276
|
+
const declaration = factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier(addName), void 0, void 0, factory.createArrowFunction(void 0, void 0, [factory.createParameterDeclaration(void 0, void 0, prefix, void 0, factory.createKeywordTypeNode(SyntaxKind.StringKeyword)), factory.createParameterDeclaration(void 0, void 0, value, void 0, factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), factory.createToken(SyntaxKind.UnknownKeyword)]))], void 0, factory.createToken(SyntaxKind.EqualsGreaterThanToken), factory.createBlock([forOf], true)))], NodeFlags.Const));
|
|
1277
|
+
const invoke = factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier(addName), void 0, [factory.createStringLiteral(parameter.name), factory.createAsExpression(id, factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), factory.createToken(SyntaxKind.UnknownKeyword)]))]));
|
|
1278
|
+
statements.push(parameter.required ? factory.createBlock([declaration, invoke], true) : factory.createIfStatement(isNotNull(id), factory.createBlock([declaration, invoke], true)));
|
|
1279
|
+
continue;
|
|
1280
|
+
}
|
|
1281
|
+
if (isArray) {
|
|
1282
|
+
if (parameter.explode ?? (parameter.style === void 0 || parameter.style === "form")) {
|
|
1283
|
+
statements.push(factory.createForOfStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier(vName), void 0, void 0, void 0)], NodeFlags.Const), factory.createBinaryExpression(id, factory.createToken(SyntaxKind.QuestionQuestionToken), factory.createArrayLiteralExpression([])), factory.createBlock([append(parameter.name, stringify(factory.createIdentifier(vName)))], true)));
|
|
1284
|
+
continue;
|
|
1285
|
+
}
|
|
1286
|
+
const separator = parameter.style === "spaceDelimited" ? " " : parameter.style === "pipeDelimited" ? "|" : ",";
|
|
1287
|
+
const join = factory.createCallExpression(factory.createPropertyAccessExpression(id, factory.createIdentifier("join")), void 0, [factory.createStringLiteral(separator)]);
|
|
1288
|
+
statements.push(factory.createIfStatement(isNotNull(id), factory.createBlock([append(parameter.name, join)], true)));
|
|
1289
|
+
continue;
|
|
1290
|
+
}
|
|
1291
|
+
const statement = append(parameter.name, stringify(id));
|
|
1292
|
+
statements.push(parameter.required ? statement : factory.createIfStatement(isNotNull(id), factory.createBlock([statement], true)));
|
|
1293
|
+
}
|
|
1294
|
+
if (auth) for (const injection of auth.injections.filter((item) => item.location === "query")) {
|
|
1295
|
+
const access = authAccess(auth, injection.scheme);
|
|
1296
|
+
statements.push(factory.createIfStatement(factory.createBinaryExpression(access, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([append(injection.name, stringify(access))], true)));
|
|
1297
|
+
}
|
|
1298
|
+
statements.push(factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier(sName), void 0, void 0, factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier(qName), factory.createIdentifier("toString")), void 0, []))], NodeFlags.Const)), factory.createReturnStatement(factory.createConditionalExpression(factory.createIdentifier(sName), factory.createToken(SyntaxKind.QuestionToken), factory.createTemplateExpression(factory.createTemplateHead("?"), [factory.createTemplateSpan(factory.createIdentifier(sName), factory.createTemplateTail(""))]), factory.createToken(SyntaxKind.ColonToken), factory.createStringLiteral(""))));
|
|
1299
|
+
return factory.createCallExpression(factory.createParenthesizedExpression(factory.createArrowFunction(void 0, void 0, [], void 0, factory.createToken(SyntaxKind.EqualsGreaterThanToken), factory.createBlock(statements, true))), void 0, []);
|
|
1300
|
+
}
|
|
1301
|
+
/**
|
|
947
1302
|
* Adds synthetic comments to a TypeScript AST node.
|
|
948
1303
|
*
|
|
949
1304
|
* @param node - The target AST node.
|
|
@@ -960,7 +1315,7 @@ var Generator = class Generator {
|
|
|
960
1315
|
if (comment.tag) return `* @${comment.tag} ${comment.comment ?? ""}`;
|
|
961
1316
|
return `* ${comment.comment}`;
|
|
962
1317
|
};
|
|
963
|
-
const formattedComments = comments.map(formatComment).join("\n").trim() + "\n";
|
|
1318
|
+
const formattedComments = comments.map(formatComment).join("\n").replaceAll("*/", "*\\/").trim() + "\n";
|
|
964
1319
|
addSyntheticLeadingComment(node, SyntaxKind.MultiLineCommentTrivia, formattedComments, true);
|
|
965
1320
|
}
|
|
966
1321
|
/**
|
|
@@ -977,6 +1332,16 @@ var Generator = class Generator {
|
|
|
977
1332
|
const nonArraySchema = schema;
|
|
978
1333
|
return nonArraySchema.format === "blob" || nonArraySchema.format === "binary" || nonArraySchema.type === "file";
|
|
979
1334
|
}
|
|
1335
|
+
/** Whether a schema is a primitive text part (not binary, ref, or object). */
|
|
1336
|
+
static isTextSchema(schema) {
|
|
1337
|
+
if (!schema || schema.isRef) return false;
|
|
1338
|
+
if (Generator.isBinarySchema(schema)) return false;
|
|
1339
|
+
if (schema.type === "array") {
|
|
1340
|
+
const items = schema.items;
|
|
1341
|
+
return items ? Generator.isTextSchema(items) : false;
|
|
1342
|
+
}
|
|
1343
|
+
return schema.type === "string" || schema.type === "integer" || schema.type === "number" || schema.type === "boolean";
|
|
1344
|
+
}
|
|
980
1345
|
static schemaToTypeString(schema) {
|
|
981
1346
|
if (schema.type === "array") {
|
|
982
1347
|
const arraySchema = schema;
|
|
@@ -995,7 +1360,7 @@ var Generator = class Generator {
|
|
|
995
1360
|
static generateParamTags(parameters, requestBody) {
|
|
996
1361
|
const tags = [];
|
|
997
1362
|
for (const p of parameters) {
|
|
998
|
-
const paramName = Base.
|
|
1363
|
+
const paramName = Base.toIdentifier(p.name);
|
|
999
1364
|
let paramType = "unknown";
|
|
1000
1365
|
if (p.schema) paramType = Generator.schemaToTypeString(p.schema);
|
|
1001
1366
|
const isOptional = p.required === false;
|
|
@@ -1004,7 +1369,7 @@ var Generator = class Generator {
|
|
|
1004
1369
|
tag: "param",
|
|
1005
1370
|
paramName,
|
|
1006
1371
|
type: `${paramType}${isOptional ? " | undefined" : ""}`,
|
|
1007
|
-
comment: `${inPrefix}${p.description ?? ""}`
|
|
1372
|
+
comment: `${inPrefix}${p.description?.trim() ?? ""}`
|
|
1008
1373
|
});
|
|
1009
1374
|
}
|
|
1010
1375
|
if (requestBody?.schema && "properties" in requestBody.schema) {
|
|
@@ -1019,7 +1384,7 @@ var Generator = class Generator {
|
|
|
1019
1384
|
tag: "param",
|
|
1020
1385
|
paramName,
|
|
1021
1386
|
type: `${paramType}${isOptional ? " | undefined" : ""}`,
|
|
1022
|
-
comment: schema.description ?? ""
|
|
1387
|
+
comment: schema.description?.trim() ?? ""
|
|
1023
1388
|
});
|
|
1024
1389
|
}
|
|
1025
1390
|
}
|
|
@@ -1028,8 +1393,47 @@ var Generator = class Generator {
|
|
|
1028
1393
|
static toRequestBodyTypeNode(schema) {
|
|
1029
1394
|
return factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("req"), void 0, Generator.toTypeNode(schema));
|
|
1030
1395
|
}
|
|
1396
|
+
/**
|
|
1397
|
+
* Narrows a `oneOf` member with its discriminator mapping value:
|
|
1398
|
+
* `Cat & { petType: 'cat' }`.
|
|
1399
|
+
*/
|
|
1400
|
+
static discriminatedMember(schema, discriminator) {
|
|
1401
|
+
const node = Generator.toTypeNode(schema);
|
|
1402
|
+
const ref = schema.ref;
|
|
1403
|
+
if (!ref) return node;
|
|
1404
|
+
const name = Base.ref2name(ref);
|
|
1405
|
+
const value = Object.entries(discriminator.mapping ?? {}).find(([, target]) => Base.ref2name(target) === name)?.[0];
|
|
1406
|
+
if (value === void 0) return node;
|
|
1407
|
+
return factory.createIntersectionTypeNode([node, factory.createTypeLiteralNode([factory.createPropertySignature(void 0, factory.createStringLiteral(discriminator.propertyName), void 0, factory.createLiteralTypeNode(factory.createStringLiteral(value)))])]);
|
|
1408
|
+
}
|
|
1031
1409
|
static toTypeNode(schema) {
|
|
1410
|
+
if ("const" in schema && schema.const !== void 0) return Generator.toLiteralTypeNode(schema.const);
|
|
1411
|
+
const base = Generator.toTypeNodeInner(schema);
|
|
1412
|
+
if (schema.nullable) return factory.createUnionTypeNode([base, factory.createLiteralTypeNode(factory.createNull())]);
|
|
1413
|
+
return base;
|
|
1414
|
+
}
|
|
1415
|
+
static toLiteralTypeNode(value) {
|
|
1416
|
+
if (typeof value === "string") return factory.createLiteralTypeNode(factory.createStringLiteral(value));
|
|
1417
|
+
if (typeof value === "number") return factory.createLiteralTypeNode(factory.createNumericLiteral(value));
|
|
1418
|
+
return factory.createLiteralTypeNode(value ? factory.createTrue() : factory.createFalse());
|
|
1419
|
+
}
|
|
1420
|
+
static primitiveTypeNode(type) {
|
|
1421
|
+
switch (type) {
|
|
1422
|
+
case "string": return factory.createToken(SyntaxKind.StringKeyword);
|
|
1423
|
+
case "integer":
|
|
1424
|
+
case "number": return factory.createToken(SyntaxKind.NumberKeyword);
|
|
1425
|
+
case "boolean": return factory.createToken(SyntaxKind.BooleanKeyword);
|
|
1426
|
+
case "object": return factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), factory.createToken(SyntaxKind.UnknownKeyword)]);
|
|
1427
|
+
default: return factory.createTypeReferenceNode(factory.createIdentifier(Base.upperCamelCase(type)));
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
static toTypeNodeInner(schema) {
|
|
1032
1431
|
const { type, ref } = schema;
|
|
1432
|
+
const unionTypes = schema.types;
|
|
1433
|
+
if (unionTypes && unionTypes.length > 0) {
|
|
1434
|
+
const nodes = Generator.deduplicateTypes(unionTypes.map((name) => Generator.primitiveTypeNode(name)));
|
|
1435
|
+
return nodes.length === 1 ? nodes[0] : factory.createUnionTypeNode(nodes);
|
|
1436
|
+
}
|
|
1033
1437
|
if (ref) {
|
|
1034
1438
|
const identify = Base.ref2name(ref);
|
|
1035
1439
|
return factory.createTypeReferenceNode(factory.createIdentifier(identify === "unknown" ? identify : Base.upperCamelCase(identify)));
|
|
@@ -1041,20 +1445,28 @@ var Generator = class Generator {
|
|
|
1041
1445
|
}
|
|
1042
1446
|
case "object": {
|
|
1043
1447
|
const propsCount = Object.keys(schema.properties ?? {}).length;
|
|
1044
|
-
|
|
1448
|
+
const additional = schema.additionalProperties;
|
|
1449
|
+
const additionalValue = additional && additional !== true ? Generator.toTypeNode(additional) : factory.createToken(SyntaxKind.UnknownKeyword);
|
|
1450
|
+
if (!schema.properties || propsCount === 0) return factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), additionalValue]);
|
|
1045
1451
|
const props = Object.keys(schema.properties);
|
|
1046
1452
|
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
1047
|
-
|
|
1453
|
+
const literal = factory.createTypeLiteralNode(props.map((propKey) => {
|
|
1048
1454
|
const propSchema = schema.properties[propKey];
|
|
1049
1455
|
return factory.createPropertySignature(void 0, factory.createStringLiteral(propKey), required.includes(propKey) ? void 0 : factory.createToken(SyntaxKind.QuestionToken), Generator.toTypeNode(propSchema));
|
|
1050
1456
|
}));
|
|
1457
|
+
const additionalProps = schema.additionalProperties;
|
|
1458
|
+
if (additionalProps === void 0 || additionalProps === false) return literal;
|
|
1459
|
+
return factory.createIntersectionTypeNode([literal, factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), additionalProps === true ? factory.createToken(SyntaxKind.UnknownKeyword) : Generator.toTypeNode(additionalProps)])]);
|
|
1051
1460
|
}
|
|
1052
1461
|
case "integer":
|
|
1053
1462
|
case "number":
|
|
1054
|
-
if (schema.enum)
|
|
1463
|
+
if (schema.enum) {
|
|
1464
|
+
const values = schema.enum.filter((value) => typeof value === "number");
|
|
1465
|
+
if (values.length > 0) return factory.createUnionTypeNode(values.map((value) => factory.createLiteralTypeNode(factory.createNumericLiteral(value))));
|
|
1466
|
+
}
|
|
1055
1467
|
return factory.createToken(SyntaxKind.NumberKeyword);
|
|
1056
1468
|
case "boolean": return factory.createToken(SyntaxKind.BooleanKeyword);
|
|
1057
|
-
case "file": return factory.createTypeReferenceNode(factory.createIdentifier("Blob"));
|
|
1469
|
+
case "file": return factory.createTypeReferenceNode(factory.createQualifiedName(factory.createIdentifier("globalThis"), factory.createIdentifier("Blob")));
|
|
1058
1470
|
default: {
|
|
1059
1471
|
const { format, oneOf, allOf, anyOf, type, enum: enum_ } = schema;
|
|
1060
1472
|
switch (format) {
|
|
@@ -1062,12 +1474,16 @@ var Generator = class Generator {
|
|
|
1062
1474
|
case "string": return factory.createToken(SyntaxKind.StringKeyword);
|
|
1063
1475
|
case "boolean": return factory.createToken(SyntaxKind.BooleanKeyword);
|
|
1064
1476
|
case "blob":
|
|
1065
|
-
case "binary": return factory.createTypeReferenceNode(factory.createIdentifier("Blob"));
|
|
1066
|
-
|
|
1477
|
+
case "binary": return factory.createTypeReferenceNode(factory.createQualifiedName(factory.createIdentifier("globalThis"), factory.createIdentifier("Blob")));
|
|
1478
|
+
}
|
|
1479
|
+
if (enum_) {
|
|
1480
|
+
const values = enum_.filter((value) => typeof value === "string");
|
|
1481
|
+
if (values.length > 0) return factory.createUnionTypeNode(values.map((value) => factory.createLiteralTypeNode(factory.createStringLiteral(value))));
|
|
1067
1482
|
}
|
|
1068
|
-
if (enum_) return factory.createUnionTypeNode(enum_.map((e) => factory.createLiteralTypeNode(factory.createStringLiteral(e))));
|
|
1069
1483
|
if (type === "string") return factory.createToken(SyntaxKind.StringKeyword);
|
|
1070
1484
|
if (oneOf) {
|
|
1485
|
+
const discriminator = schema.discriminator;
|
|
1486
|
+
if (discriminator?.mapping) return factory.createUnionTypeNode(Generator.deduplicateTypes(oneOf.map((member) => Generator.discriminatedMember(member, discriminator))));
|
|
1071
1487
|
const uniqueTypes = Generator.deduplicateTypes(oneOf.map((s) => Generator.toTypeNode(s)));
|
|
1072
1488
|
return factory.createUnionTypeNode(uniqueTypes);
|
|
1073
1489
|
}
|
|
@@ -1081,6 +1497,12 @@ var Generator = class Generator {
|
|
|
1081
1497
|
}
|
|
1082
1498
|
return factory.createToken(SyntaxKind.UnknownKeyword);
|
|
1083
1499
|
}
|
|
1500
|
+
static toResponsesTypeNode(responses) {
|
|
1501
|
+
return factory.createTypeLiteralNode(Object.entries(responses).map(([code, mediaTypes]) => {
|
|
1502
|
+
const schema = mediaTypes[0]?.schema;
|
|
1503
|
+
return factory.createPropertySignature(void 0, factory.createStringLiteral(code), void 0, schema ? Generator.toTypeNode(schema) : factory.createToken(SyntaxKind.UnknownKeyword));
|
|
1504
|
+
}));
|
|
1505
|
+
}
|
|
1084
1506
|
static deduplicateTypes(types) {
|
|
1085
1507
|
const seen = /* @__PURE__ */ new Set();
|
|
1086
1508
|
const unique = [];
|
|
@@ -1102,30 +1524,41 @@ var Generator = class Generator {
|
|
|
1102
1524
|
const refParameters = [];
|
|
1103
1525
|
for (const parameter of parameters) if (parameter.ref) {
|
|
1104
1526
|
const refName = Base.ref2name(parameter.ref);
|
|
1105
|
-
refParameters.push(factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(Base.
|
|
1527
|
+
refParameters.push(factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(Base.toIdentifier(refName)), void 0, factory.createTypeReferenceNode(factory.createIdentifier(Base.upperCamelCase(Base.normalize(refName)))), void 0));
|
|
1106
1528
|
} else {
|
|
1107
1529
|
const { name, schema, required } = parameter;
|
|
1108
|
-
|
|
1109
|
-
|
|
1530
|
+
const key = Base.camelCase(Base.normalize(name));
|
|
1531
|
+
const id = Base.toIdentifier(name);
|
|
1532
|
+
objectElements.push(factory.createBindingElement(void 0, key === id ? void 0 : factory.createIdentifier(key), factory.createIdentifier(id)));
|
|
1533
|
+
typeObjectElements.push(factory.createPropertySignature([], factory.createIdentifier(key), required ? void 0 : factory.createToken(SyntaxKind.QuestionToken), !schema ? factory.createToken(SyntaxKind.UnknownKeyword) : Generator.toTypeNode(schema)));
|
|
1110
1534
|
}
|
|
1111
1535
|
if (objectElements.length > 0) return [factory.createParameterDeclaration(void 0, void 0, factory.createObjectBindingPattern(objectElements), void 0, factory.createTypeLiteralNode(typeObjectElements), void 0), ...refParameters];
|
|
1112
1536
|
return refParameters;
|
|
1113
1537
|
}
|
|
1538
|
+
/** Property keys listed in a parent schema's `required` array. */
|
|
1539
|
+
static requiredPropertyKeys(schema) {
|
|
1540
|
+
return schema && Array.isArray(schema.required) ? schema.required : [];
|
|
1541
|
+
}
|
|
1114
1542
|
static toFormDataStatement(parameters, requestBody) {
|
|
1115
1543
|
const statements = [];
|
|
1544
|
+
const requiredKeys = Generator.requiredPropertyKeys(requestBody);
|
|
1116
1545
|
const fdDeclaration = factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier("fd"), void 0, void 0, factory.createNewExpression(factory.createIdentifier("FormData"), void 0, []))], NodeFlags.Const));
|
|
1117
1546
|
statements.push(fdDeclaration);
|
|
1118
1547
|
parameters.forEach((parameter) => {
|
|
1119
|
-
|
|
1548
|
+
const id = factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
1549
|
+
statements.push(factory.createExpressionStatement(factory.createBinaryExpression(id, factory.createToken(SyntaxKind.AmpersandAmpersandToken), factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("fd"), factory.createIdentifier("append")), void 0, [factory.createStringLiteral(parameter.name), id]))));
|
|
1120
1550
|
});
|
|
1121
1551
|
if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) Object.keys(requestBody.properties).forEach((key) => {
|
|
1122
1552
|
const schemaByKey = requestBody.properties[key];
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
factory.
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1553
|
+
const accessor = factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key));
|
|
1554
|
+
if (schemaByKey.type === "array" && Generator.isBinarySchema(schemaByKey)) {
|
|
1555
|
+
const loop = factory.createForOfStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration("file")], NodeFlags.Const), accessor, factory.createBlock([factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("fd"), factory.createIdentifier("append")), [], [
|
|
1556
|
+
factory.createStringLiteral(key),
|
|
1557
|
+
factory.createIdentifier("file"),
|
|
1558
|
+
factory.createPropertyAccessExpression(factory.createAsExpression(factory.createIdentifier("file"), factory.createTypeReferenceNode(factory.createIdentifier("File"), void 0)), factory.createIdentifier("name"))
|
|
1559
|
+
]))]));
|
|
1560
|
+
statements.push(requiredKeys.includes(key) ? loop : factory.createIfStatement(factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([loop], true)));
|
|
1561
|
+
} else if (requiredKeys.includes(key)) statements.push(factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("fd"), factory.createIdentifier("append")), void 0, [factory.createStringLiteral(key), schemaByKey.type === "string" || Generator.isBinarySchema(schemaByKey) || schemaByKey.isRef ? factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key)) : schemaByKey.type === "array" || schemaByKey.type === "object" ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), void 0, [factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key))]) : factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key))])])));
|
|
1129
1562
|
else statements.push(factory.createExpressionStatement(factory.createBinaryExpression(factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key)), factory.createToken(SyntaxKind.AmpersandAmpersandToken), factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("fd"), factory.createIdentifier("append")), void 0, [factory.createStringLiteral(key), schemaByKey.type === "string" || Generator.isBinarySchema(schemaByKey) || schemaByKey.isRef ? factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key)) : schemaByKey.type === "array" || schemaByKey.type === "object" ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), void 0, [factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key))]) : factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key))])]))));
|
|
1130
1563
|
});
|
|
1131
1564
|
return statements;
|
|
@@ -1145,17 +1578,26 @@ var Generator = class Generator {
|
|
|
1145
1578
|
const spDeclaration = factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier("sp"), void 0, void 0, factory.createNewExpression(factory.createIdentifier("URLSearchParams"), void 0, []))], NodeFlags.Const));
|
|
1146
1579
|
statements.push(spDeclaration);
|
|
1147
1580
|
const appendValue = (key, valueExpr) => factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("sp"), factory.createIdentifier("append")), void 0, [factory.createStringLiteral(key), valueExpr]));
|
|
1148
|
-
if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0)
|
|
1149
|
-
const
|
|
1150
|
-
const
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1581
|
+
if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) {
|
|
1582
|
+
const requiredKeys = Generator.requiredPropertyKeys(requestBody);
|
|
1583
|
+
for (const key of Object.keys(requestBody.properties)) {
|
|
1584
|
+
const fieldSchema = requestBody.properties[key];
|
|
1585
|
+
const required = requiredKeys.includes(key);
|
|
1586
|
+
const accessor = factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key));
|
|
1587
|
+
const nonNull = factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword));
|
|
1588
|
+
if (fieldSchema.type === "array") {
|
|
1589
|
+
const item = factory.createIdentifier("item");
|
|
1590
|
+
const loop = factory.createForOfStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(item)], NodeFlags.Const), accessor, factory.createBlock([appendValue(key, Generator.toFormDataCompatibleString(item, fieldSchema.items))], true));
|
|
1591
|
+
statements.push(required ? loop : factory.createIfStatement(nonNull, factory.createBlock([loop], true)));
|
|
1592
|
+
continue;
|
|
1593
|
+
}
|
|
1594
|
+
const append = appendValue(key, Generator.toFormDataCompatibleString(accessor, fieldSchema));
|
|
1595
|
+
statements.push(required ? append : factory.createIfStatement(nonNull, factory.createBlock([append], true)));
|
|
1596
|
+
}
|
|
1155
1597
|
}
|
|
1156
1598
|
for (const parameter of parameters) {
|
|
1157
1599
|
if (parameter.in === "header" || parameter.in === "cookie" || parameter.in === "path") continue;
|
|
1158
|
-
const accessor = factory.createIdentifier(Base.
|
|
1600
|
+
const accessor = factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
1159
1601
|
statements.push(factory.createIfStatement(factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([appendValue(parameter.name, Generator.toFormDataCompatibleString(accessor))], true)));
|
|
1160
1602
|
}
|
|
1161
1603
|
return statements;
|
|
@@ -1169,7 +1611,7 @@ var Generator = class Generator {
|
|
|
1169
1611
|
if (schema && (schema.type === "object" || schema.type === "array")) return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), void 0, [expr]);
|
|
1170
1612
|
return factory.createCallExpression(factory.createIdentifier("String"), void 0, [expr]);
|
|
1171
1613
|
}
|
|
1172
|
-
static bodyBlock(uri, method, parameters, requestBody, response, adapter) {
|
|
1614
|
+
static bodyBlock(uri, method, parameters, requestBody, response, adapter, errorMode, auth, requestControl) {
|
|
1173
1615
|
const shouldParseResponseToJSON = "application/json" === response?.type;
|
|
1174
1616
|
const parametersShouldPutInFormData = parameters.filter((p) => p.in === "formData" || p.schema && Generator.isBinarySchema(p.schema));
|
|
1175
1617
|
const parametersShouldNotPutInFormData = parameters.filter((p) => !parametersShouldPutInFormData.includes(p));
|
|
@@ -1178,10 +1620,12 @@ var Generator = class Generator {
|
|
|
1178
1620
|
const hasBinaryInParameters = parameters.some((p) => p?.schema && Generator.isBinarySchema(p.schema));
|
|
1179
1621
|
const mediaType = (requestBody?.type ?? "").toLowerCase().split(";")[0]?.trim();
|
|
1180
1622
|
const requestSchemaIsBinary = requestBody?.schema && Generator.isBinarySchema(requestBody.schema);
|
|
1623
|
+
const multipartParts = requestBody?.schema && "properties" in requestBody.schema && requestBody.schema.properties ? Object.values(requestBody.schema.properties) : [];
|
|
1624
|
+
const hasOnlyTextParts = multipartParts.length > 0 && multipartParts.every((part) => Generator.isTextSchema(part));
|
|
1181
1625
|
let bodyKind = "none";
|
|
1182
1626
|
let bodyContentType;
|
|
1183
1627
|
if (mediaType === "multipart/form-data") {
|
|
1184
|
-
if (hasBinaryInParameters || isRequestBodyContainsBinary || parametersShouldPutInFormData.length > 0) bodyKind = "form-data";
|
|
1628
|
+
if (hasBinaryInParameters || isRequestBodyContainsBinary || hasOnlyTextParts || parametersShouldPutInFormData.length > 0) bodyKind = "form-data";
|
|
1185
1629
|
} else if (mediaType === "application/x-www-form-urlencoded") {
|
|
1186
1630
|
bodyKind = "urlencoded";
|
|
1187
1631
|
bodyContentType = "application/x-www-form-urlencoded";
|
|
@@ -1200,39 +1644,164 @@ var Generator = class Generator {
|
|
|
1200
1644
|
const preStatements = [];
|
|
1201
1645
|
if (bodyKind === "form-data") preStatements.push(...Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema));
|
|
1202
1646
|
else if (bodyKind === "urlencoded") preStatements.push(...Generator.toURLSearchParamsStatement(parametersShouldNotPutInFormData, requestBody?.schema));
|
|
1203
|
-
return factory.createBlock([...preStatements, ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, bodyKind, bodyContentType, shouldParseResponseToJSON)]);
|
|
1647
|
+
return factory.createBlock([...preStatements, ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, bodyKind, bodyContentType, shouldParseResponseToJSON, errorMode, auth, requestControl)]);
|
|
1648
|
+
}
|
|
1649
|
+
/**
|
|
1650
|
+
* Resolves effective security requirements into concrete injections.
|
|
1651
|
+
* Requirements are OR-ed by the spec; we inject every credential the
|
|
1652
|
+
* caller provides, so either branch of an OR works.
|
|
1653
|
+
*/
|
|
1654
|
+
static toAuthInjections(security, schemes) {
|
|
1655
|
+
const injections = [];
|
|
1656
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1657
|
+
for (const requirement of security ?? []) for (const schemeName of Object.keys(requirement)) {
|
|
1658
|
+
const scheme = schemes[schemeName];
|
|
1659
|
+
if (!scheme) continue;
|
|
1660
|
+
let injection;
|
|
1661
|
+
if (scheme.type === "apiKey" && scheme.in && scheme.name) injection = {
|
|
1662
|
+
scheme: schemeName,
|
|
1663
|
+
location: scheme.in,
|
|
1664
|
+
name: scheme.name,
|
|
1665
|
+
kind: "raw"
|
|
1666
|
+
};
|
|
1667
|
+
else if (scheme.type === "http") injection = {
|
|
1668
|
+
scheme: schemeName,
|
|
1669
|
+
location: "header",
|
|
1670
|
+
name: "Authorization",
|
|
1671
|
+
kind: scheme.scheme === "basic" ? "basic" : "bearer"
|
|
1672
|
+
};
|
|
1673
|
+
else if (scheme.type === "basic" || scheme.type === "oauth2" || scheme.type === "openIdConnect") injection = {
|
|
1674
|
+
scheme: schemeName,
|
|
1675
|
+
location: "header",
|
|
1676
|
+
name: "Authorization",
|
|
1677
|
+
kind: scheme.type === "basic" ? "basic" : "bearer"
|
|
1678
|
+
};
|
|
1679
|
+
if (!injection) continue;
|
|
1680
|
+
const key = `${injection.location}:${injection.name}`;
|
|
1681
|
+
if (seen.has(key)) continue;
|
|
1682
|
+
seen.add(key);
|
|
1683
|
+
injections.push(injection);
|
|
1684
|
+
}
|
|
1685
|
+
return injections;
|
|
1686
|
+
}
|
|
1687
|
+
/** `{ [scheme: string]: string | { username: string; password: string } }` */
|
|
1688
|
+
static authOptionsTypeNode() {
|
|
1689
|
+
return factory.createTypeLiteralNode([factory.createIndexSignature(void 0, [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("scheme"), void 0, factory.createKeywordTypeNode(SyntaxKind.StringKeyword))], factory.createUnionTypeNode([factory.createKeywordTypeNode(SyntaxKind.StringKeyword), factory.createTypeLiteralNode([factory.createPropertySignature(void 0, factory.createIdentifier("username"), void 0, factory.createKeywordTypeNode(SyntaxKind.StringKeyword)), factory.createPropertySignature(void 0, factory.createIdentifier("password"), void 0, factory.createKeywordTypeNode(SyntaxKind.StringKeyword))])]))]);
|
|
1690
|
+
}
|
|
1691
|
+
/** `{ signal?: AbortSignal; headers?: Record<string, string>; timeout?: number }` */
|
|
1692
|
+
static requestOptionsTypeNode() {
|
|
1693
|
+
const stringType = factory.createKeywordTypeNode(SyntaxKind.StringKeyword);
|
|
1694
|
+
return factory.createTypeLiteralNode([
|
|
1695
|
+
factory.createPropertySignature(void 0, factory.createIdentifier("signal"), factory.createToken(SyntaxKind.QuestionToken), factory.createTypeReferenceNode(factory.createIdentifier("AbortSignal"))),
|
|
1696
|
+
factory.createPropertySignature(void 0, factory.createIdentifier("headers"), factory.createToken(SyntaxKind.QuestionToken), factory.createTypeReferenceNode(factory.createIdentifier("Record"), [stringType, stringType])),
|
|
1697
|
+
factory.createPropertySignature(void 0, factory.createIdentifier("timeout"), factory.createToken(SyntaxKind.QuestionToken), factory.createKeywordTypeNode(SyntaxKind.NumberKeyword))
|
|
1698
|
+
]);
|
|
1204
1699
|
}
|
|
1205
1700
|
static schemaToStatemets(parsedDoc, adaptor, options) {
|
|
1206
1701
|
const statements = [];
|
|
1207
|
-
const { apis, schemas = {}, enums } = parsedDoc;
|
|
1702
|
+
const { apis, schemas = {}, enums, securitySchemes = {} } = parsedDoc;
|
|
1208
1703
|
const enumNames = [];
|
|
1209
1704
|
for (const enumObject of enums) {
|
|
1210
1705
|
enumNames.push(Base.upperCamelCase(enumObject.name));
|
|
1211
|
-
|
|
1212
|
-
|
|
1706
|
+
const usedKeys = /* @__PURE__ */ new Set();
|
|
1707
|
+
const members = enumObject.enum.filter((member) => typeof member === "string" || typeof member === "number").map((member, index) => {
|
|
1708
|
+
let key = typeof member === "string" && !/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(member) ? member : `Value_${String(member).replace(/[^A-Za-z0-9]/g, "_")}`;
|
|
1709
|
+
if (usedKeys.has(key)) key = `${key}_${index}`;
|
|
1710
|
+
usedKeys.add(key);
|
|
1213
1711
|
return factory.createEnumMember(factory.createStringLiteral(key), typeof member === "string" ? factory.createStringLiteral(member) : factory.createNumericLiteral(member));
|
|
1214
|
-
})
|
|
1712
|
+
});
|
|
1713
|
+
statements.push(factory.createEnumDeclaration([factory.createToken(SyntaxKind.ExportKeyword)], factory.createIdentifier(Base.upperCamelCase(enumObject.name)), members));
|
|
1215
1714
|
}
|
|
1216
1715
|
for (const schemaKey in schemas) if (Object.hasOwn(schemas, schemaKey) && !enumNames.includes(Base.upperCamelCase(schemaKey))) {
|
|
1217
1716
|
const schema = schemas[schemaKey];
|
|
1218
1717
|
statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(Base.upperCamelCase(schemaKey)), void 0, Generator.toTypeNode(schema)));
|
|
1219
1718
|
}
|
|
1220
1719
|
const reserveUnique = createUniqueNameResolver();
|
|
1720
|
+
let authTypeName;
|
|
1721
|
+
let requestOptionsTypeName;
|
|
1221
1722
|
for (const uri in apis) {
|
|
1222
1723
|
const operations = apis[uri];
|
|
1223
1724
|
for (const operation of operations) {
|
|
1224
1725
|
const { method, operationId, requestBody = [], responses = [], summary, deprecated, description } = operation;
|
|
1225
|
-
|
|
1226
|
-
|
|
1726
|
+
const { parameters = [] } = operation;
|
|
1727
|
+
const authInjections = Generator.toAuthInjections(operation.security, securitySchemes);
|
|
1728
|
+
let authArgument;
|
|
1729
|
+
let authTypeReference;
|
|
1730
|
+
if (authInjections.length > 0) {
|
|
1731
|
+
const typeName = authTypeName ?? (() => {
|
|
1732
|
+
let candidate = "AuthOptions";
|
|
1733
|
+
while (Object.keys(schemas).some((key) => Base.upperCamelCase(key) === candidate) || enumNames.includes(candidate)) candidate += "2";
|
|
1734
|
+
return candidate;
|
|
1735
|
+
})();
|
|
1736
|
+
if (!authTypeName) {
|
|
1737
|
+
authTypeName = typeName;
|
|
1738
|
+
statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, Generator.authOptionsTypeNode()));
|
|
1739
|
+
}
|
|
1740
|
+
const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
|
|
1741
|
+
taken.add("req");
|
|
1742
|
+
let name = "auth";
|
|
1743
|
+
let suffix = 2;
|
|
1744
|
+
while (taken.has(name)) {
|
|
1745
|
+
name = `auth${suffix}`;
|
|
1746
|
+
suffix++;
|
|
1747
|
+
}
|
|
1748
|
+
authArgument = {
|
|
1749
|
+
name,
|
|
1750
|
+
injections: authInjections
|
|
1751
|
+
};
|
|
1752
|
+
authTypeReference = factory.createTypeReferenceNode(factory.createIdentifier(typeName));
|
|
1753
|
+
}
|
|
1754
|
+
const optionsTypeName = requestOptionsTypeName ?? (() => {
|
|
1755
|
+
let candidate = "RequestOptions";
|
|
1756
|
+
while (Object.keys(schemas).some((key) => Base.upperCamelCase(key) === candidate) || enumNames.includes(candidate)) candidate += "2";
|
|
1757
|
+
return candidate;
|
|
1758
|
+
})();
|
|
1759
|
+
if (!requestOptionsTypeName) {
|
|
1760
|
+
requestOptionsTypeName = optionsTypeName;
|
|
1761
|
+
statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(optionsTypeName), void 0, Generator.requestOptionsTypeNode()));
|
|
1762
|
+
}
|
|
1763
|
+
const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
|
|
1764
|
+
taken.add("req");
|
|
1765
|
+
if (authArgument) taken.add(authArgument.name);
|
|
1766
|
+
let requestControlName = "options";
|
|
1767
|
+
let requestControlSuffix = 2;
|
|
1768
|
+
while (taken.has(requestControlName)) {
|
|
1769
|
+
requestControlName = `options${requestControlSuffix}`;
|
|
1770
|
+
requestControlSuffix++;
|
|
1771
|
+
}
|
|
1772
|
+
const requestControl = { name: requestControlName };
|
|
1227
1773
|
if (requestBody.length === 0) requestBody.push({ type: "application/json" });
|
|
1774
|
+
const { responseTypes } = operation;
|
|
1775
|
+
const responseCodes = Object.keys(responseTypes ?? {});
|
|
1776
|
+
if (responseTypes && (responseCodes.length > 1 || !/^2\d\d$/.test(responseCodes[0] ?? ""))) {
|
|
1777
|
+
const responsesName = reserveUnique(`${Base.pathToFnName(uri, method, operationId)}Responses`);
|
|
1778
|
+
statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(responsesName), void 0, Generator.toResponsesTypeNode(responseTypes)));
|
|
1779
|
+
}
|
|
1228
1780
|
const shouldAddExtraMethodNameSuffix = requestBody.length > 1;
|
|
1229
1781
|
for (const req of requestBody) {
|
|
1230
|
-
const statement = factory.createFunctionDeclaration([factory.createModifier(SyntaxKind.ExportKeyword), factory.createModifier(SyntaxKind.AsyncKeyword)], void 0, reserveUnique(Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.mediaTypeToSuffix(req.type) : "")), void 0, [
|
|
1231
|
-
|
|
1782
|
+
const statement = factory.createFunctionDeclaration([factory.createModifier(SyntaxKind.ExportKeyword), factory.createModifier(SyntaxKind.AsyncKeyword)], void 0, reserveUnique(Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.mediaTypeToSuffix(req.type) : "")), void 0, [
|
|
1783
|
+
...parameters.length > 0 ? Generator.toDeclarationNodes(parameters) : [],
|
|
1784
|
+
...req?.schema ? [Generator.toRequestBodyTypeNode(req.schema)] : [],
|
|
1785
|
+
...authArgument && authTypeReference ? [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(authArgument.name), factory.createToken(SyntaxKind.QuestionToken), authTypeReference)] : [],
|
|
1786
|
+
factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(requestControl.name), factory.createToken(SyntaxKind.QuestionToken), factory.createTypeReferenceNode(factory.createIdentifier(optionsTypeName)))
|
|
1787
|
+
].filter(Boolean), void 0, Generator.bodyBlock(options.baseURL + uri, method, parameters, req, responses[0], adaptor, options.errorMode, authArgument, requestControl));
|
|
1788
|
+
const mergedDescription = [description, summary].filter(Boolean).map((part) => part?.trim()).join(". ");
|
|
1232
1789
|
Generator.addComments(statement, [
|
|
1233
1790
|
mergedDescription && { comment: mergedDescription },
|
|
1234
1791
|
deprecated && { tag: "deprecated" },
|
|
1235
|
-
...Generator.generateParamTags(parameters, req)
|
|
1792
|
+
...Generator.generateParamTags(parameters, req),
|
|
1793
|
+
...authArgument ? [{
|
|
1794
|
+
tag: "param",
|
|
1795
|
+
paramName: authArgument.name,
|
|
1796
|
+
type: "AuthOptions",
|
|
1797
|
+
comment: "Optional security credentials, keyed by scheme name"
|
|
1798
|
+
}] : [],
|
|
1799
|
+
{
|
|
1800
|
+
tag: "param",
|
|
1801
|
+
paramName: requestControl.name,
|
|
1802
|
+
type: optionsTypeName,
|
|
1803
|
+
comment: "Optional abort signal, extra headers and timeout"
|
|
1804
|
+
}
|
|
1236
1805
|
].filter(Boolean));
|
|
1237
1806
|
statements.push(statement);
|
|
1238
1807
|
}
|
|
@@ -1243,16 +1812,76 @@ var Generator = class Generator {
|
|
|
1243
1812
|
static async prettier(code) {
|
|
1244
1813
|
return await format(code, { parser: "typescript" });
|
|
1245
1814
|
}
|
|
1815
|
+
/**
|
|
1816
|
+
* Splits generated code into `types.ts`, one file per tag, and `index.ts`.
|
|
1817
|
+
* Shared type declarations live in `types.ts`; tag files import them and
|
|
1818
|
+
* export only their functions.
|
|
1819
|
+
*/
|
|
1820
|
+
static async genCodeMulti(schema, initOptions, adaptor) {
|
|
1821
|
+
const genOptions = {
|
|
1822
|
+
baseURL: initOptions.baseURL ?? "",
|
|
1823
|
+
errorMode: initOptions.errorMode === "throw" || initOptions.errorMode === "result" ? initOptions.errorMode : void 0
|
|
1824
|
+
};
|
|
1825
|
+
const isTypeDeclaration = (statement) => isEnumDeclaration(statement) || isTypeAliasDeclaration(statement) || isInterfaceDeclaration(statement);
|
|
1826
|
+
const typeStatements = Generator.schemaToStatemets(schema, adaptor, genOptions).filter(isTypeDeclaration);
|
|
1827
|
+
const typeNames = typeStatements.map((statement) => isEnumDeclaration(statement) || isTypeAliasDeclaration(statement) || isInterfaceDeclaration(statement) ? statement.name.text : void 0).filter((name) => Boolean(name));
|
|
1828
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1829
|
+
for (const [uri, operations] of Object.entries(schema.apis)) for (const operation of operations) {
|
|
1830
|
+
const tag = operation.tags?.[0] ?? "default";
|
|
1831
|
+
const apis = groups.get(tag) ?? {};
|
|
1832
|
+
apis[uri] ??= [];
|
|
1833
|
+
apis[uri].push(operation);
|
|
1834
|
+
groups.set(tag, apis);
|
|
1835
|
+
}
|
|
1836
|
+
const files = {};
|
|
1837
|
+
const used = /* @__PURE__ */ new Set(["index", "types"]);
|
|
1838
|
+
files["types.ts"] = await Generator.prettier(Generator.toCode(typeStatements));
|
|
1839
|
+
const exportLines = ["export * from './types.js';"];
|
|
1840
|
+
for (const [tag, apis] of groups) {
|
|
1841
|
+
const tagStatements = Generator.schemaToStatemets({
|
|
1842
|
+
...schema,
|
|
1843
|
+
apis
|
|
1844
|
+
}, adaptor, genOptions).filter((statement) => !isTypeDeclaration(statement));
|
|
1845
|
+
const nodes = [];
|
|
1846
|
+
if (typeNames.length > 0) nodes.push(factory.createImportDeclaration(void 0, factory.createImportClause(true, void 0, factory.createNamedImports(typeNames.map((name) => factory.createImportSpecifier(false, void 0, factory.createIdentifier(name))))), factory.createStringLiteral("./types.js")));
|
|
1847
|
+
nodes.push(...tagStatements);
|
|
1848
|
+
let code = Generator.toCode(nodes);
|
|
1849
|
+
if (initOptions.importClientSource) code = initOptions.importClientSource + "\n\n" + code;
|
|
1850
|
+
const fileName = Generator.uniqueFileName(tag, used);
|
|
1851
|
+
files[`${fileName}.ts`] = await Generator.prettier(code);
|
|
1852
|
+
exportLines.push(`export * from './${fileName}.js';`);
|
|
1853
|
+
}
|
|
1854
|
+
const index = await Generator.prettier(exportLines.join("\n"));
|
|
1855
|
+
files["index.ts"] = index;
|
|
1856
|
+
return {
|
|
1857
|
+
code: index,
|
|
1858
|
+
files
|
|
1859
|
+
};
|
|
1860
|
+
}
|
|
1861
|
+
/** Lower-case file stem that cannot collide with reserved or earlier names. */
|
|
1862
|
+
static uniqueFileName(tag, used) {
|
|
1863
|
+
const base = tag.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "default";
|
|
1864
|
+
let name = base;
|
|
1865
|
+
let suffix = 2;
|
|
1866
|
+
while (used.has(name)) {
|
|
1867
|
+
name = `${base}-${suffix}`;
|
|
1868
|
+
suffix++;
|
|
1869
|
+
}
|
|
1870
|
+
used.add(name);
|
|
1871
|
+
return name;
|
|
1872
|
+
}
|
|
1246
1873
|
static async genCode(schema, initOptions, adaptor) {
|
|
1247
|
-
const { importClientSource } = initOptions;
|
|
1248
|
-
const statements = Generator.schemaToStatemets(schema, adaptor, {
|
|
1874
|
+
const { importClientSource, errorMode } = initOptions;
|
|
1875
|
+
const statements = Generator.schemaToStatemets(schema, adaptor, {
|
|
1876
|
+
baseURL: initOptions.baseURL ?? "",
|
|
1877
|
+
errorMode: errorMode === "throw" || errorMode === "result" ? errorMode : void 0
|
|
1878
|
+
});
|
|
1249
1879
|
let code = Generator.toCode(statements);
|
|
1250
1880
|
if (importClientSource) code = importClientSource + "\n\n" + code;
|
|
1251
1881
|
return await Generator.prettier(code);
|
|
1252
1882
|
}
|
|
1253
1883
|
};
|
|
1254
|
-
|
|
1255
|
-
//#region src/core/client/axios.ts
|
|
1884
|
+
// src/core/client/axios.ts
|
|
1256
1885
|
/**
|
|
1257
1886
|
* Adapter class implementing support for generating code that makes use of the Axios HTTP client library.
|
|
1258
1887
|
* This adapter defines custom behavior and field mappings specific to the Axios client.
|
|
@@ -1283,16 +1912,19 @@ var AxiosAdapter = class extends Adapter {
|
|
|
1283
1912
|
*
|
|
1284
1913
|
* @returns {Statement[]} An array of TypeScript statements that define the client configuration.
|
|
1285
1914
|
*/
|
|
1286
|
-
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, _shouldUseJSONResponse) {
|
|
1915
|
+
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, _shouldUseJSONResponse, errorMode, auth, requestControl) {
|
|
1287
1916
|
const statements = [];
|
|
1288
1917
|
parameters.filter((p) => !p.in || p.in === "body");
|
|
1289
1918
|
const inHeader = parameters.filter((p) => p.in === "header");
|
|
1290
1919
|
const toLiterlExpression = () => {
|
|
1291
1920
|
const headerEntries = [];
|
|
1292
|
-
for (const p of inHeader) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.
|
|
1921
|
+
for (const p of inHeader) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.toIdentifier(p.name))])])));
|
|
1293
1922
|
if (bodyContentType !== void 0) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Content-Type"), factory.createStringLiteral(bodyContentType)));
|
|
1923
|
+
if (parameters.some((p) => p.in === "cookie") || auth?.injections.some((injection) => injection.location === "cookie")) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Cookie"), cookieHeaderExpression(parameters, auth)));
|
|
1924
|
+
if (auth) headerEntries.push(...authHeaderEntries(auth));
|
|
1294
1925
|
const properties = [factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))];
|
|
1295
|
-
if (headerEntries.length > 0) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(headerEntries)));
|
|
1926
|
+
if (headerEntries.length > 0 || requestControl) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(withRequestHeaders(headerEntries, requestControl))));
|
|
1927
|
+
if (requestControl) properties.push(factory.createPropertyAssignment(factory.createIdentifier("signal"), optionalAccess(requestControl, "signal")), factory.createPropertyAssignment(factory.createIdentifier("timeout"), optionalAccess(requestControl, "timeout")));
|
|
1296
1928
|
let bodyExpr;
|
|
1297
1929
|
switch (bodyKind) {
|
|
1298
1930
|
case "form-data":
|
|
@@ -1302,20 +1934,33 @@ var AxiosAdapter = class extends Adapter {
|
|
|
1302
1934
|
bodyExpr = factory.createIdentifier("sp");
|
|
1303
1935
|
break;
|
|
1304
1936
|
case "json":
|
|
1305
|
-
case "binary":
|
|
1306
|
-
bodyExpr = factory.createIdentifier("req");
|
|
1307
|
-
break;
|
|
1308
|
-
case "none": break;
|
|
1937
|
+
case "binary": bodyExpr = factory.createIdentifier("req");
|
|
1309
1938
|
}
|
|
1310
1939
|
if (bodyExpr) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
|
|
1311
1940
|
return factory.createObjectLiteralExpression(properties, true);
|
|
1312
1941
|
};
|
|
1313
|
-
|
|
1942
|
+
const axiosCall = factory.createCallExpression(factory.createIdentifier(adapter.name), response?.schema ? [Generator.toTypeNode(response.schema)] : [factory.createTypeReferenceNode(factory.createIdentifier("unknown"))], [Generator.toUrlTemplate(uri, parameters, "", auth), toLiterlExpression()]);
|
|
1943
|
+
if (errorMode !== "result") {
|
|
1944
|
+
statements.push(factory.createReturnStatement(axiosCall));
|
|
1945
|
+
return statements;
|
|
1946
|
+
}
|
|
1947
|
+
const prop = (name, value) => factory.createPropertyAssignment(factory.createIdentifier(name), value);
|
|
1948
|
+
const resProp = (name) => factory.createPropertyAccessExpression(factory.createIdentifier("res"), factory.createIdentifier(name));
|
|
1949
|
+
const errorProp = (name) => factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(factory.createIdentifier("failure"), factory.createIdentifier("response")), factory.createIdentifier(name));
|
|
1950
|
+
const result = (ok, key, value) => factory.createObjectLiteralExpression([
|
|
1951
|
+
prop("ok", factory.createAsExpression(ok ? factory.createTrue() : factory.createFalse(), factory.createTypeReferenceNode(factory.createIdentifier("const")))),
|
|
1952
|
+
prop("status", ok ? resProp("status") : errorProp("status")),
|
|
1953
|
+
prop(key, value)
|
|
1954
|
+
], true);
|
|
1955
|
+
statements.push(factory.createTryStatement(factory.createBlock([factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier("res"), void 0, void 0, factory.createAwaitExpression(axiosCall))], NodeFlags.Const)), factory.createReturnStatement(result(true, "data", resProp("data")))], true), factory.createCatchClause(factory.createVariableDeclaration(factory.createIdentifier("err")), factory.createBlock([
|
|
1956
|
+
factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier("failure"), void 0, void 0, factory.createAsExpression(factory.createIdentifier("err"), factory.createTypeLiteralNode([factory.createPropertySignature(void 0, factory.createIdentifier("response"), factory.createToken(SyntaxKind.QuestionToken), factory.createTypeLiteralNode([factory.createPropertySignature(void 0, factory.createIdentifier("status"), void 0, factory.createKeywordTypeNode(SyntaxKind.NumberKeyword)), factory.createPropertySignature(void 0, factory.createIdentifier("data"), void 0, factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword))]))])))], NodeFlags.Const)),
|
|
1957
|
+
factory.createIfStatement(factory.createPropertyAccessExpression(factory.createIdentifier("failure"), factory.createIdentifier("response")), factory.createBlock([factory.createReturnStatement(result(false, "error", errorProp("data")))], true)),
|
|
1958
|
+
factory.createThrowStatement(factory.createIdentifier("err"))
|
|
1959
|
+
], true)), void 0));
|
|
1314
1960
|
return statements;
|
|
1315
1961
|
}
|
|
1316
1962
|
};
|
|
1317
|
-
|
|
1318
|
-
//#region src/core/client/fetch.ts
|
|
1963
|
+
// src/core/client/fetch.ts
|
|
1319
1964
|
/**
|
|
1320
1965
|
* FetchAdapter is an adapter class that generates client-side fetch requests.
|
|
1321
1966
|
* It handles parameters, headers, and request bodies to construct proper fetch calls.
|
|
@@ -1339,7 +1984,7 @@ var FetchAdapter = class extends Adapter {
|
|
|
1339
1984
|
* @param shouldUseJSONResponse - Flag to use JSON parsing for the response
|
|
1340
1985
|
* @return - An array of generated TypeScript statements
|
|
1341
1986
|
*/
|
|
1342
|
-
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, shouldUseJSONResponse) {
|
|
1987
|
+
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, shouldUseJSONResponse, errorMode, auth, requestControl) {
|
|
1343
1988
|
const statements = [];
|
|
1344
1989
|
const inBody = parameters.filter((p) => !p.in || p.in === "body");
|
|
1345
1990
|
const inHeader = parameters.filter((p) => p.in === "header");
|
|
@@ -1350,10 +1995,13 @@ var FetchAdapter = class extends Adapter {
|
|
|
1350
1995
|
*/
|
|
1351
1996
|
const toLiterlExpression = () => {
|
|
1352
1997
|
const headerEntries = [];
|
|
1353
|
-
for (const p of inHeader) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.
|
|
1998
|
+
for (const p of inHeader) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.toIdentifier(p.name))])])));
|
|
1354
1999
|
if (bodyContentType !== void 0) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Content-Type"), factory.createStringLiteral(bodyContentType)));
|
|
2000
|
+
if (parameters.some((p) => p.in === "cookie") || auth?.injections.some((injection) => injection.location === "cookie")) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Cookie"), cookieHeaderExpression(parameters, auth)));
|
|
2001
|
+
if (auth) headerEntries.push(...authHeaderEntries(auth));
|
|
1355
2002
|
const properties = [factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))];
|
|
1356
|
-
if (headerEntries.length > 0) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(headerEntries)));
|
|
2003
|
+
if (headerEntries.length > 0 || requestControl) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(withRequestHeaders(headerEntries, requestControl))));
|
|
2004
|
+
if (requestControl) properties.push(factory.createPropertyAssignment(factory.createIdentifier("signal"), fetchSignalExpression(requestControl)));
|
|
1357
2005
|
let bodyExpr;
|
|
1358
2006
|
switch (bodyKind) {
|
|
1359
2007
|
case "form-data":
|
|
@@ -1367,20 +2015,223 @@ var FetchAdapter = class extends Adapter {
|
|
|
1367
2015
|
bodyExpr = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), [], [arg]);
|
|
1368
2016
|
break;
|
|
1369
2017
|
}
|
|
1370
|
-
case "binary":
|
|
1371
|
-
bodyExpr = factory.createIdentifier("req");
|
|
1372
|
-
break;
|
|
1373
|
-
case "none": break;
|
|
2018
|
+
case "binary": bodyExpr = factory.createIdentifier("req");
|
|
1374
2019
|
}
|
|
1375
2020
|
if (bodyExpr) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
|
|
1376
2021
|
return factory.createObjectLiteralExpression(properties, true);
|
|
1377
2022
|
};
|
|
1378
|
-
|
|
2023
|
+
const fetchCall = factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters, "", auth), toLiterlExpression()]);
|
|
2024
|
+
const responseProp = (name) => factory.createPropertyAccessExpression(factory.createIdentifier("response"), factory.createIdentifier(name));
|
|
2025
|
+
const jsonExpression = factory.createAsExpression(factory.createParenthesizedExpression(factory.createAwaitExpression(factory.createCallExpression(responseProp("json"), void 0, []))), response?.schema ? Generator.toTypeNode(response.schema) : factory.createToken(SyntaxKind.UnknownKeyword));
|
|
2026
|
+
const successExpression = shouldUseJSONResponse ? jsonExpression : factory.createIdentifier("response");
|
|
2027
|
+
if (!errorMode) {
|
|
2028
|
+
statements.push(factory.createReturnStatement(shouldUseJSONResponse ? factory.createCallExpression(factory.createPropertyAccessExpression(fetchCall, factory.createIdentifier("then")), void 0, [factory.createArrowFunction([factory.createModifier(SyntaxKind.AsyncKeyword)], [], [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("response"))], void 0, factory.createToken(SyntaxKind.EqualsGreaterThanToken), jsonExpression)]) : fetchCall));
|
|
2029
|
+
return statements;
|
|
2030
|
+
}
|
|
2031
|
+
const notOk = factory.createPrefixUnaryExpression(SyntaxKind.ExclamationToken, responseProp("ok"));
|
|
2032
|
+
const responseText = factory.createAwaitExpression(factory.createCallExpression(responseProp("text"), void 0, []));
|
|
2033
|
+
const thenStatements = [];
|
|
2034
|
+
if (errorMode === "throw") thenStatements.push(factory.createIfStatement(notOk, factory.createBlock([factory.createThrowStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), factory.createIdentifier("assign")), void 0, [factory.createNewExpression(factory.createIdentifier("Error"), void 0, [factory.createTemplateExpression(factory.createTemplateHead("HTTP "), [factory.createTemplateSpan(responseProp("status"), factory.createTemplateTail(""))])]), factory.createObjectLiteralExpression([factory.createPropertyAssignment(factory.createIdentifier("status"), responseProp("status")), factory.createPropertyAssignment(factory.createIdentifier("body"), responseText)], true)]))], true)), factory.createReturnStatement(successExpression));
|
|
2035
|
+
else {
|
|
2036
|
+
const result = (ok, key, value) => factory.createObjectLiteralExpression([
|
|
2037
|
+
factory.createPropertyAssignment(factory.createIdentifier("ok"), factory.createAsExpression(ok ? factory.createTrue() : factory.createFalse(), factory.createTypeReferenceNode(factory.createIdentifier("const")))),
|
|
2038
|
+
factory.createPropertyAssignment(factory.createIdentifier("status"), responseProp("status")),
|
|
2039
|
+
factory.createPropertyAssignment(factory.createIdentifier(key), value)
|
|
2040
|
+
], true);
|
|
2041
|
+
thenStatements.push(factory.createIfStatement(notOk, factory.createBlock([factory.createReturnStatement(result(false, "error", responseText))], true)), factory.createReturnStatement(result(true, "data", successExpression)));
|
|
2042
|
+
}
|
|
2043
|
+
statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createPropertyAccessExpression(fetchCall, factory.createIdentifier("then")), void 0, [factory.createArrowFunction([factory.createModifier(SyntaxKind.AsyncKeyword)], [], [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("response"))], void 0, factory.createToken(SyntaxKind.EqualsGreaterThanToken), factory.createBlock(thenStatements, true))])));
|
|
1379
2044
|
return statements;
|
|
1380
2045
|
}
|
|
1381
2046
|
};
|
|
1382
|
-
|
|
1383
|
-
|
|
2047
|
+
// src/openapi/filter.ts
|
|
2048
|
+
function matchesPrefix(path, prefixes) {
|
|
2049
|
+
return !!prefixes?.length && prefixes.some((prefix) => path.startsWith(prefix));
|
|
2050
|
+
}
|
|
2051
|
+
/**
|
|
2052
|
+
* Keep only the operations selected by tag and path filters.
|
|
2053
|
+
*
|
|
2054
|
+
* Paths use prefix matching (`/admin` covers `/admin/users`). Operations with
|
|
2055
|
+
* no tags are kept only when no `includeTags` filter is active.
|
|
2056
|
+
*/
|
|
2057
|
+
function filterApis(apis, filters) {
|
|
2058
|
+
const keepTag = (op) => {
|
|
2059
|
+
const tags = op.tags ?? [];
|
|
2060
|
+
if (filters.includeTags?.length && !tags.some((tag) => filters.includeTags?.includes(tag))) return false;
|
|
2061
|
+
if (filters.excludeTags?.length && tags.some((tag) => filters.excludeTags?.includes(tag))) return false;
|
|
2062
|
+
return true;
|
|
2063
|
+
};
|
|
2064
|
+
const filtered = {};
|
|
2065
|
+
for (const [path, operations] of Object.entries(apis)) {
|
|
2066
|
+
if (filters.includePaths?.length && !matchesPrefix(path, filters.includePaths)) continue;
|
|
2067
|
+
if (matchesPrefix(path, filters.excludePaths)) continue;
|
|
2068
|
+
const kept = operations.filter(keepTag);
|
|
2069
|
+
if (kept.length > 0) filtered[path] = kept;
|
|
2070
|
+
}
|
|
2071
|
+
return filtered;
|
|
2072
|
+
}
|
|
2073
|
+
// src/openapi/read-write.ts
|
|
2074
|
+
function single(schema) {
|
|
2075
|
+
return schema;
|
|
2076
|
+
}
|
|
2077
|
+
/** True when a schema carries the flag anywhere except through a `$ref`. */
|
|
2078
|
+
function containsFlag(schema, flag) {
|
|
2079
|
+
if (!schema) return false;
|
|
2080
|
+
const value = single(schema);
|
|
2081
|
+
if (value[flag]) return true;
|
|
2082
|
+
if (value.properties) {
|
|
2083
|
+
for (const prop of Object.values(value.properties)) if (containsFlag(prop, flag)) return true;
|
|
2084
|
+
}
|
|
2085
|
+
if (schema.type === "array") return containsFlag(schema.items, flag);
|
|
2086
|
+
for (const key of [
|
|
2087
|
+
"allOf",
|
|
2088
|
+
"anyOf",
|
|
2089
|
+
"oneOf"
|
|
2090
|
+
]) if (value[key]?.some((member) => containsFlag(member, flag))) return true;
|
|
2091
|
+
const additional = value.additionalProperties;
|
|
2092
|
+
return !!additional && typeof additional === "object" && containsFlag(additional, flag);
|
|
2093
|
+
}
|
|
2094
|
+
/** The referenced emitted type name, when a schema is only a reference. */
|
|
2095
|
+
function refType(schema) {
|
|
2096
|
+
const value = single(schema);
|
|
2097
|
+
if (value.ref) return Base.upperCamelCase(Base.ref2name(value.ref));
|
|
2098
|
+
if (value.properties || value.oneOf || value.anyOf || value.allOf) return;
|
|
2099
|
+
if (schema.type === "array") return void 0;
|
|
2100
|
+
return typeof value.type === "string" ? Base.upperCamelCase(value.type) : void 0;
|
|
2101
|
+
}
|
|
2102
|
+
function dependsOn(schema, names) {
|
|
2103
|
+
const ref = refType(schema);
|
|
2104
|
+
if (ref && names.has(ref)) return true;
|
|
2105
|
+
const value = single(schema);
|
|
2106
|
+
if (value.properties) {
|
|
2107
|
+
for (const prop of Object.values(value.properties)) if (dependsOn(prop, names)) return true;
|
|
2108
|
+
}
|
|
2109
|
+
if (schema.type === "array") {
|
|
2110
|
+
const items = schema.items;
|
|
2111
|
+
return !!items && dependsOn(items, names);
|
|
2112
|
+
}
|
|
2113
|
+
for (const key of [
|
|
2114
|
+
"allOf",
|
|
2115
|
+
"anyOf",
|
|
2116
|
+
"oneOf"
|
|
2117
|
+
]) if (value[key]?.some((member) => dependsOn(member, names))) return true;
|
|
2118
|
+
const additional = value.additionalProperties;
|
|
2119
|
+
return !!additional && typeof additional === "object" && dependsOn(additional, names);
|
|
2120
|
+
}
|
|
2121
|
+
/**
|
|
2122
|
+
* Pick the schemas that need an Input/Output variant.
|
|
2123
|
+
*
|
|
2124
|
+
* A schema qualifies when it contains the flag directly, or references a
|
|
2125
|
+
* schema that does. The fixed point makes nested references follow.
|
|
2126
|
+
*/
|
|
2127
|
+
function buildVariant(schemas, flag, suffix) {
|
|
2128
|
+
const seeded = /* @__PURE__ */ new Set();
|
|
2129
|
+
const emitted = /* @__PURE__ */ new Map();
|
|
2130
|
+
for (const key of Object.keys(schemas)) {
|
|
2131
|
+
emitted.set(Base.upperCamelCase(key), key);
|
|
2132
|
+
if (containsFlag(schemas[key], flag)) seeded.add(key);
|
|
2133
|
+
}
|
|
2134
|
+
let changed = true;
|
|
2135
|
+
while (changed) {
|
|
2136
|
+
changed = false;
|
|
2137
|
+
const seededNames = new Set([...seeded].map((key) => Base.upperCamelCase(key)));
|
|
2138
|
+
for (const key of Object.keys(schemas)) if (!seeded.has(key) && dependsOn(schemas[key], seededNames)) {
|
|
2139
|
+
seeded.add(key);
|
|
2140
|
+
changed = true;
|
|
2141
|
+
}
|
|
2142
|
+
}
|
|
2143
|
+
const names = /* @__PURE__ */ new Map();
|
|
2144
|
+
const keys = /* @__PURE__ */ new Map();
|
|
2145
|
+
const taken = new Set(emitted.keys());
|
|
2146
|
+
for (const key of seeded) {
|
|
2147
|
+
const variantKey = key + suffix;
|
|
2148
|
+
const variantName = Base.upperCamelCase(variantKey);
|
|
2149
|
+
if (taken.has(variantName)) continue;
|
|
2150
|
+
taken.add(variantName);
|
|
2151
|
+
names.set(Base.upperCamelCase(key), variantName);
|
|
2152
|
+
keys.set(key, variantKey);
|
|
2153
|
+
}
|
|
2154
|
+
return {
|
|
2155
|
+
names,
|
|
2156
|
+
keys
|
|
2157
|
+
};
|
|
2158
|
+
}
|
|
2159
|
+
/** Clone a schema with flagged properties removed and variant refs remapped. */
|
|
2160
|
+
function transform(schema, flag, names) {
|
|
2161
|
+
const ref = refType(schema);
|
|
2162
|
+
if (ref && names.has(ref)) {
|
|
2163
|
+
const { ref: _ref, ...rest } = single(schema);
|
|
2164
|
+
return {
|
|
2165
|
+
...rest,
|
|
2166
|
+
type: names.get(ref)
|
|
2167
|
+
};
|
|
2168
|
+
}
|
|
2169
|
+
if (schema.type === "array") {
|
|
2170
|
+
const array = schema;
|
|
2171
|
+
return {
|
|
2172
|
+
...array,
|
|
2173
|
+
items: array.items ? transform(array.items, flag, names) : void 0
|
|
2174
|
+
};
|
|
2175
|
+
}
|
|
2176
|
+
const value = single(schema);
|
|
2177
|
+
const next = { ...value };
|
|
2178
|
+
if (value.properties) {
|
|
2179
|
+
const properties = {};
|
|
2180
|
+
for (const [key, prop] of Object.entries(value.properties)) {
|
|
2181
|
+
if (single(prop)[flag]) continue;
|
|
2182
|
+
properties[key] = transform(prop, flag, names);
|
|
2183
|
+
}
|
|
2184
|
+
next.properties = properties;
|
|
2185
|
+
if (Array.isArray(value.required)) next.required = value.required.filter((key) => key in properties);
|
|
2186
|
+
}
|
|
2187
|
+
for (const key of [
|
|
2188
|
+
"allOf",
|
|
2189
|
+
"anyOf",
|
|
2190
|
+
"oneOf"
|
|
2191
|
+
]) {
|
|
2192
|
+
const members = value[key];
|
|
2193
|
+
if (members) next[key] = members.map((m) => transform(m, flag, names));
|
|
2194
|
+
}
|
|
2195
|
+
const additional = value.additionalProperties;
|
|
2196
|
+
if (additional && typeof additional === "object") next.additionalProperties = transform(additional, flag, names);
|
|
2197
|
+
return next;
|
|
2198
|
+
}
|
|
2199
|
+
function transformMedia(media, flag, names) {
|
|
2200
|
+
return media.map((entry) => entry.schema ? {
|
|
2201
|
+
...entry,
|
|
2202
|
+
schema: transform(entry.schema, flag, names)
|
|
2203
|
+
} : entry);
|
|
2204
|
+
}
|
|
2205
|
+
function transformOperation(operation, input, output) {
|
|
2206
|
+
return {
|
|
2207
|
+
...operation,
|
|
2208
|
+
...operation.requestBody ? { requestBody: transformMedia(operation.requestBody, "readOnly", input) } : {},
|
|
2209
|
+
...operation.responses ? { responses: transformMedia(operation.responses, "writeOnly", output) } : {},
|
|
2210
|
+
...operation.responseTypes ? { responseTypes: Object.fromEntries(Object.entries(operation.responseTypes).map(([code, media]) => [code, transformMedia(media, "writeOnly", output)])) } : {}
|
|
2211
|
+
};
|
|
2212
|
+
}
|
|
2213
|
+
/**
|
|
2214
|
+
* Add `XxxInput` / `XxxOutput` schema aliases and point operations at them:
|
|
2215
|
+
* requests drop `readOnly` properties, responses drop `writeOnly` ones.
|
|
2216
|
+
*
|
|
2217
|
+
* Existing type names are untouched; variants are only created when the name
|
|
2218
|
+
* is free. With no `readOnly` / `writeOnly` in the document this is a no-op.
|
|
2219
|
+
*/
|
|
2220
|
+
function splitReadWrite(parsed) {
|
|
2221
|
+
const input = buildVariant(parsed.schemas, "readOnly", "Input");
|
|
2222
|
+
const output = buildVariant(parsed.schemas, "writeOnly", "Output");
|
|
2223
|
+
if (input.keys.size === 0 && output.keys.size === 0) return parsed;
|
|
2224
|
+
const schemas = { ...parsed.schemas };
|
|
2225
|
+
for (const [key, variantKey] of input.keys) schemas[variantKey] = transform(parsed.schemas[key], "readOnly", input.names);
|
|
2226
|
+
for (const [key, variantKey] of output.keys) schemas[variantKey] = transform(parsed.schemas[key], "writeOnly", output.names);
|
|
2227
|
+
const apis = Object.fromEntries(Object.entries(parsed.apis).map(([path, operations]) => [path, operations.map((operation) => transformOperation(operation, input.names, output.names))]));
|
|
2228
|
+
return {
|
|
2229
|
+
...parsed,
|
|
2230
|
+
schemas,
|
|
2231
|
+
apis
|
|
2232
|
+
};
|
|
2233
|
+
}
|
|
2234
|
+
// src/openapi/V2.ts
|
|
1384
2235
|
var V2 = class {
|
|
1385
2236
|
doc;
|
|
1386
2237
|
constructor(doc) {
|
|
@@ -1427,11 +2278,11 @@ var V2 = class {
|
|
|
1427
2278
|
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
1428
2279
|
};
|
|
1429
2280
|
} else {
|
|
1430
|
-
const { required = [], allOf, anyOf, description, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
2281
|
+
const { required = [], allOf, anyOf, description, discriminator, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
1431
2282
|
let { type } = schema;
|
|
1432
2283
|
if (enum_ && type !== "boolean") {
|
|
1433
2284
|
const enumObject = {
|
|
1434
|
-
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey))
|
|
2285
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
|
|
1435
2286
|
enum: [...new Set(enum_)]
|
|
1436
2287
|
};
|
|
1437
2288
|
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
@@ -1447,8 +2298,11 @@ var V2 = class {
|
|
|
1447
2298
|
type,
|
|
1448
2299
|
required,
|
|
1449
2300
|
description,
|
|
2301
|
+
discriminator: discriminator ? { propertyName: discriminator } : void 0,
|
|
1450
2302
|
enum: enum_,
|
|
1451
2303
|
format,
|
|
2304
|
+
readOnly: schema.readOnly,
|
|
2305
|
+
writeOnly: schema.writeOnly,
|
|
1452
2306
|
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
1453
2307
|
...s,
|
|
1454
2308
|
ref: s.$ref,
|
|
@@ -1485,6 +2339,9 @@ var V2 = class {
|
|
|
1485
2339
|
parameter = resolved;
|
|
1486
2340
|
}
|
|
1487
2341
|
const p = parameter;
|
|
2342
|
+
const collectionFormat = p.collectionFormat;
|
|
2343
|
+
const style = collectionFormat === "ssv" ? "spaceDelimited" : collectionFormat === "pipes" ? "pipeDelimited" : "form";
|
|
2344
|
+
const explode = collectionFormat === "multi";
|
|
1488
2345
|
const { name, required, description, type, items, enum: enum_, properties, schema } = p;
|
|
1489
2346
|
if (enum_) {
|
|
1490
2347
|
const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
|
|
@@ -1502,6 +2359,8 @@ var V2 = class {
|
|
|
1502
2359
|
required,
|
|
1503
2360
|
description,
|
|
1504
2361
|
in: p.in,
|
|
2362
|
+
style,
|
|
2363
|
+
explode,
|
|
1505
2364
|
schema: { type: sameEnum?.name ?? type }
|
|
1506
2365
|
};
|
|
1507
2366
|
}
|
|
@@ -1510,6 +2369,8 @@ var V2 = class {
|
|
|
1510
2369
|
required,
|
|
1511
2370
|
description,
|
|
1512
2371
|
in: p.in,
|
|
2372
|
+
style,
|
|
2373
|
+
explode,
|
|
1513
2374
|
schema: {
|
|
1514
2375
|
type,
|
|
1515
2376
|
items
|
|
@@ -1520,6 +2381,8 @@ var V2 = class {
|
|
|
1520
2381
|
required,
|
|
1521
2382
|
description,
|
|
1522
2383
|
in: p.in,
|
|
2384
|
+
style,
|
|
2385
|
+
explode,
|
|
1523
2386
|
schema: { type: Base.capitalize(Base.ref2name(schema.$ref)) }
|
|
1524
2387
|
};
|
|
1525
2388
|
return {
|
|
@@ -1527,6 +2390,8 @@ var V2 = class {
|
|
|
1527
2390
|
required,
|
|
1528
2391
|
description,
|
|
1529
2392
|
in: p.in,
|
|
2393
|
+
style,
|
|
2394
|
+
explode,
|
|
1530
2395
|
schema: {
|
|
1531
2396
|
type,
|
|
1532
2397
|
properties
|
|
@@ -1536,16 +2401,16 @@ var V2 = class {
|
|
|
1536
2401
|
/**
|
|
1537
2402
|
* OpenAPI schema to base response
|
|
1538
2403
|
*/
|
|
1539
|
-
getResponseByRef(schema) {
|
|
2404
|
+
getResponseByRef(schema, enums = []) {
|
|
1540
2405
|
if (Base.isRef(schema)) schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
|
|
1541
2406
|
const { schema: responseSchema } = schema;
|
|
1542
2407
|
return [{
|
|
1543
2408
|
type: "application/json",
|
|
1544
|
-
schema: responseSchema && this.getSchemaByRef(responseSchema, true)
|
|
2409
|
+
schema: responseSchema && this.getSchemaByRef(responseSchema, true, enums)
|
|
1545
2410
|
}];
|
|
1546
2411
|
}
|
|
1547
2412
|
init() {
|
|
1548
|
-
const { definitions = {}, responses = {}, paths = {} } = this.doc;
|
|
2413
|
+
const { definitions = {}, responses = {}, paths = {}, security = [], securityDefinitions = {} } = this.doc;
|
|
1549
2414
|
const enums = [];
|
|
1550
2415
|
const definitions_ = Object.keys(definitions).reduce((acc, key) => {
|
|
1551
2416
|
const schema = definitions[key];
|
|
@@ -1558,7 +2423,7 @@ var V2 = class {
|
|
|
1558
2423
|
const response = responses[key];
|
|
1559
2424
|
return {
|
|
1560
2425
|
...acc,
|
|
1561
|
-
[key]: this.getResponseByRef(response)
|
|
2426
|
+
[key]: this.getResponseByRef(response, enums)
|
|
1562
2427
|
};
|
|
1563
2428
|
}, {});
|
|
1564
2429
|
const apis = Object.keys(paths).reduce((acc, path) => {
|
|
@@ -1579,42 +2444,42 @@ var V2 = class {
|
|
|
1579
2444
|
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
1580
2445
|
const inBody = baseParameters.filter((p) => p.in === "body" || p.in === "formData");
|
|
1581
2446
|
const notInBody = baseParameters.filter((p) => p.in !== "body" && p.in !== "formData");
|
|
1582
|
-
const httpCodes = Object.keys(responses);
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
}
|
|
2447
|
+
const httpCodes = Object.keys(responses).filter((code) => code in responses);
|
|
2448
|
+
const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
|
|
2449
|
+
const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
|
|
2450
|
+
const inBodyOnlyHasBody = inBody && inBody.length === 1 && inBody[0].in === "body" && inBody[0].name === "body";
|
|
2451
|
+
methodApis.push({
|
|
2452
|
+
method,
|
|
2453
|
+
operationId,
|
|
2454
|
+
summary: summary_,
|
|
2455
|
+
deprecated,
|
|
2456
|
+
description: description_,
|
|
2457
|
+
parameters: uniqueParameterName.map((name) => notInBody.find((p) => p.name === name)).filter(Boolean),
|
|
2458
|
+
responses: responseTypes[successCode] ?? [],
|
|
2459
|
+
responseTypes,
|
|
2460
|
+
tags: methodObject.tags,
|
|
2461
|
+
security: methodObject.security ?? security,
|
|
2462
|
+
requestBody: inBody.length > 0 ? inBodyOnlyHasBody ? [{
|
|
2463
|
+
type: "application/json",
|
|
2464
|
+
schema: inBody[0].schema
|
|
2465
|
+
}] : [{
|
|
2466
|
+
type: "application/json",
|
|
2467
|
+
schema: {
|
|
2468
|
+
type: "object",
|
|
2469
|
+
properties: inBody.reduce((a, p) => {
|
|
2470
|
+
return {
|
|
2471
|
+
...a,
|
|
2472
|
+
[p.name]: {
|
|
2473
|
+
type: p.schema?.type ?? "unknown",
|
|
2474
|
+
required: p.schema?.required,
|
|
2475
|
+
items: p.schema?.items,
|
|
2476
|
+
description: p.schema?.description
|
|
2477
|
+
}
|
|
2478
|
+
};
|
|
2479
|
+
}, {})
|
|
2480
|
+
}
|
|
2481
|
+
}] : void 0
|
|
2482
|
+
});
|
|
1618
2483
|
}
|
|
1619
2484
|
});
|
|
1620
2485
|
return {
|
|
@@ -1628,12 +2493,12 @@ var V2 = class {
|
|
|
1628
2493
|
responses: responses_,
|
|
1629
2494
|
parameters: {},
|
|
1630
2495
|
requestBodies: {},
|
|
2496
|
+
securitySchemes: securityDefinitions,
|
|
1631
2497
|
apis
|
|
1632
2498
|
};
|
|
1633
2499
|
}
|
|
1634
2500
|
};
|
|
1635
|
-
|
|
1636
|
-
//#region src/openapi/V3.ts
|
|
2501
|
+
// src/openapi/V3.ts
|
|
1637
2502
|
var V3 = class {
|
|
1638
2503
|
doc;
|
|
1639
2504
|
constructor(doc) {
|
|
@@ -1693,7 +2558,9 @@ var V3 = class {
|
|
|
1693
2558
|
description,
|
|
1694
2559
|
deprecated,
|
|
1695
2560
|
in: schema.in,
|
|
1696
|
-
schema: { type: sameEnum?.name ?? type }
|
|
2561
|
+
schema: { type: sameEnum?.name ?? type },
|
|
2562
|
+
style: schema.style,
|
|
2563
|
+
explode: schema.explode
|
|
1697
2564
|
};
|
|
1698
2565
|
}
|
|
1699
2566
|
return {
|
|
@@ -1702,13 +2569,15 @@ var V3 = class {
|
|
|
1702
2569
|
description,
|
|
1703
2570
|
deprecated,
|
|
1704
2571
|
in: schema.in,
|
|
2572
|
+
style: schema.style,
|
|
2573
|
+
explode: schema.explode,
|
|
1705
2574
|
schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
|
|
1706
2575
|
};
|
|
1707
2576
|
}
|
|
1708
2577
|
/**
|
|
1709
2578
|
* OpenAPI schema to base response
|
|
1710
2579
|
*/
|
|
1711
|
-
getResponseByRef(schema) {
|
|
2580
|
+
getResponseByRef(schema, enums = []) {
|
|
1712
2581
|
if (Base.isRef(schema)) {
|
|
1713
2582
|
const resolvedSchema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1714
2583
|
if (!resolvedSchema) return [];
|
|
@@ -1717,7 +2586,7 @@ var V3 = class {
|
|
|
1717
2586
|
const { content = {} } = schema;
|
|
1718
2587
|
return Object.keys(content).map((c) => ({
|
|
1719
2588
|
type: c,
|
|
1720
|
-
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
|
|
2589
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
|
|
1721
2590
|
}));
|
|
1722
2591
|
}
|
|
1723
2592
|
/**
|
|
@@ -1742,25 +2611,27 @@ var V3 = class {
|
|
|
1742
2611
|
if (!schema) return { type: "unknown" };
|
|
1743
2612
|
if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
|
|
1744
2613
|
if (this.isOpenAPIArraySchema(schema)) {
|
|
1745
|
-
const { type, description, items, required } = schema;
|
|
2614
|
+
const { type, description, items, required, nullable } = schema;
|
|
1746
2615
|
return {
|
|
1747
2616
|
type,
|
|
2617
|
+
nullable,
|
|
1748
2618
|
required: !!required,
|
|
1749
2619
|
description,
|
|
1750
2620
|
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
1751
2621
|
};
|
|
1752
2622
|
} else {
|
|
1753
|
-
const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
2623
|
+
const { required = [], allOf, anyOf, description, deprecated, discriminator, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
1754
2624
|
let { type } = schema;
|
|
1755
2625
|
if (enum_ && type !== "boolean") {
|
|
1756
2626
|
const enumObject = {
|
|
1757
|
-
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey))
|
|
2627
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
|
|
1758
2628
|
enum: [...new Set(enum_)]
|
|
1759
2629
|
};
|
|
1760
2630
|
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
1761
2631
|
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
1762
2632
|
return {
|
|
1763
2633
|
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
2634
|
+
nullable: schema.nullable,
|
|
1764
2635
|
required,
|
|
1765
2636
|
description,
|
|
1766
2637
|
deprecated
|
|
@@ -1769,11 +2640,16 @@ var V3 = class {
|
|
|
1769
2640
|
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
1770
2641
|
return {
|
|
1771
2642
|
type,
|
|
2643
|
+
nullable: schema.nullable,
|
|
2644
|
+
additionalProperties: schema.additionalProperties && typeof schema.additionalProperties === "object" ? this.toBaseSchema(schema.additionalProperties, enums) : schema.additionalProperties,
|
|
1772
2645
|
required,
|
|
1773
2646
|
description,
|
|
1774
2647
|
deprecated,
|
|
2648
|
+
discriminator,
|
|
1775
2649
|
enum: enum_,
|
|
1776
2650
|
format,
|
|
2651
|
+
readOnly: schema.readOnly,
|
|
2652
|
+
writeOnly: schema.writeOnly,
|
|
1777
2653
|
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
1778
2654
|
...s,
|
|
1779
2655
|
ref: s.$ref,
|
|
@@ -1803,9 +2679,9 @@ var V3 = class {
|
|
|
1803
2679
|
}
|
|
1804
2680
|
}
|
|
1805
2681
|
init() {
|
|
1806
|
-
const { components = {}, paths = {} } = this.doc;
|
|
2682
|
+
const { components = {}, paths = {}, security = [] } = this.doc;
|
|
1807
2683
|
const enums = [];
|
|
1808
|
-
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {} } = components;
|
|
2684
|
+
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {}, securitySchemes = {} } = components;
|
|
1809
2685
|
const schemas_ = Object.keys(schemas).reduce((acc, key) => {
|
|
1810
2686
|
const schema = schemas[key];
|
|
1811
2687
|
return {
|
|
@@ -1824,7 +2700,7 @@ var V3 = class {
|
|
|
1824
2700
|
const response = responses[key];
|
|
1825
2701
|
return {
|
|
1826
2702
|
...acc,
|
|
1827
|
-
[key]: this.getResponseByRef(response)
|
|
2703
|
+
[key]: this.getResponseByRef(response, enums)
|
|
1828
2704
|
};
|
|
1829
2705
|
}, {});
|
|
1830
2706
|
const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
|
|
@@ -1851,22 +2727,22 @@ var V3 = class {
|
|
|
1851
2727
|
const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
|
|
1852
2728
|
const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
|
|
1853
2729
|
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
1854
|
-
const httpCodes = Object.keys(responses);
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
}
|
|
2730
|
+
const httpCodes = Object.keys(responses).filter((code) => code in responses);
|
|
2731
|
+
const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
|
|
2732
|
+
const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
|
|
2733
|
+
methodApis.push({
|
|
2734
|
+
method,
|
|
2735
|
+
operationId,
|
|
2736
|
+
summary: summary_ ?? summary,
|
|
2737
|
+
description: description_ ?? description,
|
|
2738
|
+
deprecated,
|
|
2739
|
+
parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
|
|
2740
|
+
responses: responseTypes[successCode] ?? [],
|
|
2741
|
+
responseTypes,
|
|
2742
|
+
tags: methodObject.tags,
|
|
2743
|
+
security: methodObject.security ?? security,
|
|
2744
|
+
requestBody: baseRequestBody
|
|
2745
|
+
});
|
|
1870
2746
|
}
|
|
1871
2747
|
});
|
|
1872
2748
|
return {
|
|
@@ -1880,12 +2756,12 @@ var V3 = class {
|
|
|
1880
2756
|
responses: responses_,
|
|
1881
2757
|
parameters: parameters_,
|
|
1882
2758
|
requestBodies: requestBodies_,
|
|
2759
|
+
securitySchemes,
|
|
1883
2760
|
apis
|
|
1884
2761
|
};
|
|
1885
2762
|
}
|
|
1886
2763
|
};
|
|
1887
|
-
|
|
1888
|
-
//#region src/openapi/V3_1.ts
|
|
2764
|
+
// src/openapi/V3_1.ts
|
|
1889
2765
|
var V3_1 = class {
|
|
1890
2766
|
doc;
|
|
1891
2767
|
constructor(doc) {
|
|
@@ -1902,7 +2778,8 @@ var V3_1 = class {
|
|
|
1902
2778
|
* Is array schema.
|
|
1903
2779
|
*/
|
|
1904
2780
|
isOpenAPIArraySchema(schema) {
|
|
1905
|
-
|
|
2781
|
+
if (typeof schema !== "object") return false;
|
|
2782
|
+
return schema.type === "array" || Array.isArray(schema.type) && schema.type.includes("array");
|
|
1906
2783
|
}
|
|
1907
2784
|
/**
|
|
1908
2785
|
* OpenAPI schema to base schema.
|
|
@@ -1939,7 +2816,9 @@ var V3_1 = class {
|
|
|
1939
2816
|
description,
|
|
1940
2817
|
deprecated,
|
|
1941
2818
|
in: schema.in,
|
|
1942
|
-
schema: { type: sameEnum?.name ?? type }
|
|
2819
|
+
schema: { type: sameEnum?.name ?? type },
|
|
2820
|
+
style: schema.style,
|
|
2821
|
+
explode: schema.explode
|
|
1943
2822
|
};
|
|
1944
2823
|
}
|
|
1945
2824
|
return {
|
|
@@ -1948,18 +2827,20 @@ var V3_1 = class {
|
|
|
1948
2827
|
description,
|
|
1949
2828
|
deprecated,
|
|
1950
2829
|
in: schema.in,
|
|
2830
|
+
style: schema.style,
|
|
2831
|
+
explode: schema.explode,
|
|
1951
2832
|
schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
|
|
1952
2833
|
};
|
|
1953
2834
|
}
|
|
1954
2835
|
/**
|
|
1955
2836
|
* OpenAPI schema to base response
|
|
1956
2837
|
*/
|
|
1957
|
-
getResponseByRef(schema) {
|
|
2838
|
+
getResponseByRef(schema, enums = []) {
|
|
1958
2839
|
if (Base.isRef(schema)) schema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1959
2840
|
const { content = {} } = schema;
|
|
1960
2841
|
return Object.keys(content).map((c) => ({
|
|
1961
2842
|
type: c,
|
|
1962
|
-
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
|
|
2843
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
|
|
1963
2844
|
}));
|
|
1964
2845
|
}
|
|
1965
2846
|
/**
|
|
@@ -1980,25 +2861,38 @@ var V3_1 = class {
|
|
|
1980
2861
|
if (!schema) return { type: "unknown" };
|
|
1981
2862
|
if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
|
|
1982
2863
|
if (this.isOpenAPIArraySchema(schema)) {
|
|
1983
|
-
const {
|
|
2864
|
+
const { description, items, required } = schema;
|
|
2865
|
+
const rawType = schema.type;
|
|
1984
2866
|
return {
|
|
1985
|
-
type,
|
|
2867
|
+
type: "array",
|
|
2868
|
+
nullable: Array.isArray(rawType) && rawType.includes("null"),
|
|
1986
2869
|
required: !!required,
|
|
1987
2870
|
description,
|
|
1988
2871
|
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
1989
2872
|
};
|
|
1990
2873
|
} else {
|
|
1991
|
-
const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
1992
|
-
|
|
2874
|
+
const { required = [], allOf, anyOf, description, deprecated, discriminator, enum: enum_, format, oneOf, properties = {}, const: constValue, additionalProperties } = schema;
|
|
2875
|
+
const rawType = schema.type;
|
|
2876
|
+
const typeArray = Array.isArray(rawType) ? rawType.filter((t) => t !== "null") : void 0;
|
|
2877
|
+
let type = Array.isArray(rawType) ? typeArray?.[0] : schema.type;
|
|
2878
|
+
const nullableByType = Array.isArray(rawType) && rawType.includes("null");
|
|
2879
|
+
if (constValue !== void 0) return {
|
|
2880
|
+
type: typeof constValue === "number" ? "number" : typeof constValue === "boolean" ? "boolean" : "string",
|
|
2881
|
+
const: constValue,
|
|
2882
|
+
required,
|
|
2883
|
+
description,
|
|
2884
|
+
deprecated
|
|
2885
|
+
};
|
|
1993
2886
|
if (enum_ && type !== "boolean") {
|
|
1994
2887
|
const enumObject = {
|
|
1995
|
-
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey))
|
|
2888
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
|
|
1996
2889
|
enum: [...new Set(enum_)]
|
|
1997
2890
|
};
|
|
1998
2891
|
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
1999
2892
|
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
2000
2893
|
return {
|
|
2001
2894
|
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
2895
|
+
nullable: nullableByType,
|
|
2002
2896
|
required,
|
|
2003
2897
|
description,
|
|
2004
2898
|
deprecated
|
|
@@ -2007,11 +2901,18 @@ var V3_1 = class {
|
|
|
2007
2901
|
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
2008
2902
|
return {
|
|
2009
2903
|
type,
|
|
2904
|
+
types: typeArray,
|
|
2905
|
+
nullable: nullableByType,
|
|
2906
|
+
const: constValue,
|
|
2907
|
+
additionalProperties: additionalProperties && typeof additionalProperties === "object" ? this.toBaseSchema(additionalProperties, enums) : additionalProperties,
|
|
2010
2908
|
required,
|
|
2011
2909
|
description,
|
|
2012
2910
|
deprecated,
|
|
2911
|
+
discriminator,
|
|
2013
2912
|
enum: enum_,
|
|
2014
2913
|
format,
|
|
2914
|
+
readOnly: schema.readOnly,
|
|
2915
|
+
writeOnly: schema.writeOnly,
|
|
2015
2916
|
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
2016
2917
|
...s,
|
|
2017
2918
|
ref: s.$ref,
|
|
@@ -2041,9 +2942,9 @@ var V3_1 = class {
|
|
|
2041
2942
|
}
|
|
2042
2943
|
}
|
|
2043
2944
|
init() {
|
|
2044
|
-
const { components = {}, paths = {} } = this.doc;
|
|
2945
|
+
const { components = {}, paths = {}, security = [] } = this.doc;
|
|
2045
2946
|
const enums = [];
|
|
2046
|
-
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {} } = components;
|
|
2947
|
+
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {}, securitySchemes = {} } = components;
|
|
2047
2948
|
const schemas_ = Object.keys(schemas).reduce((acc, key) => {
|
|
2048
2949
|
const schema = schemas[key];
|
|
2049
2950
|
return {
|
|
@@ -2062,7 +2963,7 @@ var V3_1 = class {
|
|
|
2062
2963
|
const response = responses[key];
|
|
2063
2964
|
return {
|
|
2064
2965
|
...acc,
|
|
2065
|
-
[key]: this.getResponseByRef(response)
|
|
2966
|
+
[key]: this.getResponseByRef(response, enums)
|
|
2066
2967
|
};
|
|
2067
2968
|
}, {});
|
|
2068
2969
|
const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
|
|
@@ -2089,22 +2990,22 @@ var V3_1 = class {
|
|
|
2089
2990
|
const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
|
|
2090
2991
|
const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
|
|
2091
2992
|
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
2092
|
-
const httpCodes = Object.keys(responses);
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
}
|
|
2993
|
+
const httpCodes = Object.keys(responses).filter((code) => code in responses);
|
|
2994
|
+
const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
|
|
2995
|
+
const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
|
|
2996
|
+
methodApis.push({
|
|
2997
|
+
method,
|
|
2998
|
+
operationId,
|
|
2999
|
+
summary: summary_ ?? summary,
|
|
3000
|
+
description: description_ ?? description,
|
|
3001
|
+
deprecated,
|
|
3002
|
+
parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
|
|
3003
|
+
responses: responseTypes[successCode] ?? [],
|
|
3004
|
+
responseTypes,
|
|
3005
|
+
tags: methodObject.tags,
|
|
3006
|
+
security: methodObject.security ?? security,
|
|
3007
|
+
requestBody: baseRequestBody
|
|
3008
|
+
});
|
|
2108
3009
|
}
|
|
2109
3010
|
});
|
|
2110
3011
|
return {
|
|
@@ -2118,12 +3019,12 @@ var V3_1 = class {
|
|
|
2118
3019
|
responses: responses_,
|
|
2119
3020
|
parameters: parameters_,
|
|
2120
3021
|
requestBodies: requestBodies_,
|
|
3022
|
+
securitySchemes,
|
|
2121
3023
|
apis
|
|
2122
3024
|
};
|
|
2123
3025
|
}
|
|
2124
3026
|
};
|
|
2125
|
-
|
|
2126
|
-
//#region src/openapi/index.ts
|
|
3027
|
+
// src/openapi/index.ts
|
|
2127
3028
|
const logger$1 = createScopedLogger("OpenAPI");
|
|
2128
3029
|
function getDocVersion(doc) {
|
|
2129
3030
|
const raw = doc.openapi || doc.swagger;
|
|
@@ -2153,6 +3054,18 @@ function getAdaptor(type) {
|
|
|
2153
3054
|
default: return new FetchAdapter();
|
|
2154
3055
|
}
|
|
2155
3056
|
}
|
|
3057
|
+
/**
|
|
3058
|
+
* Use the document's first server when the caller did not configure a base URL.
|
|
3059
|
+
* Server variables fall back to their declared defaults.
|
|
3060
|
+
*/
|
|
3061
|
+
function inferBaseURL(doc) {
|
|
3062
|
+
const server = doc.servers?.[0];
|
|
3063
|
+
if (server?.url) return server.url.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
3064
|
+
return server.variables?.[name]?.default ?? `{${name}}`;
|
|
3065
|
+
}).replace(/\/+$/, "");
|
|
3066
|
+
const v2 = doc;
|
|
3067
|
+
if (v2.host) return `${v2.schemes?.[0] ?? "https"}://${v2.host}${(v2.basePath ?? "").replace(/\/+$/, "")}`;
|
|
3068
|
+
}
|
|
2156
3069
|
async function codeGen(initOptions) {
|
|
2157
3070
|
const startTime = Date.now();
|
|
2158
3071
|
const { verbose } = initOptions;
|
|
@@ -2160,7 +3073,7 @@ async function codeGen(initOptions) {
|
|
|
2160
3073
|
else logger$1.setLevel("info");
|
|
2161
3074
|
logger$1.info(`Fetch document from ${initOptions.docURL}`);
|
|
2162
3075
|
const { transport, source } = Base.resolveSpecURL(initOptions.docURL);
|
|
2163
|
-
const
|
|
3076
|
+
const rawDoc = transport === "file" ? await (async () => {
|
|
2164
3077
|
let raw;
|
|
2165
3078
|
try {
|
|
2166
3079
|
raw = await readFile(source, "utf8");
|
|
@@ -2168,34 +3081,50 @@ async function codeGen(initOptions) {
|
|
|
2168
3081
|
if (error?.code === "ENOENT") throw createErrors.specNotFound(source, error);
|
|
2169
3082
|
throw new Error(`Failed to read OpenAPI spec from ${source}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2170
3083
|
}
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
3084
|
+
return Base.parseDoc(raw, source);
|
|
3085
|
+
})() : await Base.fetchDoc(source, initOptions.requestOptions);
|
|
3086
|
+
const doc = await Base.bundleExternalRefs(rawDoc, source, initOptions.requestOptions);
|
|
3087
|
+
const options = {
|
|
3088
|
+
...initOptions,
|
|
3089
|
+
baseURL: initOptions.baseURL ?? inferBaseURL(doc)
|
|
3090
|
+
};
|
|
3091
|
+
const { enums, schemas, parameters, responses, requestBodies, securitySchemes, apis } = new OpenAPIProvider(options, doc);
|
|
2177
3092
|
const adaptor = getAdaptor(initOptions.adaptor ?? "fetch");
|
|
2178
|
-
const
|
|
3093
|
+
const split = splitReadWrite({
|
|
2179
3094
|
enums,
|
|
2180
3095
|
schemas,
|
|
2181
3096
|
parameters,
|
|
2182
3097
|
responses,
|
|
2183
3098
|
requestBodies,
|
|
3099
|
+
securitySchemes,
|
|
2184
3100
|
apis
|
|
2185
|
-
}
|
|
2186
|
-
|
|
3101
|
+
});
|
|
3102
|
+
const parsed = {
|
|
3103
|
+
...split,
|
|
3104
|
+
apis: filterApis(split.apis, options)
|
|
3105
|
+
};
|
|
3106
|
+
const multi = initOptions.splitBy === "tag" ? await Generator.genCodeMulti(parsed, options, adaptor) : void 0;
|
|
3107
|
+
const code = multi?.code ?? await Generator.genCode(parsed, options, adaptor);
|
|
3108
|
+
if (initOptions.output) {
|
|
3109
|
+
if (multi) for (const [name, content] of Object.entries(multi.files)) await Generator.write(content, join(initOptions.output, name));
|
|
3110
|
+
else await Generator.write(code, initOptions.output);
|
|
3111
|
+
}
|
|
2187
3112
|
const duration = Date.now() - startTime;
|
|
3113
|
+
const endpoints = Object.keys(apis).length;
|
|
3114
|
+
const schemasCount = Object.keys(schemas).length;
|
|
2188
3115
|
return {
|
|
2189
3116
|
code,
|
|
3117
|
+
...multi ? { files: multi.files } : {},
|
|
2190
3118
|
stats: {
|
|
2191
|
-
endpoints
|
|
2192
|
-
schemas:
|
|
3119
|
+
endpoints,
|
|
3120
|
+
schemas: schemasCount,
|
|
2193
3121
|
duration
|
|
2194
3122
|
}
|
|
2195
3123
|
};
|
|
2196
3124
|
}
|
|
2197
|
-
|
|
2198
|
-
|
|
3125
|
+
// package.json
|
|
3126
|
+
var version = "1.0.0";
|
|
3127
|
+
// src/vite-plugin/cache.ts
|
|
2199
3128
|
/**
|
|
2200
3129
|
* Cache for a single vite-plugin codegen run. Lives only for the duration
|
|
2201
3130
|
* of one plugin invocation — there is no module-level state.
|
|
@@ -2214,7 +3143,8 @@ var CodegenCache = class CodegenCache {
|
|
|
2214
3143
|
}
|
|
2215
3144
|
/** Hash the options that affect generated output (excluding the spec). */
|
|
2216
3145
|
static hashOptions(options) {
|
|
2217
|
-
const
|
|
3146
|
+
const keys = Object.keys(options).sort();
|
|
3147
|
+
const payload = [`generatorVersion=${version}`, ...keys.filter((k) => k !== "verbose" && k !== "typeCheck" && k !== "cache").map((k) => `${k}=${JSON.stringify(options[k])}`)].join("|");
|
|
2218
3148
|
return createHash("sha256").update(payload).digest("hex").slice(0, 16);
|
|
2219
3149
|
}
|
|
2220
3150
|
/** Hash the raw spec content so unrelated edits are detected. */
|
|
@@ -2270,24 +3200,10 @@ var CodegenCache = class CodegenCache {
|
|
|
2270
3200
|
await writeFile(cachePath, JSON.stringify(entry));
|
|
2271
3201
|
}
|
|
2272
3202
|
};
|
|
2273
|
-
|
|
2274
|
-
//#region src/vite-plugin/index.ts
|
|
3203
|
+
// src/vite-plugin/index.ts
|
|
2275
3204
|
const PLUGIN_NAME = "api-code-gen";
|
|
2276
3205
|
const logger = createScopedLogger("api-code-gen");
|
|
2277
3206
|
/**
|
|
2278
|
-
* Run TypeScript type checking on generated file
|
|
2279
|
-
*/
|
|
2280
|
-
async function runTypeCheck(filePath) {
|
|
2281
|
-
const { execaCommand } = await import("execa");
|
|
2282
|
-
const errors = [];
|
|
2283
|
-
try {
|
|
2284
|
-
await execaCommand(`npx tsc ${filePath} --noEmit`, { shell: true });
|
|
2285
|
-
} catch (error) {
|
|
2286
|
-
if (error instanceof Error) errors.push(error.message);
|
|
2287
|
-
}
|
|
2288
|
-
return errors;
|
|
2289
|
-
}
|
|
2290
|
-
/**
|
|
2291
3207
|
* Validate spec path exists
|
|
2292
3208
|
*/
|
|
2293
3209
|
async function validateSpecPath(specPath) {
|
|
@@ -2296,6 +3212,12 @@ async function validateSpecPath(specPath) {
|
|
|
2296
3212
|
const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
|
|
2297
3213
|
if (!await fs.pathExists(absolutePath)) throw createErrors.specNotFound(absolutePath);
|
|
2298
3214
|
}
|
|
3215
|
+
/** Resolve a local spec to an absolute path; remote specs return null. */
|
|
3216
|
+
function toWatchPath(spec) {
|
|
3217
|
+
if (!spec || spec.startsWith("http://") || spec.startsWith("https://")) return null;
|
|
3218
|
+
const filePath = spec.replace(/^file:\/\//, "");
|
|
3219
|
+
return path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
|
|
3220
|
+
}
|
|
2299
3221
|
/**
|
|
2300
3222
|
* Generate code for a single API configuration
|
|
2301
3223
|
*/
|
|
@@ -2311,19 +3233,21 @@ async function generateForOption(option) {
|
|
|
2311
3233
|
}
|
|
2312
3234
|
});
|
|
2313
3235
|
await validateSpecPath(config.spec);
|
|
2314
|
-
if (config.output) {
|
|
2315
|
-
const outputDir = path.dirname(config.output);
|
|
2316
|
-
await fs.ensureDir(outputDir);
|
|
2317
|
-
}
|
|
2318
3236
|
let docURL = config.spec;
|
|
2319
3237
|
if (!docURL.startsWith("http://") && !docURL.startsWith("https://") && !docURL.startsWith("file://") && !docURL.startsWith("/") && !/^[A-Za-z]:[\\/]/.test(docURL)) docURL = path.resolve(process.cwd(), docURL);
|
|
2320
3238
|
const resolvedCacheDir = cacheDir ?? path.join(process.cwd(), "node_modules", ".cache", "apicodegen");
|
|
2321
|
-
const codegenCache = cache ? new CodegenCache(resolvedCacheDir) : null;
|
|
3239
|
+
const codegenCache = cache && !config.splitBy ? new CodegenCache(resolvedCacheDir) : null;
|
|
2322
3240
|
const optionsHash = CodegenCache.hashOptions({
|
|
2323
3241
|
name,
|
|
2324
3242
|
spec: docURL,
|
|
2325
3243
|
output: config.output,
|
|
2326
3244
|
adaptor: config.adaptor,
|
|
3245
|
+
errorMode: config.errorMode,
|
|
3246
|
+
splitBy: config.splitBy,
|
|
3247
|
+
includeTags: config.includeTags,
|
|
3248
|
+
excludeTags: config.excludeTags,
|
|
3249
|
+
includePaths: config.includePaths,
|
|
3250
|
+
excludePaths: config.excludePaths,
|
|
2327
3251
|
baseURL: config.baseURL,
|
|
2328
3252
|
importClientSource: config.importClientSource
|
|
2329
3253
|
});
|
|
@@ -2365,7 +3289,13 @@ async function generateForOption(option) {
|
|
|
2365
3289
|
if (verbose) logger.warn(`Cache write failed for ${name}: ${cacheError.message}`);
|
|
2366
3290
|
}
|
|
2367
3291
|
}
|
|
2368
|
-
if (config.output)
|
|
3292
|
+
if (config.output) {
|
|
3293
|
+
if (result.files) {
|
|
3294
|
+
const dir = path.dirname(config.output);
|
|
3295
|
+
for (const [name, content] of Object.entries(result.files)) if (name !== "index.ts") await fs.outputFile(path.join(dir, name), content);
|
|
3296
|
+
}
|
|
3297
|
+
await fs.outputFile(config.output, result.code);
|
|
3298
|
+
}
|
|
2369
3299
|
if (typeCheck && config.output) {
|
|
2370
3300
|
const typeErrors = await runTypeCheck(config.output);
|
|
2371
3301
|
if (typeErrors.length > 0) {
|
|
@@ -2415,49 +3345,72 @@ function apiCodeGenPlugin(options) {
|
|
|
2415
3345
|
logger.warn("No API configurations provided to apiCodeGenPlugin");
|
|
2416
3346
|
return { name: PLUGIN_NAME };
|
|
2417
3347
|
}
|
|
3348
|
+
let mode = "unknown";
|
|
3349
|
+
const watched = /* @__PURE__ */ new Set();
|
|
3350
|
+
const printResults = (results) => {
|
|
3351
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3352
|
+
console.log(`\x1b[1m\x1b[36mAPI Code Gen\x1b[0m`);
|
|
3353
|
+
console.log(`\x1b[90mMode:\x1b[0m ${mode}`);
|
|
3354
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3355
|
+
const successCount = results.filter((r) => r.success).length;
|
|
3356
|
+
const failCount = results.length - successCount;
|
|
3357
|
+
for (const result of results) if (result.success) {
|
|
3358
|
+
const { name, output, stats, cached } = result;
|
|
3359
|
+
if (stats) {
|
|
3360
|
+
const cachedTag = cached ? " \x1B[90m[cached]\x1B[0m" : "";
|
|
3361
|
+
console.log(`\x1b[32m✓\x1b[0m ${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms${cachedTag}`);
|
|
3362
|
+
} else console.log(`\x1b[32m✓\x1b[0m ${name} → ${output || "N/A"}`);
|
|
3363
|
+
} else {
|
|
3364
|
+
const { name, error } = result;
|
|
3365
|
+
const wrapped = isApicodegenError(error) ? error : wrapError(error, {
|
|
3366
|
+
code: "E_GENERATION_FAILED",
|
|
3367
|
+
message: `Failed to generate API "${name}"`
|
|
3368
|
+
});
|
|
3369
|
+
console.log(`\x1b[31m✗\x1b[0m ${name}`);
|
|
3370
|
+
console.log(`\x1b[90m${formatError(wrapped, true)}\x1b[0m`);
|
|
3371
|
+
}
|
|
3372
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3373
|
+
const totalDuration = results.reduce((sum, r) => sum + (r.stats?.duration || 0), 0);
|
|
3374
|
+
const totalEndpoints = results.reduce((sum, r) => sum + (r.stats?.endpoints || 0), 0);
|
|
3375
|
+
const totalSchemas = results.reduce((sum, r) => sum + (r.stats?.schemas || 0), 0);
|
|
3376
|
+
if (failCount === 0) console.log(`\x1b[32m✓\x1b[0m API Code Gen - Complete (\x1b[90m${successCount}/${results.length} succeeded\x1b[0m, ${totalEndpoints} endpoints, ${totalSchemas} schemas, ${totalDuration}ms\x1b[0m)`);
|
|
3377
|
+
else console.log(`\x1b[33m⚠\x1b[0m API Code Gen - Complete (\x1b[90m${successCount} succeeded, ${failCount} failed\x1b[0m, ${totalEndpoints} endpoints, ${totalSchemas} schemas, ${totalDuration}ms\x1b[0m)`);
|
|
3378
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3379
|
+
};
|
|
3380
|
+
const regenerate = async (option) => {
|
|
3381
|
+
const result = await generateForOption(option);
|
|
3382
|
+
printResults([result]);
|
|
3383
|
+
};
|
|
2418
3384
|
return {
|
|
2419
3385
|
name: PLUGIN_NAME,
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
console.log(`\x1b[1m\x1b[36mAPI Code Gen\x1b[0m`);
|
|
2423
|
-
console.log(`\x1b[90mMode:\x1b[0m ${env?.command || "unknown"}`);
|
|
2424
|
-
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
2425
|
-
const results = await Promise.all(options.map(generateForOption));
|
|
2426
|
-
const successCount = results.filter((r) => r.success).length;
|
|
2427
|
-
const failCount = options.length - successCount;
|
|
2428
|
-
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
2429
|
-
for (const result of results) if (result.success) {
|
|
2430
|
-
const { name, output, stats, cached } = result;
|
|
2431
|
-
if (stats) {
|
|
2432
|
-
const cachedTag = cached ? " \x1B[90m[cached]\x1B[0m" : "";
|
|
2433
|
-
console.log(`\x1b[32m✓\x1b[0m ${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms${cachedTag}`);
|
|
2434
|
-
} else console.log(`\x1b[32m✓\x1b[0m ${name} → ${output || "N/A"}`);
|
|
2435
|
-
} else {
|
|
2436
|
-
const { name, error } = result;
|
|
2437
|
-
if (isApicodegenError(error)) {
|
|
2438
|
-
console.log(`\x1b[31m✗\x1b[0m ${name}`);
|
|
2439
|
-
console.log(`\x1b[90m${formatError(error, true)}\x1b[0m`);
|
|
2440
|
-
} else {
|
|
2441
|
-
const wrapped = wrapError(error, {
|
|
2442
|
-
code: "E_GENERATION_FAILED",
|
|
2443
|
-
message: `Failed to generate API "${name}"`
|
|
2444
|
-
});
|
|
2445
|
-
console.log(`\x1b[31m✗\x1b[0m ${name}`);
|
|
2446
|
-
console.log(`\x1b[90m${formatError(wrapped, true)}\x1b[0m`);
|
|
2447
|
-
}
|
|
2448
|
-
}
|
|
2449
|
-
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
2450
|
-
const totalDuration = results.reduce((sum, r) => sum + (r.stats?.duration || 0), 0);
|
|
2451
|
-
const totalEndpoints = results.reduce((sum, r) => sum + (r.stats?.endpoints || 0), 0);
|
|
2452
|
-
const totalSchemas = results.reduce((sum, r) => sum + (r.stats?.schemas || 0), 0);
|
|
2453
|
-
if (failCount === 0) console.log(`\x1b[32m✓\x1b[0m API Code Gen - Complete (\x1b[90m${successCount}/${options.length} succeeded\x1b[0m, ${totalEndpoints} endpoints, ${totalSchemas} schemas, ${totalDuration}ms\x1b[0m)`);
|
|
2454
|
-
else console.log(`\x1b[33m⚠\x1b[0m API Code Gen - Complete (\x1b[90m${successCount} succeeded, ${failCount} failed\x1b[0m, ${totalEndpoints} endpoints, ${totalSchemas} schemas, ${totalDuration}ms\x1b[0m)`);
|
|
2455
|
-
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3386
|
+
config(_config, env) {
|
|
3387
|
+
mode = env?.command || "unknown";
|
|
2456
3388
|
return {};
|
|
3389
|
+
},
|
|
3390
|
+
async buildStart() {
|
|
3391
|
+
for (const option of options) {
|
|
3392
|
+
const specPath = toWatchPath(option.spec);
|
|
3393
|
+
if (specPath) this.addWatchFile(specPath);
|
|
3394
|
+
}
|
|
3395
|
+
printResults(await Promise.all(options.map(generateForOption)));
|
|
3396
|
+
},
|
|
3397
|
+
configureServer(server) {
|
|
3398
|
+
for (const option of options) {
|
|
3399
|
+
const specPath = toWatchPath(option.spec);
|
|
3400
|
+
if (!specPath || watched.has(specPath)) continue;
|
|
3401
|
+
watched.add(specPath);
|
|
3402
|
+
server.watcher.add(specPath);
|
|
3403
|
+
const onChange = async (changed) => {
|
|
3404
|
+
if (path.resolve(changed) !== path.resolve(specPath)) return;
|
|
3405
|
+
await regenerate(option);
|
|
3406
|
+
server.ws.send({ type: "full-reload" });
|
|
3407
|
+
};
|
|
3408
|
+
server.watcher.on("change", onChange);
|
|
3409
|
+
server.watcher.on("add", onChange);
|
|
3410
|
+
}
|
|
2457
3411
|
}
|
|
2458
3412
|
};
|
|
2459
3413
|
}
|
|
2460
|
-
//#endregion
|
|
2461
3414
|
export { apiCodeGenPlugin, apiCodeGenPlugin as default };
|
|
2462
3415
|
|
|
2463
3416
|
//# sourceMappingURL=index.mjs.map
|