@moccona/apicodegen 0.1.1 → 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 +517 -121
- package/bin/cli.cjs +15 -12
- package/npm/index.cjs +2520 -1025
- package/npm/index.cjs.map +1 -1
- package/npm/index.d.cts +409 -93
- package/npm/index.d.cts.map +1 -1
- package/npm/index.d.mts +409 -93
- package/npm/index.d.mts.map +1 -1
- package/npm/index.mjs +2390 -904
- package/npm/index.mjs.map +1 -1
- package/npm/vite/index.d.mts +38 -10
- package/npm/vite/index.d.mts.map +1 -1
- package/npm/vite/index.mjs +2140 -648
- package/npm/vite/index.mjs.map +1 -1
- package/package.json +41 -22
package/npm/index.mjs
CHANGED
|
@@ -1,19 +1,16 @@
|
|
|
1
|
+
import { NodeFlags, SyntaxKind, addSyntheticLeadingComment, createPrinter, factory, isEnumDeclaration, isInterfaceDeclaration, isTypeAliasDeclaration } from "typescript";
|
|
2
|
+
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
1
4
|
import { Agent, request } from "undici";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
5
|
+
import { parse } from "yaml";
|
|
6
|
+
import path, { dirname, join } from "node:path";
|
|
4
7
|
import { format } from "prettier";
|
|
5
|
-
import path from "node:path";
|
|
6
8
|
import fs from "fs-extra";
|
|
7
9
|
import { createScopedLogger } from "@moccona/logger";
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
*/
|
|
13
|
-
var Adapter = class {};
|
|
14
|
-
//#endregion
|
|
15
|
-
//#region src/core/constants/keywords.ts
|
|
16
|
-
const typescriptKeywords = new Set([
|
|
10
|
+
import { execaCommand } from "execa";
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
// src/core/constants/keywords.ts
|
|
13
|
+
const typescriptKeywords = /* @__PURE__ */ new Set([
|
|
17
14
|
"break",
|
|
18
15
|
"case",
|
|
19
16
|
"catch",
|
|
@@ -89,8 +86,260 @@ const typescriptKeywords = new Set([
|
|
|
89
86
|
"undefined",
|
|
90
87
|
"bigint"
|
|
91
88
|
]);
|
|
92
|
-
|
|
93
|
-
|
|
89
|
+
// src/core/errors.ts
|
|
90
|
+
/**
|
|
91
|
+
* Error handling utilities for api-codegen
|
|
92
|
+
*/
|
|
93
|
+
const ErrorCodes = {
|
|
94
|
+
SPEC_NOT_FOUND: "E_SPEC_NOT_FOUND",
|
|
95
|
+
SPEC_FETCH_FAILED: "E_SPEC_FETCH_FAILED",
|
|
96
|
+
SPEC_PARSE_FAILED: "E_SPEC_PARSE_FAILED",
|
|
97
|
+
OUTPUT_DIR_MISSING: "E_OUTPUT_DIR_MISSING",
|
|
98
|
+
CONFIG_INVALID: "E_CONFIG_INVALID",
|
|
99
|
+
VALIDATION_FAILED: "E_VALIDATION_FAILED",
|
|
100
|
+
GENERATION_FAILED: "E_GENERATION_FAILED",
|
|
101
|
+
TYPE_CHECK_FAILED: "E_TYPE_CHECK_FAILED"
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* Custom error class for api-codegen with rich context
|
|
105
|
+
*/
|
|
106
|
+
var ApicodegenError = class ApicodegenError extends Error {
|
|
107
|
+
code;
|
|
108
|
+
location;
|
|
109
|
+
line;
|
|
110
|
+
column;
|
|
111
|
+
path;
|
|
112
|
+
suggestions;
|
|
113
|
+
cause;
|
|
114
|
+
constructor(context) {
|
|
115
|
+
super(context.message);
|
|
116
|
+
this.name = "ApicodegenError";
|
|
117
|
+
this.code = context.code;
|
|
118
|
+
this.location = context.location;
|
|
119
|
+
this.line = context.line;
|
|
120
|
+
this.column = context.column;
|
|
121
|
+
this.path = context.path;
|
|
122
|
+
this.suggestions = context.suggestions || [];
|
|
123
|
+
this.cause = context.cause;
|
|
124
|
+
if (Error.captureStackTrace) Error.captureStackTrace(this, ApicodegenError);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Convert error to formatted string for CLI output
|
|
128
|
+
*/
|
|
129
|
+
toString(verbose = false) {
|
|
130
|
+
const lines = [];
|
|
131
|
+
lines.push(`\x1b[1;31mError [${this.code}]\x1b[0m ${this.message}`);
|
|
132
|
+
if (this.location) lines.push(` \x1b[36m→ Location:\x1b[0m ${this.location}`);
|
|
133
|
+
if (this.path) lines.push(` \x1b[36m→ Path:\x1b[0m ${this.path}`);
|
|
134
|
+
if (this.line !== void 0) {
|
|
135
|
+
let lineInfo = ` \x1b[36m→ Line:\x1b[0m ${this.line}`;
|
|
136
|
+
if (this.column !== void 0) lineInfo += `, Column: ${this.column}`;
|
|
137
|
+
lines.push(lineInfo);
|
|
138
|
+
}
|
|
139
|
+
if (this.suggestions.length > 0) for (const suggestion of this.suggestions) lines.push(` \x1b[32m→ Suggestion:\x1b[0m ${suggestion}`);
|
|
140
|
+
if (verbose && this.cause) {
|
|
141
|
+
lines.push(`\n \x1b[90mOriginal Error:\x1b[0m ${this.cause.message}`);
|
|
142
|
+
if (this.stack) {
|
|
143
|
+
const stackLines = this.stack.split("\n").slice(1).join("\n");
|
|
144
|
+
lines.push(`\x1b[90m${stackLines}\x1b[0m`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return lines.join("\n");
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Convert to JSON-serializable object
|
|
151
|
+
*/
|
|
152
|
+
toJSON() {
|
|
153
|
+
return {
|
|
154
|
+
name: this.name,
|
|
155
|
+
code: this.code,
|
|
156
|
+
message: this.message,
|
|
157
|
+
location: this.location,
|
|
158
|
+
line: this.line,
|
|
159
|
+
column: this.column,
|
|
160
|
+
path: this.path,
|
|
161
|
+
suggestions: this.suggestions,
|
|
162
|
+
cause: this.cause?.message
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
/**
|
|
167
|
+
* ANSI color codes for terminal output
|
|
168
|
+
*/
|
|
169
|
+
const Colors = {
|
|
170
|
+
reset: "\x1B[0m",
|
|
171
|
+
bold: "\x1B[1m",
|
|
172
|
+
red: "\x1B[31m",
|
|
173
|
+
green: "\x1B[32m",
|
|
174
|
+
yellow: "\x1B[33m",
|
|
175
|
+
blue: "\x1B[34m",
|
|
176
|
+
cyan: "\x1B[36m",
|
|
177
|
+
gray: "\x1B[90m",
|
|
178
|
+
brightRed: "\x1B[91m",
|
|
179
|
+
brightGreen: "\x1B[92m"
|
|
180
|
+
};
|
|
181
|
+
/**
|
|
182
|
+
* Format error for CLI output
|
|
183
|
+
*/
|
|
184
|
+
function formatError(error, verbose = false) {
|
|
185
|
+
if (error instanceof ApicodegenError) return error.toString(verbose);
|
|
186
|
+
if (error instanceof Error) return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${error.message}${verbose && error.stack ? `\n\n${Colors.gray}${error.stack}${Colors.reset}` : ""}`;
|
|
187
|
+
return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${String(error)}`;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Print error to console with formatting
|
|
191
|
+
*/
|
|
192
|
+
function printError(error, verbose = false, stream = process.stderr) {
|
|
193
|
+
stream.write(formatError(error, verbose));
|
|
194
|
+
stream.write("\n");
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Create error with common patterns
|
|
198
|
+
*/
|
|
199
|
+
const createErrors = {
|
|
200
|
+
specNotFound(path, cause) {
|
|
201
|
+
return new ApicodegenError({
|
|
202
|
+
code: ErrorCodes.SPEC_NOT_FOUND,
|
|
203
|
+
message: "OpenAPI spec file not found",
|
|
204
|
+
location: path,
|
|
205
|
+
suggestions: [
|
|
206
|
+
"Check if the file exists using 'ls -la'",
|
|
207
|
+
"Use --spec to provide the correct path",
|
|
208
|
+
"For remote specs, ensure the URL is accessible"
|
|
209
|
+
],
|
|
210
|
+
cause
|
|
211
|
+
});
|
|
212
|
+
},
|
|
213
|
+
specFetchFailed(url, statusCode, cause) {
|
|
214
|
+
const message = statusCode ? `Failed to fetch OpenAPI spec (HTTP ${statusCode})` : "Failed to fetch OpenAPI spec from URL";
|
|
215
|
+
return new ApicodegenError({
|
|
216
|
+
code: ErrorCodes.SPEC_FETCH_FAILED,
|
|
217
|
+
message,
|
|
218
|
+
location: url,
|
|
219
|
+
suggestions: [
|
|
220
|
+
"Check if the URL is accessible in a browser",
|
|
221
|
+
"Download the spec file locally and use the local path",
|
|
222
|
+
"Verify CORS settings if fetching from a different origin"
|
|
223
|
+
],
|
|
224
|
+
cause
|
|
225
|
+
});
|
|
226
|
+
},
|
|
227
|
+
specParseFailed(path, line, column, cause) {
|
|
228
|
+
return new ApicodegenError({
|
|
229
|
+
code: ErrorCodes.SPEC_PARSE_FAILED,
|
|
230
|
+
message: "Failed to parse OpenAPI spec (invalid JSON or YAML)",
|
|
231
|
+
location: path,
|
|
232
|
+
line,
|
|
233
|
+
column,
|
|
234
|
+
suggestions: [
|
|
235
|
+
"Validate JSON syntax using jsonlint.com",
|
|
236
|
+
"For YAML specs, ensure proper indentation",
|
|
237
|
+
"Check for trailing commas or unquoted special characters"
|
|
238
|
+
],
|
|
239
|
+
cause
|
|
240
|
+
});
|
|
241
|
+
},
|
|
242
|
+
outputDirMissing(path, cause) {
|
|
243
|
+
return new ApicodegenError({
|
|
244
|
+
code: ErrorCodes.OUTPUT_DIR_MISSING,
|
|
245
|
+
message: "Output directory does not exist",
|
|
246
|
+
location: path,
|
|
247
|
+
suggestions: ["Create the directory: mkdir -p $(dirname <output>)", "Check if the path is correct"],
|
|
248
|
+
cause
|
|
249
|
+
});
|
|
250
|
+
},
|
|
251
|
+
configInvalid(path, cause) {
|
|
252
|
+
return new ApicodegenError({
|
|
253
|
+
code: ErrorCodes.CONFIG_INVALID,
|
|
254
|
+
message: "Invalid configuration file",
|
|
255
|
+
location: path,
|
|
256
|
+
suggestions: ["Validate JSON syntax in the config file", "Check for required fields (spec, output)"],
|
|
257
|
+
cause
|
|
258
|
+
});
|
|
259
|
+
},
|
|
260
|
+
validationFailed(path, details, cause) {
|
|
261
|
+
return new ApicodegenError({
|
|
262
|
+
code: ErrorCodes.VALIDATION_FAILED,
|
|
263
|
+
message: "OpenAPI spec validation failed",
|
|
264
|
+
location: path,
|
|
265
|
+
path: details,
|
|
266
|
+
suggestions: [
|
|
267
|
+
"Check OpenAPI spec structure at the specified path",
|
|
268
|
+
"Ensure all required fields are present",
|
|
269
|
+
"Validate using swagger.io editor"
|
|
270
|
+
],
|
|
271
|
+
cause
|
|
272
|
+
});
|
|
273
|
+
},
|
|
274
|
+
generationFailed(cause) {
|
|
275
|
+
return new ApicodegenError({
|
|
276
|
+
code: ErrorCodes.GENERATION_FAILED,
|
|
277
|
+
message: "Code generation failed",
|
|
278
|
+
suggestions: [
|
|
279
|
+
"Check for unsupported OpenAPI features",
|
|
280
|
+
"Ensure spec follows OpenAPI 2.0, 3.0, or 3.1 specification",
|
|
281
|
+
"Use --verbose for more details"
|
|
282
|
+
],
|
|
283
|
+
cause
|
|
284
|
+
});
|
|
285
|
+
},
|
|
286
|
+
writeFailed(path, cause) {
|
|
287
|
+
return new ApicodegenError({
|
|
288
|
+
code: ErrorCodes.GENERATION_FAILED,
|
|
289
|
+
message: "Failed to write generated code",
|
|
290
|
+
location: path,
|
|
291
|
+
suggestions: ["Check that the output path is writable", "Ensure the output directory can be created"],
|
|
292
|
+
cause
|
|
293
|
+
});
|
|
294
|
+
},
|
|
295
|
+
typeCheckFailed(path, _errors, cause) {
|
|
296
|
+
return new ApicodegenError({
|
|
297
|
+
code: ErrorCodes.TYPE_CHECK_FAILED,
|
|
298
|
+
message: "TypeScript type check failed",
|
|
299
|
+
location: path,
|
|
300
|
+
suggestions: [
|
|
301
|
+
..._errors.length > 0 ? _errors : [],
|
|
302
|
+
"Review type errors above",
|
|
303
|
+
"Check for schema inconsistencies",
|
|
304
|
+
"Update generated types or fix source schema"
|
|
305
|
+
],
|
|
306
|
+
cause
|
|
307
|
+
});
|
|
308
|
+
},
|
|
309
|
+
missingRequiredField(field, context) {
|
|
310
|
+
return new ApicodegenError({
|
|
311
|
+
code: ErrorCodes.VALIDATION_FAILED,
|
|
312
|
+
message: `Missing required field: ${field}`,
|
|
313
|
+
path: context,
|
|
314
|
+
suggestions: [`Add the '${field}' field to your configuration`]
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
/**
|
|
319
|
+
* Wrap unknown error in ApicodegenError if needed
|
|
320
|
+
*/
|
|
321
|
+
function wrapError(error, context) {
|
|
322
|
+
if (error instanceof ApicodegenError) return error;
|
|
323
|
+
if (error instanceof Error) return new ApicodegenError({
|
|
324
|
+
code: context?.code || ErrorCodes.GENERATION_FAILED,
|
|
325
|
+
message: context?.message || error.message,
|
|
326
|
+
location: context?.location,
|
|
327
|
+
suggestions: context?.suggestions,
|
|
328
|
+
cause: error
|
|
329
|
+
});
|
|
330
|
+
return new ApicodegenError({
|
|
331
|
+
code: context?.code || ErrorCodes.GENERATION_FAILED,
|
|
332
|
+
message: String(error),
|
|
333
|
+
suggestions: context?.suggestions
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Check if error is an ApicodegenError
|
|
338
|
+
*/
|
|
339
|
+
function isApicodegenError(error) {
|
|
340
|
+
return error instanceof ApicodegenError;
|
|
341
|
+
}
|
|
342
|
+
// src/core/interface.ts
|
|
94
343
|
let SchemaType = /* @__PURE__ */ function(SchemaType) {
|
|
95
344
|
SchemaType["schemas"] = "schemas";
|
|
96
345
|
SchemaType["parameters"] = "parameters";
|
|
@@ -132,7 +381,6 @@ let ParameterIn = /* @__PURE__ */ function(ParameterIn) {
|
|
|
132
381
|
}({});
|
|
133
382
|
let MediaTypes = /* @__PURE__ */ function(MediaTypes) {
|
|
134
383
|
MediaTypes["JSON"] = "application/json";
|
|
135
|
-
MediaTypes["EVENT_STREAM"] = "text/event-stream";
|
|
136
384
|
MediaTypes["TEXT"] = "text";
|
|
137
385
|
MediaTypes["IMAGE"] = "image";
|
|
138
386
|
MediaTypes["AUDIO"] = "audio";
|
|
@@ -155,8 +403,7 @@ let Adaptors = /* @__PURE__ */ function(Adaptors) {
|
|
|
155
403
|
Adaptors["axios"] = "axios";
|
|
156
404
|
return Adaptors;
|
|
157
405
|
}({});
|
|
158
|
-
|
|
159
|
-
//#region src/core/base/Base.ts
|
|
406
|
+
// src/core/base/Base.ts
|
|
160
407
|
/**
|
|
161
408
|
* @file Base class implementation
|
|
162
409
|
* @author wp.l
|
|
@@ -211,17 +458,70 @@ var Base = class Base {
|
|
|
211
458
|
* @param [operationId] - Unique identifier for the operation.
|
|
212
459
|
* @returns - The generated function name.
|
|
213
460
|
*/
|
|
214
|
-
static pathToFnName(path, method,
|
|
215
|
-
|
|
461
|
+
static pathToFnName(path, method, operationId) {
|
|
462
|
+
let name = "";
|
|
463
|
+
let keywordProtected = false;
|
|
464
|
+
if (operationId) {
|
|
465
|
+
keywordProtected = typescriptKeywords.has(operationId);
|
|
466
|
+
name = Base.camelCase(Base.normalize(operationId));
|
|
467
|
+
}
|
|
468
|
+
if (!name) {
|
|
469
|
+
keywordProtected = typescriptKeywords.has(path);
|
|
470
|
+
name = Base.camelCase(Base.normalize(path));
|
|
471
|
+
}
|
|
472
|
+
if (keywordProtected && !name.endsWith("_")) name = `${name}_`;
|
|
473
|
+
const suffix = method ? Base.capitalize(Base.upperCamelCase(`using_${method}`)) : "";
|
|
474
|
+
return name + suffix;
|
|
216
475
|
}
|
|
217
476
|
/**
|
|
218
|
-
*
|
|
477
|
+
* Converts arbitrary text into a legal TypeScript variable identifier.
|
|
478
|
+
* Keywords keep the `_` suffix that `normalize` adds, since `camelCase`
|
|
479
|
+
* would otherwise strip it and emit a reserved word.
|
|
480
|
+
* @param text - Input text.
|
|
481
|
+
* @returns - A legal identifier.
|
|
482
|
+
*/
|
|
483
|
+
static toIdentifier(text) {
|
|
484
|
+
const name = Base.camelCase(Base.normalize(text));
|
|
485
|
+
return typescriptKeywords.has(name) ? `${name}_` : name;
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Normalizes a string by replacing special characters and avoiding TypeScript keywords.
|
|
219
489
|
* @param text - Input text to normalize.
|
|
220
490
|
* @returns - The normalized string.
|
|
221
491
|
*/
|
|
222
492
|
static normalize(text) {
|
|
223
493
|
if (typescriptKeywords.has(text)) text += "_";
|
|
224
|
-
return text.replace(/[/\-_{}():\s`,*<>$#.]/gm, "_").replace(/^\d
|
|
494
|
+
return text.replaceAll("...", "").replace(/[/\-_{}():\s`,*<>$#.]/gm, "_").replace(/^\d/gm, "");
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Map a request body media type to a stable function-name suffix.
|
|
498
|
+
*
|
|
499
|
+
* Used to disambiguate sibling operations sharing the same path+method
|
|
500
|
+
* but different request body media types. The result is appended (in
|
|
501
|
+
* upperCamelCase) to the operation's base function name.
|
|
502
|
+
*
|
|
503
|
+
* Known types are mapped to short, human-readable names. Unknown types
|
|
504
|
+
* fall back to `camelCase(normalize(<sub-type>))`.
|
|
505
|
+
*
|
|
506
|
+
* @param mediaType - The OpenAPI media type (e.g. `application/json`).
|
|
507
|
+
* @returns - The suffix without leading underscore, or empty string.
|
|
508
|
+
*/
|
|
509
|
+
static mediaTypeToSuffix(mediaType) {
|
|
510
|
+
const known = {
|
|
511
|
+
"application/json": "Json",
|
|
512
|
+
"multipart/form-data": "FormData",
|
|
513
|
+
"application/x-www-form-urlencoded": "FormUrlencoded",
|
|
514
|
+
"application/octet-stream": "OctetStream",
|
|
515
|
+
"text/plain": "Text",
|
|
516
|
+
"text/html": "Html",
|
|
517
|
+
"application/xml": "Xml",
|
|
518
|
+
"text/xml": "Xml"
|
|
519
|
+
};
|
|
520
|
+
const normalized = mediaType.toLowerCase().split(";")[0]?.trim() ?? "";
|
|
521
|
+
if (known[normalized]) return known[normalized];
|
|
522
|
+
const sub = normalized.split("/")[1];
|
|
523
|
+
if (!sub || sub === "*" || normalized === "*/*" || normalized === "") return "";
|
|
524
|
+
return Base.upperCamelCase(Base.normalize(sub));
|
|
225
525
|
}
|
|
226
526
|
/**
|
|
227
527
|
* Capitalizes the first character of a string.
|
|
@@ -249,26 +549,230 @@ var Base = class Base {
|
|
|
249
549
|
* @returns - UpperCamelCase string.
|
|
250
550
|
*/
|
|
251
551
|
static upperCamelCase(text) {
|
|
252
|
-
return Base.normalize(text).replaceAll("...", "").split("_").filter(Boolean).map(Base.capitalize).join("");
|
|
552
|
+
return Base.normalize(text).replaceAll("...", "").split("_").filter(Boolean).map((part) => part.match(/^\d/) ? `N${part}` : Base.capitalize(part)).join("");
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Classify a spec location string into a transport + source pair.
|
|
556
|
+
*
|
|
557
|
+
* Returns:
|
|
558
|
+
* - `{ transport: 'file', source }` when `input` looks like a local
|
|
559
|
+
* filesystem path (`file://...`, POSIX absolute, Windows absolute).
|
|
560
|
+
* - `{ transport: 'http', source }` for `http(s)://...` URLs.
|
|
561
|
+
*
|
|
562
|
+
* Relative paths are treated as `http` so that callers (CLI / Vite
|
|
563
|
+
* plugin) must resolve them against cwd first. This makes intent
|
|
564
|
+
* explicit and avoids accidentally reading from process.cwd().
|
|
565
|
+
*/
|
|
566
|
+
static resolveSpecURL(input) {
|
|
567
|
+
if (input.startsWith("file://")) {
|
|
568
|
+
const stripped = input.replace(/^file:\/\//, "");
|
|
569
|
+
return {
|
|
570
|
+
transport: "file",
|
|
571
|
+
source: /^\/[A-Za-z]:/.test(stripped) ? stripped.slice(1) : stripped
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
if (input.startsWith("/")) return {
|
|
575
|
+
transport: "file",
|
|
576
|
+
source: input
|
|
577
|
+
};
|
|
578
|
+
if (/^[A-Za-z]:[\\/]/.test(input)) return {
|
|
579
|
+
transport: "file",
|
|
580
|
+
source: input
|
|
581
|
+
};
|
|
582
|
+
return {
|
|
583
|
+
transport: "http",
|
|
584
|
+
source: input
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Read and parse a local OpenAPI document from the filesystem.
|
|
589
|
+
*
|
|
590
|
+
* @param filePath - Absolute filesystem path to the spec.
|
|
591
|
+
* @returns - A promise resolving to the parsed document.
|
|
592
|
+
*/
|
|
593
|
+
static async readLocalDoc(filePath) {
|
|
594
|
+
let raw;
|
|
595
|
+
try {
|
|
596
|
+
raw = await readFile(filePath, "utf8");
|
|
597
|
+
} catch (error) {
|
|
598
|
+
if (error?.code === "ENOENT") throw createErrors.specNotFound(filePath, error);
|
|
599
|
+
throw new Error(`Failed to read OpenAPI spec from ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
600
|
+
}
|
|
601
|
+
return Base.parseDoc(raw, filePath);
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* Parses an OpenAPI document from JSON or YAML text.
|
|
605
|
+
*
|
|
606
|
+
* JSON is attempted first for a clearer syntax error on JSON files; YAML
|
|
607
|
+
* then handles `.yaml` / `.yml` specs. Any failure is reported as
|
|
608
|
+
* `E_SPEC_PARSE_FAILED` with the source path attached.
|
|
609
|
+
*
|
|
610
|
+
* @param raw - Raw spec content.
|
|
611
|
+
* @param source - Path or URL used in error messages.
|
|
612
|
+
* @returns - The parsed document.
|
|
613
|
+
*/
|
|
614
|
+
static parseDoc(raw, source) {
|
|
615
|
+
let parsed;
|
|
616
|
+
try {
|
|
617
|
+
parsed = JSON.parse(raw);
|
|
618
|
+
} catch {
|
|
619
|
+
try {
|
|
620
|
+
parsed = parse(raw);
|
|
621
|
+
} catch (error) {
|
|
622
|
+
throw createErrors.specParseFailed(source, void 0, void 0, error);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
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"));
|
|
626
|
+
return parsed;
|
|
253
627
|
}
|
|
254
628
|
/**
|
|
255
629
|
* Fetches documentation from a given URL.
|
|
256
|
-
*
|
|
257
|
-
*
|
|
630
|
+
*
|
|
631
|
+
* Supports three transport modes:
|
|
632
|
+
* - `file://...` URLs → read from filesystem (JSON or YAML)
|
|
633
|
+
* - absolute filesystem paths → read from filesystem (JSON or YAML)
|
|
634
|
+
* - `http(s)://...` URLs (and unrecognised inputs like relative paths)
|
|
635
|
+
* → fetched via undici (existing behavior)
|
|
636
|
+
*
|
|
637
|
+
* Callers should pass an already-resolved absolute path or URL. Relative
|
|
638
|
+
* paths fall through to undici by design — CLI / Vite plugin should
|
|
639
|
+
* resolve them against cwd first.
|
|
640
|
+
*
|
|
641
|
+
* @param url - The URL or filesystem path to fetch the documentation from.
|
|
642
|
+
* @param requestInit - Additional request parameters (only used for http(s)).
|
|
643
|
+
* TLS certificates are verified by default; set `insecure: true` to opt out.
|
|
258
644
|
* @returns - A promise resolving to the fetched documentation data.
|
|
259
645
|
*/
|
|
260
646
|
static async fetchDoc(url, requestInit = {}) {
|
|
261
|
-
const {
|
|
647
|
+
const { transport, source } = Base.resolveSpecURL(url);
|
|
648
|
+
if (transport === "file") return Base.readLocalDoc(source);
|
|
649
|
+
const { insecure = false, ...init } = requestInit;
|
|
650
|
+
const { body, statusCode } = await request(source, {
|
|
262
651
|
method: "GET",
|
|
263
|
-
dispatcher: new Agent({ connect: { rejectUnauthorized: false } }),
|
|
264
|
-
...
|
|
652
|
+
...insecure ? { dispatcher: new Agent({ connect: { rejectUnauthorized: false } }) } : {},
|
|
653
|
+
...init
|
|
265
654
|
});
|
|
266
|
-
if (statusCode >= 400) throw new Error(`Failed to fetch OpenAPI documentation from ${
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
655
|
+
if (statusCode >= 400) throw new Error(`Failed to fetch OpenAPI documentation from ${source}: HTTP ${statusCode}`);
|
|
656
|
+
return Base.parseDoc(await body.text(), source);
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* Copies external `$ref` targets (other files or remote URLs) into the root
|
|
660
|
+
* document and rewrites the refs to local ones. Objects are registered
|
|
661
|
+
* before their children are walked, so cycles keep working.
|
|
662
|
+
*
|
|
663
|
+
* External refs are placed in the component section implied by their
|
|
664
|
+
* fragment (`schemas` by default); a generated local `$ref` points at the
|
|
665
|
+
* copy.
|
|
666
|
+
*
|
|
667
|
+
* @param doc - Parsed root document (mutated in place).
|
|
668
|
+
* @param source - Absolute path or URL of the root document.
|
|
669
|
+
* @param requestInit - Request options for remote refs.
|
|
670
|
+
* @returns - The same document with external refs resolved.
|
|
671
|
+
*/
|
|
672
|
+
static async bundleExternalRefs(doc, source, requestInit = {}) {
|
|
673
|
+
const root = doc;
|
|
674
|
+
const isV2 = typeof root.swagger === "string";
|
|
675
|
+
const rootURL = Base.resolveSpecURL(source).transport === "file" ? pathToFileURL(source).href : source;
|
|
676
|
+
const docs = /* @__PURE__ */ new Map([[rootURL, root]]);
|
|
677
|
+
const registered = /* @__PURE__ */ new Map();
|
|
678
|
+
const loadDoc = async (url) => {
|
|
679
|
+
const cached = docs.get(url);
|
|
680
|
+
if (cached !== void 0) return cached;
|
|
681
|
+
const loaded = await Base.fetchDoc(url, requestInit);
|
|
682
|
+
docs.set(url, loaded);
|
|
683
|
+
return loaded;
|
|
684
|
+
};
|
|
685
|
+
const containerFor = (ref) => {
|
|
686
|
+
const section = Base.externalRefSection(ref, isV2);
|
|
687
|
+
if (isV2) {
|
|
688
|
+
root[section] ??= {};
|
|
689
|
+
return {
|
|
690
|
+
record: root[section],
|
|
691
|
+
prefix: `#/${section}/`
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
root.components ??= {};
|
|
695
|
+
root.components[section] ??= {};
|
|
696
|
+
return {
|
|
697
|
+
record: root.components[section],
|
|
698
|
+
prefix: `#/components/${section}/`
|
|
699
|
+
};
|
|
700
|
+
};
|
|
701
|
+
const register = async (absolute) => {
|
|
702
|
+
const existing = registered.get(absolute);
|
|
703
|
+
if (existing) return existing;
|
|
704
|
+
const hashIndex = absolute.indexOf("#");
|
|
705
|
+
const docURL = hashIndex === -1 ? absolute : absolute.slice(0, hashIndex);
|
|
706
|
+
const fragment = hashIndex === -1 ? "" : absolute.slice(hashIndex);
|
|
707
|
+
const externalDoc = await loadDoc(docURL);
|
|
708
|
+
const { record, prefix } = containerFor(fragment);
|
|
709
|
+
const target = Base.resolveJSONPointer(externalDoc, fragment);
|
|
710
|
+
if (target === void 0) return `${prefix}unknown`;
|
|
711
|
+
const baseName = Base.externalRefName(fragment, docURL);
|
|
712
|
+
let name = baseName;
|
|
713
|
+
let suffix = 2;
|
|
714
|
+
while (name in record) {
|
|
715
|
+
name = `${baseName}${suffix}`;
|
|
716
|
+
suffix++;
|
|
717
|
+
}
|
|
718
|
+
registered.set(absolute, prefix + name);
|
|
719
|
+
record[name] = target;
|
|
720
|
+
await walk(target, docURL);
|
|
721
|
+
return prefix + name;
|
|
722
|
+
};
|
|
723
|
+
const walk = async (value, docURL) => {
|
|
724
|
+
if (Array.isArray(value)) {
|
|
725
|
+
for (const item of value) await walk(item, docURL);
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
if (value === null || typeof value !== "object") return;
|
|
729
|
+
const object = value;
|
|
730
|
+
if (typeof object.$ref === "string") {
|
|
731
|
+
const ref = object.$ref;
|
|
732
|
+
if (ref.startsWith("#") && docURL === rootURL) return;
|
|
733
|
+
const absolute = ref.startsWith("#") ? docURL + ref : new URL(ref, docURL).href;
|
|
734
|
+
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}`);
|
|
735
|
+
object.$ref = await register(absolute);
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
for (const key of Object.keys(object)) await walk(object[key], docURL);
|
|
739
|
+
};
|
|
740
|
+
await walk(root, rootURL);
|
|
741
|
+
return doc;
|
|
742
|
+
}
|
|
743
|
+
/** Component section an external ref belongs to. */
|
|
744
|
+
static externalRefSection(ref, isV2) {
|
|
745
|
+
if (isV2) {
|
|
746
|
+
if (ref.includes("/parameters/")) return "parameters";
|
|
747
|
+
if (ref.includes("/responses/")) return "responses";
|
|
748
|
+
return "definitions";
|
|
749
|
+
}
|
|
750
|
+
if (ref.includes("/parameters/")) return "parameters";
|
|
751
|
+
if (ref.includes("/responses/")) return "responses";
|
|
752
|
+
if (ref.includes("/requestBodies/")) return "requestBodies";
|
|
753
|
+
return "schemas";
|
|
754
|
+
}
|
|
755
|
+
/** Local component name derived from the ref fragment or file name. */
|
|
756
|
+
static externalRefName(fragment, docURL) {
|
|
757
|
+
let name = fragment.replace(/^#/, "").split("/").filter(Boolean).map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")).at(-1) ?? "";
|
|
758
|
+
if (!name) try {
|
|
759
|
+
name = new URL(docURL).pathname.split("/").pop() ?? "";
|
|
760
|
+
} catch {
|
|
761
|
+
name = "";
|
|
271
762
|
}
|
|
763
|
+
name = name.replace(/\.(json|ya?ml)$/i, "").replace(/[^A-Za-z0-9_.-]/g, "_");
|
|
764
|
+
return name || "External";
|
|
765
|
+
}
|
|
766
|
+
/** Resolves a `#/a/b` JSON pointer inside a parsed document. */
|
|
767
|
+
static resolveJSONPointer(doc, fragment) {
|
|
768
|
+
if (!fragment) return doc;
|
|
769
|
+
const parts = fragment.replace(/^#\/?/, "").split("/").filter(Boolean).map((part) => decodeURIComponent(part).replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
770
|
+
let current = doc;
|
|
771
|
+
for (const part of parts) {
|
|
772
|
+
if (current === null || typeof current !== "object") return void 0;
|
|
773
|
+
current = current[part];
|
|
774
|
+
}
|
|
775
|
+
return current;
|
|
272
776
|
}
|
|
273
777
|
/**
|
|
274
778
|
* Determines the media type from a given media type string.
|
|
@@ -338,8 +842,72 @@ var Base = class Base {
|
|
|
338
842
|
return typeof schema === "object" && schema !== null && "$ref" in schema && typeof schema.$ref === "string";
|
|
339
843
|
}
|
|
340
844
|
};
|
|
341
|
-
|
|
342
|
-
|
|
845
|
+
// src/core/base/Adaptor.ts
|
|
846
|
+
/** `options?.name` */
|
|
847
|
+
function optionalAccess(control, name) {
|
|
848
|
+
return factory.createPropertyAccessChain(factory.createIdentifier(control.name), factory.createToken(SyntaxKind.QuestionDotToken), factory.createIdentifier(name));
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* `options?.signal && options?.timeout ? AbortSignal.any([...]) : ...`,
|
|
852
|
+
* combining a caller signal with a timeout when both are present.
|
|
853
|
+
*/
|
|
854
|
+
function fetchSignalExpression(control) {
|
|
855
|
+
const signal = optionalAccess(control, "signal");
|
|
856
|
+
const timeout = optionalAccess(control, "timeout");
|
|
857
|
+
const timeoutSignal = () => factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("AbortSignal"), factory.createIdentifier("timeout")), void 0, [timeout]);
|
|
858
|
+
const both = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("AbortSignal"), factory.createIdentifier("any")), void 0, [factory.createArrayLiteralExpression([signal, timeoutSignal()])]);
|
|
859
|
+
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")));
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Header entries plus a spread of caller-supplied headers.
|
|
863
|
+
*/
|
|
864
|
+
function withRequestHeaders(entries, control) {
|
|
865
|
+
if (!control) return entries;
|
|
866
|
+
return [...entries, factory.createSpreadAssignment(optionalAccess(control, "headers"))];
|
|
867
|
+
}
|
|
868
|
+
/** `auth?.["scheme"]` */
|
|
869
|
+
function authAccess(auth, scheme) {
|
|
870
|
+
return factory.createElementAccessChain(factory.createIdentifier(auth.name), factory.createToken(SyntaxKind.QuestionDotToken), factory.createStringLiteral(scheme));
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Header entries (conditional spreads) for auth schemes sent as headers.
|
|
874
|
+
*/
|
|
875
|
+
function authHeaderEntries(auth) {
|
|
876
|
+
return auth.injections.filter((injection) => injection.location === "header").map((injection) => {
|
|
877
|
+
const access = authAccess(auth, injection.scheme);
|
|
878
|
+
const hasValue = factory.createBinaryExpression(access, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword));
|
|
879
|
+
let value;
|
|
880
|
+
let condition = hasValue;
|
|
881
|
+
if (injection.kind === "basic") {
|
|
882
|
+
condition = factory.createBinaryExpression(access, factory.createToken(SyntaxKind.AmpersandAmpersandToken), factory.createBinaryExpression(factory.createTypeOfExpression(access), factory.createToken(SyntaxKind.EqualsEqualsEqualsToken), factory.createStringLiteral("object")));
|
|
883
|
+
const credentials = factory.createTemplateExpression(factory.createTemplateHead(""), [factory.createTemplateSpan(factory.createPropertyAccessExpression(access, "username"), factory.createTemplateMiddle(":")), factory.createTemplateSpan(factory.createPropertyAccessExpression(access, "password"), factory.createTemplateTail(""))]);
|
|
884
|
+
value = factory.createTemplateExpression(factory.createTemplateHead("Basic "), [factory.createTemplateSpan(factory.createCallExpression(factory.createIdentifier("btoa"), void 0, [credentials]), factory.createTemplateTail(""))]);
|
|
885
|
+
} else if (injection.kind === "bearer") value = factory.createTemplateExpression(factory.createTemplateHead("Bearer "), [factory.createTemplateSpan(factory.createCallExpression(factory.createIdentifier("String"), void 0, [access]), factory.createTemplateTail(""))]);
|
|
886
|
+
else value = factory.createCallExpression(factory.createIdentifier("String"), void 0, [access]);
|
|
887
|
+
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)));
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* Builds a `Cookie` header value from OpenAPI cookie parameters.
|
|
892
|
+
* Undefined/null values are filtered out at runtime.
|
|
893
|
+
*/
|
|
894
|
+
function cookieHeaderExpression(parameters, auth) {
|
|
895
|
+
const entries = parameters.filter((p) => p.in === "cookie").map((parameter) => {
|
|
896
|
+
const id = factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
897
|
+
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(""));
|
|
898
|
+
});
|
|
899
|
+
const authEntries = auth ? auth.injections.filter((injection) => injection.location === "cookie").map((injection) => {
|
|
900
|
+
const access = authAccess(auth, injection.scheme);
|
|
901
|
+
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(""));
|
|
902
|
+
}) : [];
|
|
903
|
+
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("; ")]);
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* Base adapter for tool
|
|
907
|
+
* This abstract class serves as the foundation for implementing adapters for different code generation tools
|
|
908
|
+
*/
|
|
909
|
+
var Adapter = class {};
|
|
910
|
+
// src/core/base/Provider.ts
|
|
343
911
|
/**
|
|
344
912
|
* Abstract Provider Class.
|
|
345
913
|
*
|
|
@@ -383,6 +951,8 @@ var Provider = class {
|
|
|
383
951
|
responses = {};
|
|
384
952
|
/** collection of request bodies indexed by name */
|
|
385
953
|
requestBodies = {};
|
|
954
|
+
/** security schemes declared by the document */
|
|
955
|
+
securitySchemes = {};
|
|
386
956
|
/** collection of API endpoints (operations) indexed by path */
|
|
387
957
|
apis = {};
|
|
388
958
|
/** URL for fetching API documentation */
|
|
@@ -406,330 +976,166 @@ var Provider = class {
|
|
|
406
976
|
this.output = initOptions.output ?? ".";
|
|
407
977
|
this.requestOptions = initOptions.requestOptions ?? {};
|
|
408
978
|
this.importClientSource = initOptions.importClientSource ?? "";
|
|
409
|
-
const { enums, schemas, requestBodies, responses, parameters, apis } = this.parse(doc);
|
|
979
|
+
const { enums, schemas, requestBodies, responses, parameters, securitySchemes, apis } = this.parse(doc);
|
|
410
980
|
this.enums = enums;
|
|
411
981
|
this.schemas = schemas;
|
|
412
982
|
this.responses = responses;
|
|
413
983
|
this.parameters = parameters;
|
|
414
984
|
this.requestBodies = requestBodies;
|
|
985
|
+
this.securitySchemes = securitySchemes;
|
|
415
986
|
this.apis = apis;
|
|
416
987
|
}
|
|
417
988
|
};
|
|
418
|
-
|
|
419
|
-
//#region src/core/errors.ts
|
|
989
|
+
// src/core/generator/naming.ts
|
|
420
990
|
/**
|
|
421
|
-
*
|
|
991
|
+
* Create a per-generation unique-name resolver.
|
|
992
|
+
*
|
|
993
|
+
* Tracks how many times each base name has been seen during a single
|
|
994
|
+
* code generation pass and returns a unique variant on every call:
|
|
995
|
+
*
|
|
996
|
+
* reserve('foo') // 'foo'
|
|
997
|
+
* reserve('foo') // 'foo2'
|
|
998
|
+
* reserve('foo') // 'foo3'
|
|
999
|
+
* reserve('bar') // 'bar' (independent counter)
|
|
1000
|
+
*
|
|
1001
|
+
* The resolver holds no module-level state — create one per generation pass
|
|
1002
|
+
* and let it go out of scope when the pass completes.
|
|
422
1003
|
*/
|
|
423
|
-
const
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
GENERATION_FAILED: "E_GENERATION_FAILED",
|
|
431
|
-
TYPE_CHECK_FAILED: "E_TYPE_CHECK_FAILED"
|
|
1004
|
+
const createUniqueNameResolver = () => {
|
|
1005
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1006
|
+
return (name) => {
|
|
1007
|
+
const next = (seen.get(name) ?? 0) + 1;
|
|
1008
|
+
seen.set(name, next);
|
|
1009
|
+
return next === 1 ? name : `${name}${next}`;
|
|
1010
|
+
};
|
|
432
1011
|
};
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
*/
|
|
436
|
-
var ApicodegenError = class ApicodegenError extends Error {
|
|
437
|
-
code;
|
|
438
|
-
location;
|
|
439
|
-
line;
|
|
440
|
-
column;
|
|
441
|
-
path;
|
|
442
|
-
suggestions;
|
|
443
|
-
cause;
|
|
444
|
-
constructor(context) {
|
|
445
|
-
super(context.message);
|
|
446
|
-
this.name = "ApicodegenError";
|
|
447
|
-
this.code = context.code;
|
|
448
|
-
this.location = context.location;
|
|
449
|
-
this.line = context.line;
|
|
450
|
-
this.column = context.column;
|
|
451
|
-
this.path = context.path;
|
|
452
|
-
this.suggestions = context.suggestions || [];
|
|
453
|
-
this.cause = context.cause;
|
|
454
|
-
if (Error.captureStackTrace) Error.captureStackTrace(this, ApicodegenError);
|
|
455
|
-
}
|
|
1012
|
+
// src/core/generator/index.ts
|
|
1013
|
+
var Generator = class Generator {
|
|
456
1014
|
/**
|
|
457
|
-
*
|
|
1015
|
+
* Converts an array of TypeScript statements into a formatted string of code.
|
|
1016
|
+
*
|
|
1017
|
+
* @param statements - The array of TypeScript statement nodes.
|
|
1018
|
+
* @returns Formatted code as a string.
|
|
1019
|
+
* @throws {Error} If no valid statements are provided.
|
|
458
1020
|
*/
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
1021
|
+
static toCode(statements) {
|
|
1022
|
+
if (statements.length === 0) return "// No api declaration found.";
|
|
1023
|
+
const sourceFile = factory.createSourceFile(statements, factory.createToken(SyntaxKind.EndOfFileToken), NodeFlags.None);
|
|
1024
|
+
return createPrinter().printFile(sourceFile);
|
|
1025
|
+
}
|
|
1026
|
+
static async write(code, filepath) {
|
|
1027
|
+
try {
|
|
1028
|
+
await mkdir(dirname(filepath), { recursive: true });
|
|
1029
|
+
await writeFile(filepath, code);
|
|
1030
|
+
} catch (error) {
|
|
1031
|
+
throw createErrors.writeFailed(filepath, error instanceof Error ? error : new Error(String(error)));
|
|
468
1032
|
}
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
1033
|
+
}
|
|
1034
|
+
/**
|
|
1035
|
+
* Converts a path string with parameters into a TypeScript template expression.
|
|
1036
|
+
* Handles query parameters and path placeholders.
|
|
1037
|
+
*
|
|
1038
|
+
* @param path - The base path string containing placeholders.
|
|
1039
|
+
* @param parameters - Array of parameter objects defining the parameters.
|
|
1040
|
+
* @param basePath - Optional base path to prepend (default: "").
|
|
1041
|
+
* @returns A TypeScript template expressi
|
|
1042
|
+
*/
|
|
1043
|
+
static toUrlTemplate(path, parameters, basePath = "", auth) {
|
|
1044
|
+
const pathExpression = Generator.toPathTemplate(path, basePath);
|
|
1045
|
+
const queryParameters = parameters.filter((p) => p.in === "query");
|
|
1046
|
+
const hasAuthQuery = auth?.injections.some((injection) => injection.location === "query");
|
|
1047
|
+
if (queryParameters.length === 0 && !hasAuthQuery) return pathExpression;
|
|
1048
|
+
return factory.createBinaryExpression(pathExpression, factory.createToken(SyntaxKind.PlusToken), Generator.toQueryStringExpression(queryParameters, auth));
|
|
1049
|
+
}
|
|
1050
|
+
/**
|
|
1051
|
+
* Builds the path part of a URL, encoding every `{param}` interpolation.
|
|
1052
|
+
*/
|
|
1053
|
+
static toPathTemplate(path, basePath) {
|
|
1054
|
+
const pathSegments = path.replaceAll("{", "${").split("$").filter(Boolean);
|
|
1055
|
+
if (pathSegments.length === 1) return factory.createNoSubstitutionTemplateLiteral(basePath + path);
|
|
1056
|
+
return factory.createTemplateExpression(factory.createTemplateHead(basePath + pathSegments[0]), pathSegments.slice(1).map((segment, index) => {
|
|
1057
|
+
const match = /^{(.+)}(.+)?/gm.exec(segment);
|
|
1058
|
+
const isLastSegment = index === pathSegments.length - 2;
|
|
1059
|
+
if (!match) throw new Error(`Invalid path segment: ${segment}`);
|
|
1060
|
+
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] || ""));
|
|
1061
|
+
}));
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Emits an IIFE that builds a query string, omitting undefined/null
|
|
1065
|
+
* values and honouring array `explode` / delimiter styles.
|
|
1066
|
+
*/
|
|
1067
|
+
static toQueryStringExpression(parameters, auth) {
|
|
1068
|
+
const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
|
|
1069
|
+
const unique = (base) => {
|
|
1070
|
+
let name = base;
|
|
1071
|
+
let suffix = 2;
|
|
1072
|
+
while (taken.has(name)) name = `${base}${suffix++}`;
|
|
1073
|
+
taken.add(name);
|
|
1074
|
+
return name;
|
|
1075
|
+
};
|
|
1076
|
+
const qName = unique("q");
|
|
1077
|
+
const vName = unique("v");
|
|
1078
|
+
const sName = unique("s");
|
|
1079
|
+
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))];
|
|
1080
|
+
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]));
|
|
1081
|
+
const stringify = (value) => factory.createCallExpression(factory.createIdentifier("String"), void 0, [value]);
|
|
1082
|
+
const isNotNull = (value) => factory.createBinaryExpression(value, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword));
|
|
1083
|
+
for (const parameter of parameters) {
|
|
1084
|
+
const id = factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
1085
|
+
const isArray = parameter.schema?.type === "array";
|
|
1086
|
+
if (parameter.style === "deepObject" && !isArray) {
|
|
1087
|
+
const addName = unique("addDeepObject");
|
|
1088
|
+
const prefix = factory.createIdentifier("prefix");
|
|
1089
|
+
const value = factory.createIdentifier("value");
|
|
1090
|
+
const key = factory.createIdentifier("k");
|
|
1091
|
+
const entry = factory.createIdentifier("v");
|
|
1092
|
+
const path = factory.createTemplateExpression(factory.createTemplateHead(""), [factory.createTemplateSpan(prefix, factory.createTemplateMiddle("[")), factory.createTemplateSpan(key, factory.createTemplateTail("]"))]);
|
|
1093
|
+
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)]))]);
|
|
1094
|
+
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));
|
|
1095
|
+
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));
|
|
1096
|
+
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)]))]));
|
|
1097
|
+
statements.push(parameter.required ? factory.createBlock([declaration, invoke], true) : factory.createIfStatement(isNotNull(id), factory.createBlock([declaration, invoke], true)));
|
|
1098
|
+
continue;
|
|
1099
|
+
}
|
|
1100
|
+
if (isArray) {
|
|
1101
|
+
if (parameter.explode ?? (parameter.style === void 0 || parameter.style === "form")) {
|
|
1102
|
+
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)));
|
|
1103
|
+
continue;
|
|
1104
|
+
}
|
|
1105
|
+
const separator = parameter.style === "spaceDelimited" ? " " : parameter.style === "pipeDelimited" ? "|" : ",";
|
|
1106
|
+
const join = factory.createCallExpression(factory.createPropertyAccessExpression(id, factory.createIdentifier("join")), void 0, [factory.createStringLiteral(separator)]);
|
|
1107
|
+
statements.push(factory.createIfStatement(isNotNull(id), factory.createBlock([append(parameter.name, join)], true)));
|
|
1108
|
+
continue;
|
|
475
1109
|
}
|
|
1110
|
+
const statement = append(parameter.name, stringify(id));
|
|
1111
|
+
statements.push(parameter.required ? statement : factory.createIfStatement(isNotNull(id), factory.createBlock([statement], true)));
|
|
476
1112
|
}
|
|
477
|
-
|
|
1113
|
+
if (auth) for (const injection of auth.injections.filter((item) => item.location === "query")) {
|
|
1114
|
+
const access = authAccess(auth, injection.scheme);
|
|
1115
|
+
statements.push(factory.createIfStatement(factory.createBinaryExpression(access, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([append(injection.name, stringify(access))], true)));
|
|
1116
|
+
}
|
|
1117
|
+
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(""))));
|
|
1118
|
+
return factory.createCallExpression(factory.createParenthesizedExpression(factory.createArrowFunction(void 0, void 0, [], void 0, factory.createToken(SyntaxKind.EqualsGreaterThanToken), factory.createBlock(statements, true))), void 0, []);
|
|
478
1119
|
}
|
|
479
1120
|
/**
|
|
480
|
-
*
|
|
1121
|
+
* Adds synthetic comments to a TypeScript AST node.
|
|
1122
|
+
*
|
|
1123
|
+
* @param node - The target AST node.
|
|
1124
|
+
* @param comments - Array of comment objects to add.
|
|
481
1125
|
*/
|
|
482
|
-
|
|
483
|
-
return
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
cause: this.cause?.message
|
|
1126
|
+
static addComments(node, comments) {
|
|
1127
|
+
if (!Array.isArray(comments) || comments.filter(Boolean).length === 0) return;
|
|
1128
|
+
const formatComment = (comment) => {
|
|
1129
|
+
if (comment.tag === "returns") return `* @returns {${comment.type}} ${comment.comment ?? ""}`;
|
|
1130
|
+
if (comment.tag === "param") {
|
|
1131
|
+
const typePart = comment.type ? `{${comment.type}} ` : "";
|
|
1132
|
+
return comment.comment ? `* @param ${typePart}${comment.paramName} - ${comment.comment}` : `* @param ${typePart}${comment.paramName}`;
|
|
1133
|
+
}
|
|
1134
|
+
if (comment.tag) return `* @${comment.tag} ${comment.comment ?? ""}`;
|
|
1135
|
+
return `* ${comment.comment}`;
|
|
493
1136
|
};
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
/**
|
|
497
|
-
* ANSI color codes for terminal output
|
|
498
|
-
*/
|
|
499
|
-
const Colors = {
|
|
500
|
-
reset: "\x1B[0m",
|
|
501
|
-
bold: "\x1B[1m",
|
|
502
|
-
red: "\x1B[31m",
|
|
503
|
-
green: "\x1B[32m",
|
|
504
|
-
yellow: "\x1B[33m",
|
|
505
|
-
blue: "\x1B[34m",
|
|
506
|
-
cyan: "\x1B[36m",
|
|
507
|
-
gray: "\x1B[90m",
|
|
508
|
-
brightRed: "\x1B[91m",
|
|
509
|
-
brightGreen: "\x1B[92m"
|
|
510
|
-
};
|
|
511
|
-
/**
|
|
512
|
-
* Format error for CLI output
|
|
513
|
-
*/
|
|
514
|
-
function formatError(error, verbose = false) {
|
|
515
|
-
if (error instanceof ApicodegenError) return error.toString(verbose);
|
|
516
|
-
if (error instanceof Error) return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${error.message}${verbose && error.stack ? `\n\n${Colors.gray}${error.stack}${Colors.reset}` : ""}`;
|
|
517
|
-
return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${String(error)}`;
|
|
518
|
-
}
|
|
519
|
-
/**
|
|
520
|
-
* Print error to console with formatting
|
|
521
|
-
*/
|
|
522
|
-
function printError(error, verbose = false, stream = process.stderr) {
|
|
523
|
-
stream.write(formatError(error, verbose));
|
|
524
|
-
stream.write("\n");
|
|
525
|
-
}
|
|
526
|
-
/**
|
|
527
|
-
* Create error with common patterns
|
|
528
|
-
*/
|
|
529
|
-
const createErrors = {
|
|
530
|
-
specNotFound(path, cause) {
|
|
531
|
-
return new ApicodegenError({
|
|
532
|
-
code: ErrorCodes.SPEC_NOT_FOUND,
|
|
533
|
-
message: "OpenAPI spec file not found",
|
|
534
|
-
location: path,
|
|
535
|
-
suggestions: [
|
|
536
|
-
"Check if the file exists using 'ls -la'",
|
|
537
|
-
"Use --spec to provide the correct path",
|
|
538
|
-
"For remote specs, ensure the URL is accessible"
|
|
539
|
-
],
|
|
540
|
-
cause
|
|
541
|
-
});
|
|
542
|
-
},
|
|
543
|
-
specFetchFailed(url, statusCode, cause) {
|
|
544
|
-
const message = statusCode ? `Failed to fetch OpenAPI spec (HTTP ${statusCode})` : "Failed to fetch OpenAPI spec from URL";
|
|
545
|
-
return new ApicodegenError({
|
|
546
|
-
code: ErrorCodes.SPEC_FETCH_FAILED,
|
|
547
|
-
message,
|
|
548
|
-
location: url,
|
|
549
|
-
suggestions: [
|
|
550
|
-
"Check if the URL is accessible in a browser",
|
|
551
|
-
"Download the spec file locally and use the local path",
|
|
552
|
-
"Verify CORS settings if fetching from a different origin"
|
|
553
|
-
],
|
|
554
|
-
cause
|
|
555
|
-
});
|
|
556
|
-
},
|
|
557
|
-
specParseFailed(path, line, column, cause) {
|
|
558
|
-
return new ApicodegenError({
|
|
559
|
-
code: ErrorCodes.SPEC_PARSE_FAILED,
|
|
560
|
-
message: "Failed to parse OpenAPI spec (invalid JSON or YAML)",
|
|
561
|
-
location: path,
|
|
562
|
-
line,
|
|
563
|
-
column,
|
|
564
|
-
suggestions: [
|
|
565
|
-
"Validate JSON syntax using jsonlint.com",
|
|
566
|
-
"For YAML specs, ensure proper indentation",
|
|
567
|
-
"Check for trailing commas or unquoted special characters"
|
|
568
|
-
],
|
|
569
|
-
cause
|
|
570
|
-
});
|
|
571
|
-
},
|
|
572
|
-
outputDirMissing(path, cause) {
|
|
573
|
-
return new ApicodegenError({
|
|
574
|
-
code: ErrorCodes.OUTPUT_DIR_MISSING,
|
|
575
|
-
message: "Output directory does not exist",
|
|
576
|
-
location: path,
|
|
577
|
-
suggestions: ["Create the directory: mkdir -p $(dirname <output>)", "Check if the path is correct"],
|
|
578
|
-
cause
|
|
579
|
-
});
|
|
580
|
-
},
|
|
581
|
-
configInvalid(path, cause) {
|
|
582
|
-
return new ApicodegenError({
|
|
583
|
-
code: ErrorCodes.CONFIG_INVALID,
|
|
584
|
-
message: "Invalid configuration file",
|
|
585
|
-
location: path,
|
|
586
|
-
suggestions: ["Validate JSON syntax in the config file", "Check for required fields (spec, output)"],
|
|
587
|
-
cause
|
|
588
|
-
});
|
|
589
|
-
},
|
|
590
|
-
validationFailed(path, details, cause) {
|
|
591
|
-
return new ApicodegenError({
|
|
592
|
-
code: ErrorCodes.VALIDATION_FAILED,
|
|
593
|
-
message: "OpenAPI spec validation failed",
|
|
594
|
-
location: path,
|
|
595
|
-
path: details,
|
|
596
|
-
suggestions: [
|
|
597
|
-
"Check OpenAPI spec structure at the specified path",
|
|
598
|
-
"Ensure all required fields are present",
|
|
599
|
-
"Validate using swagger.io editor"
|
|
600
|
-
],
|
|
601
|
-
cause
|
|
602
|
-
});
|
|
603
|
-
},
|
|
604
|
-
generationFailed(cause) {
|
|
605
|
-
return new ApicodegenError({
|
|
606
|
-
code: ErrorCodes.GENERATION_FAILED,
|
|
607
|
-
message: "Code generation failed",
|
|
608
|
-
suggestions: [
|
|
609
|
-
"Check for unsupported OpenAPI features",
|
|
610
|
-
"Ensure spec follows OpenAPI 2.0, 3.0, or 3.1 specification",
|
|
611
|
-
"Use --verbose for more details"
|
|
612
|
-
],
|
|
613
|
-
cause
|
|
614
|
-
});
|
|
615
|
-
},
|
|
616
|
-
typeCheckFailed(path, _errors, cause) {
|
|
617
|
-
return new ApicodegenError({
|
|
618
|
-
code: ErrorCodes.TYPE_CHECK_FAILED,
|
|
619
|
-
message: "TypeScript type check failed",
|
|
620
|
-
location: path,
|
|
621
|
-
suggestions: [
|
|
622
|
-
"Review type errors above",
|
|
623
|
-
"Check for schema inconsistencies",
|
|
624
|
-
"Update generated types or fix source schema"
|
|
625
|
-
],
|
|
626
|
-
cause
|
|
627
|
-
});
|
|
628
|
-
},
|
|
629
|
-
missingRequiredField(field, context) {
|
|
630
|
-
return new ApicodegenError({
|
|
631
|
-
code: ErrorCodes.VALIDATION_FAILED,
|
|
632
|
-
message: `Missing required field: ${field}`,
|
|
633
|
-
path: context,
|
|
634
|
-
suggestions: [`Add the '${field}' field to your configuration`]
|
|
635
|
-
});
|
|
636
|
-
}
|
|
637
|
-
};
|
|
638
|
-
/**
|
|
639
|
-
* Wrap unknown error in ApicodegenError if needed
|
|
640
|
-
*/
|
|
641
|
-
function wrapError(error, context) {
|
|
642
|
-
if (error instanceof ApicodegenError) return error;
|
|
643
|
-
if (error instanceof Error) return new ApicodegenError({
|
|
644
|
-
code: context?.code || ErrorCodes.GENERATION_FAILED,
|
|
645
|
-
message: context?.message || error.message,
|
|
646
|
-
location: context?.location,
|
|
647
|
-
suggestions: context?.suggestions,
|
|
648
|
-
cause: error
|
|
649
|
-
});
|
|
650
|
-
return new ApicodegenError({
|
|
651
|
-
code: context?.code || ErrorCodes.GENERATION_FAILED,
|
|
652
|
-
message: String(error),
|
|
653
|
-
suggestions: context?.suggestions
|
|
654
|
-
});
|
|
655
|
-
}
|
|
656
|
-
/**
|
|
657
|
-
* Check if error is an ApicodegenError
|
|
658
|
-
*/
|
|
659
|
-
function isApicodegenError(error) {
|
|
660
|
-
return error instanceof ApicodegenError;
|
|
661
|
-
}
|
|
662
|
-
//#endregion
|
|
663
|
-
//#region src/core/generator/index.ts
|
|
664
|
-
var Generator = class Generator {
|
|
665
|
-
/**
|
|
666
|
-
* Converts an array of TypeScript statements into a formatted string of code.
|
|
667
|
-
*
|
|
668
|
-
* @param statements - The array of TypeScript statement nodes.
|
|
669
|
-
* @returns Formatted code as a string.
|
|
670
|
-
* @throws {Error} If no valid statements are provided.
|
|
671
|
-
*/
|
|
672
|
-
static toCode(statements) {
|
|
673
|
-
if (statements.length === 0) return "// No api declaration found.";
|
|
674
|
-
const sourceFile = factory.createSourceFile(statements, factory.createToken(SyntaxKind.EndOfFileToken), NodeFlags.None);
|
|
675
|
-
return createPrinter().printFile(sourceFile);
|
|
676
|
-
}
|
|
677
|
-
static async write(code, filepath) {
|
|
678
|
-
const { mkdir } = await import("node:fs/promises");
|
|
679
|
-
const { dirname } = await import("node:path");
|
|
680
|
-
try {
|
|
681
|
-
await mkdir(dirname(filepath), { recursive: true });
|
|
682
|
-
await writeFile(filepath, code);
|
|
683
|
-
} catch (error) {
|
|
684
|
-
throw new ApicodegenError({
|
|
685
|
-
code: ErrorCodes.OUTPUT_DIR_MISSING,
|
|
686
|
-
message: "Failed to write generated code to output file",
|
|
687
|
-
location: filepath,
|
|
688
|
-
cause: error instanceof Error ? error : new Error(String(error)),
|
|
689
|
-
suggestions: ["Verify the output directory path is writable", "Check that the parent directory exists or can be created"]
|
|
690
|
-
});
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
/**
|
|
694
|
-
* Converts a path string with parameters into a TypeScript template expression.
|
|
695
|
-
* Handles query parameters and path placeholders.
|
|
696
|
-
*
|
|
697
|
-
* @param path - The base path string containing placeholders.
|
|
698
|
-
* @param parameters - Array of parameter objects defining the parameters.
|
|
699
|
-
* @param basePath - Optional base path to prepend (default: "").
|
|
700
|
-
* @returns A TypeScript template expressi
|
|
701
|
-
*/
|
|
702
|
-
static toUrlTemplate(path, parameters, basePath = "") {
|
|
703
|
-
const queryParameters = parameters.filter((p) => p.in === "query");
|
|
704
|
-
if (queryParameters.length > 0) {
|
|
705
|
-
const queryString = queryParameters.map((qp, index) => `${index === 0 ? "?" : "&"}${encodeURIComponent(qp.name)}={${Base.normalize(qp.name)}}`).join("");
|
|
706
|
-
path += queryString;
|
|
707
|
-
}
|
|
708
|
-
const pathSegments = path.replaceAll("{", "${").split("$").filter(Boolean);
|
|
709
|
-
if (pathSegments.length === 1) return factory.createNoSubstitutionTemplateLiteral(basePath + path);
|
|
710
|
-
return factory.createTemplateExpression(factory.createTemplateHead(basePath + pathSegments[0]), pathSegments.slice(1).map((segment, index) => {
|
|
711
|
-
const match = /^{(.+)}(.+)?/gm.exec(segment);
|
|
712
|
-
const isLastSegment = index === pathSegments.length - 2;
|
|
713
|
-
if (!match) throw new Error(`Invalid path segment: ${segment}`);
|
|
714
|
-
return factory.createTemplateSpan(factory.createIdentifier(Base.normalize(match[1])), !isLastSegment ? factory.createTemplateMiddle(match[2]) : factory.createTemplateTail(match[2] || ""));
|
|
715
|
-
}));
|
|
716
|
-
}
|
|
717
|
-
/**
|
|
718
|
-
* Adds synthetic comments to a TypeScript AST node.
|
|
719
|
-
*
|
|
720
|
-
* @param node - The target AST node.
|
|
721
|
-
* @param comments - Array of comment objects to add.
|
|
722
|
-
*/
|
|
723
|
-
static addComments(node, comments) {
|
|
724
|
-
if (!Array.isArray(comments) || comments.filter(Boolean).length === 0) return;
|
|
725
|
-
const formatComment = (comment) => {
|
|
726
|
-
if (comment.tag === "returns") return `* @returns {${comment.type}} ${comment.comment ?? ""}`;
|
|
727
|
-
if (comment.tag === "param") return comment.comment ? `* @param ${comment.paramName} - ${comment.comment}` : `* @param ${comment.paramName}`;
|
|
728
|
-
if (comment.tag) return `* @${comment.tag} ${comment.comment ?? ""}`;
|
|
729
|
-
return `* ${comment.comment}`;
|
|
730
|
-
};
|
|
731
|
-
const formattedComments = comments.map(formatComment).join("\n").trim() + "\n";
|
|
732
|
-
addSyntheticLeadingComment(node, SyntaxKind.MultiLineCommentTrivia, formattedComments, true);
|
|
1137
|
+
const formattedComments = comments.map(formatComment).join("\n").replaceAll("*/", "*\\/").trim() + "\n";
|
|
1138
|
+
addSyntheticLeadingComment(node, SyntaxKind.MultiLineCommentTrivia, formattedComments, true);
|
|
733
1139
|
}
|
|
734
1140
|
/**
|
|
735
1141
|
* Checks if a schema represents a binary type.
|
|
@@ -745,6 +1151,16 @@ var Generator = class Generator {
|
|
|
745
1151
|
const nonArraySchema = schema;
|
|
746
1152
|
return nonArraySchema.format === "blob" || nonArraySchema.format === "binary" || nonArraySchema.type === "file";
|
|
747
1153
|
}
|
|
1154
|
+
/** Whether a schema is a primitive text part (not binary, ref, or object). */
|
|
1155
|
+
static isTextSchema(schema) {
|
|
1156
|
+
if (!schema || schema.isRef) return false;
|
|
1157
|
+
if (Generator.isBinarySchema(schema)) return false;
|
|
1158
|
+
if (schema.type === "array") {
|
|
1159
|
+
const items = schema.items;
|
|
1160
|
+
return items ? Generator.isTextSchema(items) : false;
|
|
1161
|
+
}
|
|
1162
|
+
return schema.type === "string" || schema.type === "integer" || schema.type === "number" || schema.type === "boolean";
|
|
1163
|
+
}
|
|
748
1164
|
static schemaToTypeString(schema) {
|
|
749
1165
|
if (schema.type === "array") {
|
|
750
1166
|
const arraySchema = schema;
|
|
@@ -763,15 +1179,16 @@ var Generator = class Generator {
|
|
|
763
1179
|
static generateParamTags(parameters, requestBody) {
|
|
764
1180
|
const tags = [];
|
|
765
1181
|
for (const p of parameters) {
|
|
766
|
-
const paramName = Base.
|
|
1182
|
+
const paramName = Base.toIdentifier(p.name);
|
|
767
1183
|
let paramType = "unknown";
|
|
768
1184
|
if (p.schema) paramType = Generator.schemaToTypeString(p.schema);
|
|
769
1185
|
const isOptional = p.required === false;
|
|
1186
|
+
const inPrefix = p.in ? `[${p.in}] ` : "";
|
|
770
1187
|
tags.push({
|
|
771
1188
|
tag: "param",
|
|
772
1189
|
paramName,
|
|
773
1190
|
type: `${paramType}${isOptional ? " | undefined" : ""}`,
|
|
774
|
-
comment: p.description ?? ""
|
|
1191
|
+
comment: `${inPrefix}${p.description?.trim() ?? ""}`
|
|
775
1192
|
});
|
|
776
1193
|
}
|
|
777
1194
|
if (requestBody?.schema && "properties" in requestBody.schema) {
|
|
@@ -786,7 +1203,7 @@ var Generator = class Generator {
|
|
|
786
1203
|
tag: "param",
|
|
787
1204
|
paramName,
|
|
788
1205
|
type: `${paramType}${isOptional ? " | undefined" : ""}`,
|
|
789
|
-
comment: schema.description ?? ""
|
|
1206
|
+
comment: schema.description?.trim() ?? ""
|
|
790
1207
|
});
|
|
791
1208
|
}
|
|
792
1209
|
}
|
|
@@ -795,8 +1212,47 @@ var Generator = class Generator {
|
|
|
795
1212
|
static toRequestBodyTypeNode(schema) {
|
|
796
1213
|
return factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("req"), void 0, Generator.toTypeNode(schema));
|
|
797
1214
|
}
|
|
1215
|
+
/**
|
|
1216
|
+
* Narrows a `oneOf` member with its discriminator mapping value:
|
|
1217
|
+
* `Cat & { petType: 'cat' }`.
|
|
1218
|
+
*/
|
|
1219
|
+
static discriminatedMember(schema, discriminator) {
|
|
1220
|
+
const node = Generator.toTypeNode(schema);
|
|
1221
|
+
const ref = schema.ref;
|
|
1222
|
+
if (!ref) return node;
|
|
1223
|
+
const name = Base.ref2name(ref);
|
|
1224
|
+
const value = Object.entries(discriminator.mapping ?? {}).find(([, target]) => Base.ref2name(target) === name)?.[0];
|
|
1225
|
+
if (value === void 0) return node;
|
|
1226
|
+
return factory.createIntersectionTypeNode([node, factory.createTypeLiteralNode([factory.createPropertySignature(void 0, factory.createStringLiteral(discriminator.propertyName), void 0, factory.createLiteralTypeNode(factory.createStringLiteral(value)))])]);
|
|
1227
|
+
}
|
|
798
1228
|
static toTypeNode(schema) {
|
|
1229
|
+
if ("const" in schema && schema.const !== void 0) return Generator.toLiteralTypeNode(schema.const);
|
|
1230
|
+
const base = Generator.toTypeNodeInner(schema);
|
|
1231
|
+
if (schema.nullable) return factory.createUnionTypeNode([base, factory.createLiteralTypeNode(factory.createNull())]);
|
|
1232
|
+
return base;
|
|
1233
|
+
}
|
|
1234
|
+
static toLiteralTypeNode(value) {
|
|
1235
|
+
if (typeof value === "string") return factory.createLiteralTypeNode(factory.createStringLiteral(value));
|
|
1236
|
+
if (typeof value === "number") return factory.createLiteralTypeNode(factory.createNumericLiteral(value));
|
|
1237
|
+
return factory.createLiteralTypeNode(value ? factory.createTrue() : factory.createFalse());
|
|
1238
|
+
}
|
|
1239
|
+
static primitiveTypeNode(type) {
|
|
1240
|
+
switch (type) {
|
|
1241
|
+
case "string": return factory.createToken(SyntaxKind.StringKeyword);
|
|
1242
|
+
case "integer":
|
|
1243
|
+
case "number": return factory.createToken(SyntaxKind.NumberKeyword);
|
|
1244
|
+
case "boolean": return factory.createToken(SyntaxKind.BooleanKeyword);
|
|
1245
|
+
case "object": return factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), factory.createToken(SyntaxKind.UnknownKeyword)]);
|
|
1246
|
+
default: return factory.createTypeReferenceNode(factory.createIdentifier(Base.upperCamelCase(type)));
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
static toTypeNodeInner(schema) {
|
|
799
1250
|
const { type, ref } = schema;
|
|
1251
|
+
const unionTypes = schema.types;
|
|
1252
|
+
if (unionTypes && unionTypes.length > 0) {
|
|
1253
|
+
const nodes = Generator.deduplicateTypes(unionTypes.map((name) => Generator.primitiveTypeNode(name)));
|
|
1254
|
+
return nodes.length === 1 ? nodes[0] : factory.createUnionTypeNode(nodes);
|
|
1255
|
+
}
|
|
800
1256
|
if (ref) {
|
|
801
1257
|
const identify = Base.ref2name(ref);
|
|
802
1258
|
return factory.createTypeReferenceNode(factory.createIdentifier(identify === "unknown" ? identify : Base.upperCamelCase(identify)));
|
|
@@ -808,19 +1264,28 @@ var Generator = class Generator {
|
|
|
808
1264
|
}
|
|
809
1265
|
case "object": {
|
|
810
1266
|
const propsCount = Object.keys(schema.properties ?? {}).length;
|
|
811
|
-
|
|
1267
|
+
const additional = schema.additionalProperties;
|
|
1268
|
+
const additionalValue = additional && additional !== true ? Generator.toTypeNode(additional) : factory.createToken(SyntaxKind.UnknownKeyword);
|
|
1269
|
+
if (!schema.properties || propsCount === 0) return factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), additionalValue]);
|
|
812
1270
|
const props = Object.keys(schema.properties);
|
|
813
|
-
|
|
1271
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
1272
|
+
const literal = factory.createTypeLiteralNode(props.map((propKey) => {
|
|
814
1273
|
const propSchema = schema.properties[propKey];
|
|
815
|
-
return factory.createPropertySignature(void 0, factory.createStringLiteral(propKey),
|
|
1274
|
+
return factory.createPropertySignature(void 0, factory.createStringLiteral(propKey), required.includes(propKey) ? void 0 : factory.createToken(SyntaxKind.QuestionToken), Generator.toTypeNode(propSchema));
|
|
816
1275
|
}));
|
|
1276
|
+
const additionalProps = schema.additionalProperties;
|
|
1277
|
+
if (additionalProps === void 0 || additionalProps === false) return literal;
|
|
1278
|
+
return factory.createIntersectionTypeNode([literal, factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), additionalProps === true ? factory.createToken(SyntaxKind.UnknownKeyword) : Generator.toTypeNode(additionalProps)])]);
|
|
817
1279
|
}
|
|
818
1280
|
case "integer":
|
|
819
1281
|
case "number":
|
|
820
|
-
if (schema.enum)
|
|
1282
|
+
if (schema.enum) {
|
|
1283
|
+
const values = schema.enum.filter((value) => typeof value === "number");
|
|
1284
|
+
if (values.length > 0) return factory.createUnionTypeNode(values.map((value) => factory.createLiteralTypeNode(factory.createNumericLiteral(value))));
|
|
1285
|
+
}
|
|
821
1286
|
return factory.createToken(SyntaxKind.NumberKeyword);
|
|
822
1287
|
case "boolean": return factory.createToken(SyntaxKind.BooleanKeyword);
|
|
823
|
-
case "file": return factory.createTypeReferenceNode(factory.createIdentifier("Blob"));
|
|
1288
|
+
case "file": return factory.createTypeReferenceNode(factory.createQualifiedName(factory.createIdentifier("globalThis"), factory.createIdentifier("Blob")));
|
|
824
1289
|
default: {
|
|
825
1290
|
const { format, oneOf, allOf, anyOf, type, enum: enum_ } = schema;
|
|
826
1291
|
switch (format) {
|
|
@@ -828,94 +1293,334 @@ var Generator = class Generator {
|
|
|
828
1293
|
case "string": return factory.createToken(SyntaxKind.StringKeyword);
|
|
829
1294
|
case "boolean": return factory.createToken(SyntaxKind.BooleanKeyword);
|
|
830
1295
|
case "blob":
|
|
831
|
-
case "binary": return factory.createTypeReferenceNode(factory.createIdentifier("Blob"));
|
|
832
|
-
|
|
1296
|
+
case "binary": return factory.createTypeReferenceNode(factory.createQualifiedName(factory.createIdentifier("globalThis"), factory.createIdentifier("Blob")));
|
|
1297
|
+
}
|
|
1298
|
+
if (enum_) {
|
|
1299
|
+
const values = enum_.filter((value) => typeof value === "string");
|
|
1300
|
+
if (values.length > 0) return factory.createUnionTypeNode(values.map((value) => factory.createLiteralTypeNode(factory.createStringLiteral(value))));
|
|
833
1301
|
}
|
|
834
|
-
if (enum_) return factory.createUnionTypeNode(enum_.map((e) => factory.createLiteralTypeNode(factory.createStringLiteral(e))));
|
|
835
1302
|
if (type === "string") return factory.createToken(SyntaxKind.StringKeyword);
|
|
836
|
-
if (oneOf)
|
|
837
|
-
|
|
1303
|
+
if (oneOf) {
|
|
1304
|
+
const discriminator = schema.discriminator;
|
|
1305
|
+
if (discriminator?.mapping) return factory.createUnionTypeNode(Generator.deduplicateTypes(oneOf.map((member) => Generator.discriminatedMember(member, discriminator))));
|
|
1306
|
+
const uniqueTypes = Generator.deduplicateTypes(oneOf.map((s) => Generator.toTypeNode(s)));
|
|
1307
|
+
return factory.createUnionTypeNode(uniqueTypes);
|
|
1308
|
+
}
|
|
1309
|
+
if (anyOf) {
|
|
1310
|
+
const uniqueTypes = Generator.deduplicateTypes(anyOf.map((s) => Generator.toTypeNode(s)));
|
|
1311
|
+
return factory.createUnionTypeNode(uniqueTypes);
|
|
1312
|
+
}
|
|
838
1313
|
if (allOf) return factory.createIntersectionTypeNode(allOf.map((schema) => Generator.toTypeNode(schema)));
|
|
839
1314
|
if (type && typeof type === "string") return factory.createTypeReferenceNode(type !== "unknown" && type !== "null" ? factory.createIdentifier(Base.upperCamelCase(type)) : type);
|
|
840
1315
|
}
|
|
841
1316
|
}
|
|
842
1317
|
return factory.createToken(SyntaxKind.UnknownKeyword);
|
|
843
1318
|
}
|
|
1319
|
+
static toResponsesTypeNode(responses) {
|
|
1320
|
+
return factory.createTypeLiteralNode(Object.entries(responses).map(([code, mediaTypes]) => {
|
|
1321
|
+
const schema = mediaTypes[0]?.schema;
|
|
1322
|
+
return factory.createPropertySignature(void 0, factory.createStringLiteral(code), void 0, schema ? Generator.toTypeNode(schema) : factory.createToken(SyntaxKind.UnknownKeyword));
|
|
1323
|
+
}));
|
|
1324
|
+
}
|
|
1325
|
+
static deduplicateTypes(types) {
|
|
1326
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1327
|
+
const unique = [];
|
|
1328
|
+
for (const type of types) {
|
|
1329
|
+
const key = Generator.getTypeNodeKey(type);
|
|
1330
|
+
if (!seen.has(key)) {
|
|
1331
|
+
seen.add(key);
|
|
1332
|
+
unique.push(type);
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
return unique;
|
|
1336
|
+
}
|
|
1337
|
+
static getTypeNodeKey(type) {
|
|
1338
|
+
return JSON.stringify(type);
|
|
1339
|
+
}
|
|
844
1340
|
static toDeclarationNodes(parameters) {
|
|
845
1341
|
const objectElements = [];
|
|
846
1342
|
const typeObjectElements = [];
|
|
847
1343
|
const refParameters = [];
|
|
848
1344
|
for (const parameter of parameters) if (parameter.ref) {
|
|
849
1345
|
const refName = Base.ref2name(parameter.ref);
|
|
850
|
-
refParameters.push(factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(Base.
|
|
1346
|
+
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));
|
|
851
1347
|
} else {
|
|
852
1348
|
const { name, schema, required } = parameter;
|
|
853
|
-
|
|
854
|
-
|
|
1349
|
+
const key = Base.camelCase(Base.normalize(name));
|
|
1350
|
+
const id = Base.toIdentifier(name);
|
|
1351
|
+
objectElements.push(factory.createBindingElement(void 0, key === id ? void 0 : factory.createIdentifier(key), factory.createIdentifier(id)));
|
|
1352
|
+
typeObjectElements.push(factory.createPropertySignature([], factory.createIdentifier(key), required ? void 0 : factory.createToken(SyntaxKind.QuestionToken), !schema ? factory.createToken(SyntaxKind.UnknownKeyword) : Generator.toTypeNode(schema)));
|
|
855
1353
|
}
|
|
856
1354
|
if (objectElements.length > 0) return [factory.createParameterDeclaration(void 0, void 0, factory.createObjectBindingPattern(objectElements), void 0, factory.createTypeLiteralNode(typeObjectElements), void 0), ...refParameters];
|
|
857
1355
|
return refParameters;
|
|
858
1356
|
}
|
|
1357
|
+
/** Property keys listed in a parent schema's `required` array. */
|
|
1358
|
+
static requiredPropertyKeys(schema) {
|
|
1359
|
+
return schema && Array.isArray(schema.required) ? schema.required : [];
|
|
1360
|
+
}
|
|
859
1361
|
static toFormDataStatement(parameters, requestBody) {
|
|
860
1362
|
const statements = [];
|
|
1363
|
+
const requiredKeys = Generator.requiredPropertyKeys(requestBody);
|
|
861
1364
|
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));
|
|
862
1365
|
statements.push(fdDeclaration);
|
|
863
1366
|
parameters.forEach((parameter) => {
|
|
864
|
-
|
|
1367
|
+
const id = factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
1368
|
+
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]))));
|
|
865
1369
|
});
|
|
866
1370
|
if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) Object.keys(requestBody.properties).forEach((key) => {
|
|
867
1371
|
const schemaByKey = requestBody.properties[key];
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
factory.
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
1372
|
+
const accessor = factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key));
|
|
1373
|
+
if (schemaByKey.type === "array" && Generator.isBinarySchema(schemaByKey)) {
|
|
1374
|
+
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")), [], [
|
|
1375
|
+
factory.createStringLiteral(key),
|
|
1376
|
+
factory.createIdentifier("file"),
|
|
1377
|
+
factory.createPropertyAccessExpression(factory.createAsExpression(factory.createIdentifier("file"), factory.createTypeReferenceNode(factory.createIdentifier("File"), void 0)), factory.createIdentifier("name"))
|
|
1378
|
+
]))]));
|
|
1379
|
+
statements.push(requiredKeys.includes(key) ? loop : factory.createIfStatement(factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([loop], true)));
|
|
1380
|
+
} 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))])])));
|
|
874
1381
|
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))])]))));
|
|
875
1382
|
});
|
|
876
1383
|
return statements;
|
|
877
1384
|
}
|
|
878
|
-
|
|
879
|
-
|
|
1385
|
+
/**
|
|
1386
|
+
* Build statements that construct a `URLSearchParams` from request body
|
|
1387
|
+
* fields for an `application/x-www-form-urlencoded` request.
|
|
1388
|
+
*
|
|
1389
|
+
* Skips `undefined` / `null` values so optional fields don't end up as
|
|
1390
|
+
* the literal string `"undefined"` in the URL (fixes #8).
|
|
1391
|
+
*
|
|
1392
|
+
* The resulting `sp` variable is referenced by the adapter as the
|
|
1393
|
+
* `body` payload.
|
|
1394
|
+
*/
|
|
1395
|
+
static toURLSearchParamsStatement(parameters, requestBody) {
|
|
1396
|
+
const statements = [];
|
|
1397
|
+
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));
|
|
1398
|
+
statements.push(spDeclaration);
|
|
1399
|
+
const appendValue = (key, valueExpr) => factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("sp"), factory.createIdentifier("append")), void 0, [factory.createStringLiteral(key), valueExpr]));
|
|
1400
|
+
if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) {
|
|
1401
|
+
const requiredKeys = Generator.requiredPropertyKeys(requestBody);
|
|
1402
|
+
for (const key of Object.keys(requestBody.properties)) {
|
|
1403
|
+
const fieldSchema = requestBody.properties[key];
|
|
1404
|
+
const required = requiredKeys.includes(key);
|
|
1405
|
+
const accessor = factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key));
|
|
1406
|
+
const nonNull = factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword));
|
|
1407
|
+
if (fieldSchema.type === "array") {
|
|
1408
|
+
const item = factory.createIdentifier("item");
|
|
1409
|
+
const loop = factory.createForOfStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(item)], NodeFlags.Const), accessor, factory.createBlock([appendValue(key, Generator.toFormDataCompatibleString(item, fieldSchema.items))], true));
|
|
1410
|
+
statements.push(required ? loop : factory.createIfStatement(nonNull, factory.createBlock([loop], true)));
|
|
1411
|
+
continue;
|
|
1412
|
+
}
|
|
1413
|
+
const append = appendValue(key, Generator.toFormDataCompatibleString(accessor, fieldSchema));
|
|
1414
|
+
statements.push(required ? append : factory.createIfStatement(nonNull, factory.createBlock([append], true)));
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
for (const parameter of parameters) {
|
|
1418
|
+
if (parameter.in === "header" || parameter.in === "cookie" || parameter.in === "path") continue;
|
|
1419
|
+
const accessor = factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
1420
|
+
statements.push(factory.createIfStatement(factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([appendValue(parameter.name, Generator.toFormDataCompatibleString(accessor))], true)));
|
|
1421
|
+
}
|
|
1422
|
+
return statements;
|
|
1423
|
+
}
|
|
1424
|
+
/**
|
|
1425
|
+
* Render `expr` as a string suitable for `FormData.append` /
|
|
1426
|
+
* `URLSearchParams.append`. Object/array schemas are JSON-stringified,
|
|
1427
|
+
* everything else is coerced via `String(...)`.
|
|
1428
|
+
*/
|
|
1429
|
+
static toFormDataCompatibleString(expr, schema) {
|
|
1430
|
+
if (schema && (schema.type === "object" || schema.type === "array")) return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), void 0, [expr]);
|
|
1431
|
+
return factory.createCallExpression(factory.createIdentifier("String"), void 0, [expr]);
|
|
1432
|
+
}
|
|
1433
|
+
static bodyBlock(uri, method, parameters, requestBody, response, adapter, errorMode, auth, requestControl) {
|
|
880
1434
|
const shouldParseResponseToJSON = "application/json" === response?.type;
|
|
881
|
-
const isEventStream = response?.type === "text/event-stream";
|
|
882
|
-
const isRequestBodyBinary = requestBody?.schema && requestBody.schema.type === "array" && Generator.isBinarySchema(requestBody.schema);
|
|
883
1435
|
const parametersShouldPutInFormData = parameters.filter((p) => p.in === "formData" || p.schema && Generator.isBinarySchema(p.schema));
|
|
884
1436
|
const parametersShouldNotPutInFormData = parameters.filter((p) => !parametersShouldPutInFormData.includes(p));
|
|
1437
|
+
const inBody = parametersShouldNotPutInFormData.filter((p) => !p.in || p.in === "body");
|
|
885
1438
|
const isRequestBodyContainsBinary = requestBody?.schema && "properties" in requestBody.schema && Object.values(requestBody.schema?.properties ?? {}).some((p) => Generator.isBinarySchema(p));
|
|
886
1439
|
const hasBinaryInParameters = parameters.some((p) => p?.schema && Generator.isBinarySchema(p.schema));
|
|
887
|
-
const
|
|
888
|
-
|
|
1440
|
+
const mediaType = (requestBody?.type ?? "").toLowerCase().split(";")[0]?.trim();
|
|
1441
|
+
const requestSchemaIsBinary = requestBody?.schema && Generator.isBinarySchema(requestBody.schema);
|
|
1442
|
+
const multipartParts = requestBody?.schema && "properties" in requestBody.schema && requestBody.schema.properties ? Object.values(requestBody.schema.properties) : [];
|
|
1443
|
+
const hasOnlyTextParts = multipartParts.length > 0 && multipartParts.every((part) => Generator.isTextSchema(part));
|
|
1444
|
+
let bodyKind = "none";
|
|
1445
|
+
let bodyContentType;
|
|
1446
|
+
if (mediaType === "multipart/form-data") {
|
|
1447
|
+
if (hasBinaryInParameters || isRequestBodyContainsBinary || hasOnlyTextParts || parametersShouldPutInFormData.length > 0) bodyKind = "form-data";
|
|
1448
|
+
} else if (mediaType === "application/x-www-form-urlencoded") {
|
|
1449
|
+
bodyKind = "urlencoded";
|
|
1450
|
+
bodyContentType = "application/x-www-form-urlencoded";
|
|
1451
|
+
} else if (mediaType === "application/json") {
|
|
1452
|
+
if (requestBody?.schema || inBody.length > 0) {
|
|
1453
|
+
bodyKind = "json";
|
|
1454
|
+
bodyContentType = "application/json";
|
|
1455
|
+
}
|
|
1456
|
+
} else if (requestSchemaIsBinary) {
|
|
1457
|
+
bodyKind = "binary";
|
|
1458
|
+
bodyContentType = requestBody?.type;
|
|
1459
|
+
} else if (requestBody?.schema) {
|
|
1460
|
+
bodyKind = "json";
|
|
1461
|
+
bodyContentType = requestBody?.type;
|
|
1462
|
+
}
|
|
1463
|
+
const preStatements = [];
|
|
1464
|
+
if (bodyKind === "form-data") preStatements.push(...Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema));
|
|
1465
|
+
else if (bodyKind === "urlencoded") preStatements.push(...Generator.toURLSearchParamsStatement(parametersShouldNotPutInFormData, requestBody?.schema));
|
|
1466
|
+
return factory.createBlock([...preStatements, ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, bodyKind, bodyContentType, shouldParseResponseToJSON, errorMode, auth, requestControl)]);
|
|
1467
|
+
}
|
|
1468
|
+
/**
|
|
1469
|
+
* Resolves effective security requirements into concrete injections.
|
|
1470
|
+
* Requirements are OR-ed by the spec; we inject every credential the
|
|
1471
|
+
* caller provides, so either branch of an OR works.
|
|
1472
|
+
*/
|
|
1473
|
+
static toAuthInjections(security, schemes) {
|
|
1474
|
+
const injections = [];
|
|
1475
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1476
|
+
for (const requirement of security ?? []) for (const schemeName of Object.keys(requirement)) {
|
|
1477
|
+
const scheme = schemes[schemeName];
|
|
1478
|
+
if (!scheme) continue;
|
|
1479
|
+
let injection;
|
|
1480
|
+
if (scheme.type === "apiKey" && scheme.in && scheme.name) injection = {
|
|
1481
|
+
scheme: schemeName,
|
|
1482
|
+
location: scheme.in,
|
|
1483
|
+
name: scheme.name,
|
|
1484
|
+
kind: "raw"
|
|
1485
|
+
};
|
|
1486
|
+
else if (scheme.type === "http") injection = {
|
|
1487
|
+
scheme: schemeName,
|
|
1488
|
+
location: "header",
|
|
1489
|
+
name: "Authorization",
|
|
1490
|
+
kind: scheme.scheme === "basic" ? "basic" : "bearer"
|
|
1491
|
+
};
|
|
1492
|
+
else if (scheme.type === "basic" || scheme.type === "oauth2" || scheme.type === "openIdConnect") injection = {
|
|
1493
|
+
scheme: schemeName,
|
|
1494
|
+
location: "header",
|
|
1495
|
+
name: "Authorization",
|
|
1496
|
+
kind: scheme.type === "basic" ? "basic" : "bearer"
|
|
1497
|
+
};
|
|
1498
|
+
if (!injection) continue;
|
|
1499
|
+
const key = `${injection.location}:${injection.name}`;
|
|
1500
|
+
if (seen.has(key)) continue;
|
|
1501
|
+
seen.add(key);
|
|
1502
|
+
injections.push(injection);
|
|
1503
|
+
}
|
|
1504
|
+
return injections;
|
|
1505
|
+
}
|
|
1506
|
+
/** `{ [scheme: string]: string | { username: string; password: string } }` */
|
|
1507
|
+
static authOptionsTypeNode() {
|
|
1508
|
+
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))])]))]);
|
|
1509
|
+
}
|
|
1510
|
+
/** `{ signal?: AbortSignal; headers?: Record<string, string>; timeout?: number }` */
|
|
1511
|
+
static requestOptionsTypeNode() {
|
|
1512
|
+
const stringType = factory.createKeywordTypeNode(SyntaxKind.StringKeyword);
|
|
1513
|
+
return factory.createTypeLiteralNode([
|
|
1514
|
+
factory.createPropertySignature(void 0, factory.createIdentifier("signal"), factory.createToken(SyntaxKind.QuestionToken), factory.createTypeReferenceNode(factory.createIdentifier("AbortSignal"))),
|
|
1515
|
+
factory.createPropertySignature(void 0, factory.createIdentifier("headers"), factory.createToken(SyntaxKind.QuestionToken), factory.createTypeReferenceNode(factory.createIdentifier("Record"), [stringType, stringType])),
|
|
1516
|
+
factory.createPropertySignature(void 0, factory.createIdentifier("timeout"), factory.createToken(SyntaxKind.QuestionToken), factory.createKeywordTypeNode(SyntaxKind.NumberKeyword))
|
|
1517
|
+
]);
|
|
889
1518
|
}
|
|
890
1519
|
static schemaToStatemets(parsedDoc, adaptor, options) {
|
|
891
1520
|
const statements = [];
|
|
892
|
-
const { apis, schemas = {}, enums } = parsedDoc;
|
|
1521
|
+
const { apis, schemas = {}, enums, securitySchemes = {} } = parsedDoc;
|
|
893
1522
|
const enumNames = [];
|
|
894
1523
|
for (const enumObject of enums) {
|
|
895
1524
|
enumNames.push(Base.upperCamelCase(enumObject.name));
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
1525
|
+
const usedKeys = /* @__PURE__ */ new Set();
|
|
1526
|
+
const members = enumObject.enum.filter((member) => typeof member === "string" || typeof member === "number").map((member, index) => {
|
|
1527
|
+
let key = typeof member === "string" && !/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(member) ? member : `Value_${String(member).replace(/[^A-Za-z0-9]/g, "_")}`;
|
|
1528
|
+
if (usedKeys.has(key)) key = `${key}_${index}`;
|
|
1529
|
+
usedKeys.add(key);
|
|
1530
|
+
return factory.createEnumMember(factory.createStringLiteral(key), typeof member === "string" ? factory.createStringLiteral(member) : factory.createNumericLiteral(member));
|
|
1531
|
+
});
|
|
1532
|
+
statements.push(factory.createEnumDeclaration([factory.createToken(SyntaxKind.ExportKeyword)], factory.createIdentifier(Base.upperCamelCase(enumObject.name)), members));
|
|
899
1533
|
}
|
|
900
1534
|
for (const schemaKey in schemas) if (Object.hasOwn(schemas, schemaKey) && !enumNames.includes(Base.upperCamelCase(schemaKey))) {
|
|
901
1535
|
const schema = schemas[schemaKey];
|
|
902
1536
|
statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(Base.upperCamelCase(schemaKey)), void 0, Generator.toTypeNode(schema)));
|
|
903
1537
|
}
|
|
1538
|
+
const reserveUnique = createUniqueNameResolver();
|
|
1539
|
+
let authTypeName;
|
|
1540
|
+
let requestOptionsTypeName;
|
|
904
1541
|
for (const uri in apis) {
|
|
905
1542
|
const operations = apis[uri];
|
|
906
1543
|
for (const operation of operations) {
|
|
907
1544
|
const { method, operationId, requestBody = [], responses = [], summary, deprecated, description } = operation;
|
|
908
|
-
|
|
909
|
-
|
|
1545
|
+
const { parameters = [] } = operation;
|
|
1546
|
+
const authInjections = Generator.toAuthInjections(operation.security, securitySchemes);
|
|
1547
|
+
let authArgument;
|
|
1548
|
+
let authTypeReference;
|
|
1549
|
+
if (authInjections.length > 0) {
|
|
1550
|
+
const typeName = authTypeName ?? (() => {
|
|
1551
|
+
let candidate = "AuthOptions";
|
|
1552
|
+
while (Object.keys(schemas).some((key) => Base.upperCamelCase(key) === candidate) || enumNames.includes(candidate)) candidate += "2";
|
|
1553
|
+
return candidate;
|
|
1554
|
+
})();
|
|
1555
|
+
if (!authTypeName) {
|
|
1556
|
+
authTypeName = typeName;
|
|
1557
|
+
statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, Generator.authOptionsTypeNode()));
|
|
1558
|
+
}
|
|
1559
|
+
const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
|
|
1560
|
+
taken.add("req");
|
|
1561
|
+
let name = "auth";
|
|
1562
|
+
let suffix = 2;
|
|
1563
|
+
while (taken.has(name)) {
|
|
1564
|
+
name = `auth${suffix}`;
|
|
1565
|
+
suffix++;
|
|
1566
|
+
}
|
|
1567
|
+
authArgument = {
|
|
1568
|
+
name,
|
|
1569
|
+
injections: authInjections
|
|
1570
|
+
};
|
|
1571
|
+
authTypeReference = factory.createTypeReferenceNode(factory.createIdentifier(typeName));
|
|
1572
|
+
}
|
|
1573
|
+
const optionsTypeName = requestOptionsTypeName ?? (() => {
|
|
1574
|
+
let candidate = "RequestOptions";
|
|
1575
|
+
while (Object.keys(schemas).some((key) => Base.upperCamelCase(key) === candidate) || enumNames.includes(candidate)) candidate += "2";
|
|
1576
|
+
return candidate;
|
|
1577
|
+
})();
|
|
1578
|
+
if (!requestOptionsTypeName) {
|
|
1579
|
+
requestOptionsTypeName = optionsTypeName;
|
|
1580
|
+
statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(optionsTypeName), void 0, Generator.requestOptionsTypeNode()));
|
|
1581
|
+
}
|
|
1582
|
+
const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
|
|
1583
|
+
taken.add("req");
|
|
1584
|
+
if (authArgument) taken.add(authArgument.name);
|
|
1585
|
+
let requestControlName = "options";
|
|
1586
|
+
let requestControlSuffix = 2;
|
|
1587
|
+
while (taken.has(requestControlName)) {
|
|
1588
|
+
requestControlName = `options${requestControlSuffix}`;
|
|
1589
|
+
requestControlSuffix++;
|
|
1590
|
+
}
|
|
1591
|
+
const requestControl = { name: requestControlName };
|
|
910
1592
|
if (requestBody.length === 0) requestBody.push({ type: "application/json" });
|
|
1593
|
+
const { responseTypes } = operation;
|
|
1594
|
+
const responseCodes = Object.keys(responseTypes ?? {});
|
|
1595
|
+
if (responseTypes && (responseCodes.length > 1 || !/^2\d\d$/.test(responseCodes[0] ?? ""))) {
|
|
1596
|
+
const responsesName = reserveUnique(`${Base.pathToFnName(uri, method, operationId)}Responses`);
|
|
1597
|
+
statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(responsesName), void 0, Generator.toResponsesTypeNode(responseTypes)));
|
|
1598
|
+
}
|
|
911
1599
|
const shouldAddExtraMethodNameSuffix = requestBody.length > 1;
|
|
912
1600
|
for (const req of requestBody) {
|
|
913
|
-
const statement = factory.createFunctionDeclaration([factory.createModifier(SyntaxKind.ExportKeyword), factory.createModifier(SyntaxKind.AsyncKeyword)], void 0, Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.
|
|
914
|
-
|
|
1601
|
+
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, [
|
|
1602
|
+
...parameters.length > 0 ? Generator.toDeclarationNodes(parameters) : [],
|
|
1603
|
+
...req?.schema ? [Generator.toRequestBodyTypeNode(req.schema)] : [],
|
|
1604
|
+
...authArgument && authTypeReference ? [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(authArgument.name), factory.createToken(SyntaxKind.QuestionToken), authTypeReference)] : [],
|
|
1605
|
+
factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(requestControl.name), factory.createToken(SyntaxKind.QuestionToken), factory.createTypeReferenceNode(factory.createIdentifier(optionsTypeName)))
|
|
1606
|
+
].filter(Boolean), void 0, Generator.bodyBlock(options.baseURL + uri, method, parameters, req, responses[0], adaptor, options.errorMode, authArgument, requestControl));
|
|
1607
|
+
const mergedDescription = [description, summary].filter(Boolean).map((part) => part?.trim()).join(". ");
|
|
915
1608
|
Generator.addComments(statement, [
|
|
916
1609
|
mergedDescription && { comment: mergedDescription },
|
|
917
1610
|
deprecated && { tag: "deprecated" },
|
|
918
|
-
...Generator.generateParamTags(parameters, req)
|
|
1611
|
+
...Generator.generateParamTags(parameters, req),
|
|
1612
|
+
...authArgument ? [{
|
|
1613
|
+
tag: "param",
|
|
1614
|
+
paramName: authArgument.name,
|
|
1615
|
+
type: "AuthOptions",
|
|
1616
|
+
comment: "Optional security credentials, keyed by scheme name"
|
|
1617
|
+
}] : [],
|
|
1618
|
+
{
|
|
1619
|
+
tag: "param",
|
|
1620
|
+
paramName: requestControl.name,
|
|
1621
|
+
type: optionsTypeName,
|
|
1622
|
+
comment: "Optional abort signal, extra headers and timeout"
|
|
1623
|
+
}
|
|
919
1624
|
].filter(Boolean));
|
|
920
1625
|
statements.push(statement);
|
|
921
1626
|
}
|
|
@@ -926,19 +1631,79 @@ var Generator = class Generator {
|
|
|
926
1631
|
static async prettier(code) {
|
|
927
1632
|
return await format(code, { parser: "typescript" });
|
|
928
1633
|
}
|
|
1634
|
+
/**
|
|
1635
|
+
* Splits generated code into `types.ts`, one file per tag, and `index.ts`.
|
|
1636
|
+
* Shared type declarations live in `types.ts`; tag files import them and
|
|
1637
|
+
* export only their functions.
|
|
1638
|
+
*/
|
|
1639
|
+
static async genCodeMulti(schema, initOptions, adaptor) {
|
|
1640
|
+
const genOptions = {
|
|
1641
|
+
baseURL: initOptions.baseURL ?? "",
|
|
1642
|
+
errorMode: initOptions.errorMode === "throw" || initOptions.errorMode === "result" ? initOptions.errorMode : void 0
|
|
1643
|
+
};
|
|
1644
|
+
const isTypeDeclaration = (statement) => isEnumDeclaration(statement) || isTypeAliasDeclaration(statement) || isInterfaceDeclaration(statement);
|
|
1645
|
+
const typeStatements = Generator.schemaToStatemets(schema, adaptor, genOptions).filter(isTypeDeclaration);
|
|
1646
|
+
const typeNames = typeStatements.map((statement) => isEnumDeclaration(statement) || isTypeAliasDeclaration(statement) || isInterfaceDeclaration(statement) ? statement.name.text : void 0).filter((name) => Boolean(name));
|
|
1647
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1648
|
+
for (const [uri, operations] of Object.entries(schema.apis)) for (const operation of operations) {
|
|
1649
|
+
const tag = operation.tags?.[0] ?? "default";
|
|
1650
|
+
const apis = groups.get(tag) ?? {};
|
|
1651
|
+
apis[uri] ??= [];
|
|
1652
|
+
apis[uri].push(operation);
|
|
1653
|
+
groups.set(tag, apis);
|
|
1654
|
+
}
|
|
1655
|
+
const files = {};
|
|
1656
|
+
const used = /* @__PURE__ */ new Set(["index", "types"]);
|
|
1657
|
+
files["types.ts"] = await Generator.prettier(Generator.toCode(typeStatements));
|
|
1658
|
+
const exportLines = ["export * from './types.js';"];
|
|
1659
|
+
for (const [tag, apis] of groups) {
|
|
1660
|
+
const tagStatements = Generator.schemaToStatemets({
|
|
1661
|
+
...schema,
|
|
1662
|
+
apis
|
|
1663
|
+
}, adaptor, genOptions).filter((statement) => !isTypeDeclaration(statement));
|
|
1664
|
+
const nodes = [];
|
|
1665
|
+
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")));
|
|
1666
|
+
nodes.push(...tagStatements);
|
|
1667
|
+
let code = Generator.toCode(nodes);
|
|
1668
|
+
if (initOptions.importClientSource) code = initOptions.importClientSource + "\n\n" + code;
|
|
1669
|
+
const fileName = Generator.uniqueFileName(tag, used);
|
|
1670
|
+
files[`${fileName}.ts`] = await Generator.prettier(code);
|
|
1671
|
+
exportLines.push(`export * from './${fileName}.js';`);
|
|
1672
|
+
}
|
|
1673
|
+
const index = await Generator.prettier(exportLines.join("\n"));
|
|
1674
|
+
files["index.ts"] = index;
|
|
1675
|
+
return {
|
|
1676
|
+
code: index,
|
|
1677
|
+
files
|
|
1678
|
+
};
|
|
1679
|
+
}
|
|
1680
|
+
/** Lower-case file stem that cannot collide with reserved or earlier names. */
|
|
1681
|
+
static uniqueFileName(tag, used) {
|
|
1682
|
+
const base = tag.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "default";
|
|
1683
|
+
let name = base;
|
|
1684
|
+
let suffix = 2;
|
|
1685
|
+
while (used.has(name)) {
|
|
1686
|
+
name = `${base}-${suffix}`;
|
|
1687
|
+
suffix++;
|
|
1688
|
+
}
|
|
1689
|
+
used.add(name);
|
|
1690
|
+
return name;
|
|
1691
|
+
}
|
|
929
1692
|
static async genCode(schema, initOptions, adaptor) {
|
|
930
|
-
const { importClientSource } = initOptions;
|
|
931
|
-
const statements = Generator.schemaToStatemets(schema, adaptor, {
|
|
1693
|
+
const { importClientSource, errorMode } = initOptions;
|
|
1694
|
+
const statements = Generator.schemaToStatemets(schema, adaptor, {
|
|
1695
|
+
baseURL: initOptions.baseURL ?? "",
|
|
1696
|
+
errorMode: errorMode === "throw" || errorMode === "result" ? errorMode : void 0
|
|
1697
|
+
});
|
|
932
1698
|
let code = Generator.toCode(statements);
|
|
933
1699
|
if (importClientSource) code = importClientSource + "\n\n" + code;
|
|
934
1700
|
return await Generator.prettier(code);
|
|
935
1701
|
}
|
|
936
1702
|
};
|
|
937
|
-
|
|
938
|
-
//#region src/core/client/axios.ts
|
|
1703
|
+
// src/core/client/axios.ts
|
|
939
1704
|
/**
|
|
940
1705
|
* Adapter class implementing support for generating code that makes use of the Axios HTTP client library.
|
|
941
|
-
* This
|
|
1706
|
+
* This adapter defines custom behavior and field mappings specific to the Axios client.
|
|
942
1707
|
*/
|
|
943
1708
|
var AxiosAdapter = class extends Adapter {
|
|
944
1709
|
/**
|
|
@@ -962,40 +1727,59 @@ var AxiosAdapter = class extends Adapter {
|
|
|
962
1727
|
*/
|
|
963
1728
|
name = "axios";
|
|
964
1729
|
/**
|
|
965
|
-
*
|
|
966
|
-
*
|
|
967
|
-
* @
|
|
968
|
-
* @param parameters - Array of parameters to include in the request
|
|
969
|
-
* @param requestBody - The request body media type definition
|
|
970
|
-
* @param response - The response media type definition
|
|
971
|
-
* @param adapter - The adapter instance
|
|
972
|
-
* @param shouldUseFormData - Flag to use FormData for the request body
|
|
973
|
-
* @param shouldUseJSONResponse - Unused by AxiosAdapter; present to align with the abstract signature so positional args bind correctly
|
|
974
|
-
* @param isEventStream - Flag indicating a text/event-stream response; when true the raw AxiosResponse is returned without JSON parsing
|
|
975
|
-
* @return - An array of generated TypeScript statements
|
|
1730
|
+
* Method that should generate and return the client-specific configuration statements.
|
|
1731
|
+
*
|
|
1732
|
+
* @returns {Statement[]} An array of TypeScript statements that define the client configuration.
|
|
976
1733
|
*/
|
|
977
|
-
client(uri, method, parameters, requestBody, response, adapter,
|
|
1734
|
+
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, _shouldUseJSONResponse, errorMode, auth, requestControl) {
|
|
978
1735
|
const statements = [];
|
|
979
|
-
|
|
1736
|
+
parameters.filter((p) => !p.in || p.in === "body");
|
|
980
1737
|
const inHeader = parameters.filter((p) => p.in === "header");
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
1738
|
+
const toLiterlExpression = () => {
|
|
1739
|
+
const headerEntries = [];
|
|
1740
|
+
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))])])));
|
|
1741
|
+
if (bodyContentType !== void 0) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Content-Type"), factory.createStringLiteral(bodyContentType)));
|
|
1742
|
+
if (parameters.some((p) => p.in === "cookie") || auth?.injections.some((injection) => injection.location === "cookie")) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Cookie"), cookieHeaderExpression(parameters, auth)));
|
|
1743
|
+
if (auth) headerEntries.push(...authHeaderEntries(auth));
|
|
1744
|
+
const properties = [factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))];
|
|
1745
|
+
if (headerEntries.length > 0 || requestControl) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(withRequestHeaders(headerEntries, requestControl))));
|
|
1746
|
+
if (requestControl) properties.push(factory.createPropertyAssignment(factory.createIdentifier("signal"), optionalAccess(requestControl, "signal")), factory.createPropertyAssignment(factory.createIdentifier("timeout"), optionalAccess(requestControl, "timeout")));
|
|
1747
|
+
let bodyExpr;
|
|
1748
|
+
switch (bodyKind) {
|
|
1749
|
+
case "form-data":
|
|
1750
|
+
bodyExpr = factory.createIdentifier("fd");
|
|
1751
|
+
break;
|
|
1752
|
+
case "urlencoded":
|
|
1753
|
+
bodyExpr = factory.createIdentifier("sp");
|
|
1754
|
+
break;
|
|
1755
|
+
case "json":
|
|
1756
|
+
case "binary": bodyExpr = factory.createIdentifier("req");
|
|
1757
|
+
}
|
|
1758
|
+
if (bodyExpr) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
|
|
1759
|
+
return factory.createObjectLiteralExpression(properties, true);
|
|
1760
|
+
};
|
|
1761
|
+
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()]);
|
|
1762
|
+
if (errorMode !== "result") {
|
|
1763
|
+
statements.push(factory.createReturnStatement(axiosCall));
|
|
1764
|
+
return statements;
|
|
992
1765
|
}
|
|
993
|
-
|
|
1766
|
+
const prop = (name, value) => factory.createPropertyAssignment(factory.createIdentifier(name), value);
|
|
1767
|
+
const resProp = (name) => factory.createPropertyAccessExpression(factory.createIdentifier("res"), factory.createIdentifier(name));
|
|
1768
|
+
const errorProp = (name) => factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(factory.createIdentifier("failure"), factory.createIdentifier("response")), factory.createIdentifier(name));
|
|
1769
|
+
const result = (ok, key, value) => factory.createObjectLiteralExpression([
|
|
1770
|
+
prop("ok", factory.createAsExpression(ok ? factory.createTrue() : factory.createFalse(), factory.createTypeReferenceNode(factory.createIdentifier("const")))),
|
|
1771
|
+
prop("status", ok ? resProp("status") : errorProp("status")),
|
|
1772
|
+
prop(key, value)
|
|
1773
|
+
], true);
|
|
1774
|
+
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([
|
|
1775
|
+
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)),
|
|
1776
|
+
factory.createIfStatement(factory.createPropertyAccessExpression(factory.createIdentifier("failure"), factory.createIdentifier("response")), factory.createBlock([factory.createReturnStatement(result(false, "error", errorProp("data")))], true)),
|
|
1777
|
+
factory.createThrowStatement(factory.createIdentifier("err"))
|
|
1778
|
+
], true)), void 0));
|
|
994
1779
|
return statements;
|
|
995
1780
|
}
|
|
996
1781
|
};
|
|
997
|
-
|
|
998
|
-
//#region src/core/client/fetch.ts
|
|
1782
|
+
// src/core/client/fetch.ts
|
|
999
1783
|
/**
|
|
1000
1784
|
* FetchAdapter is an adapter class that generates client-side fetch requests.
|
|
1001
1785
|
* It handles parameters, headers, and request bodies to construct proper fetch calls.
|
|
@@ -1014,12 +1798,12 @@ var FetchAdapter = class extends Adapter {
|
|
|
1014
1798
|
* @param requestBody - The request body media type definition
|
|
1015
1799
|
* @param response - The response media type definition
|
|
1016
1800
|
* @param adapter - The adapter instance
|
|
1017
|
-
* @param
|
|
1801
|
+
* @param bodyKind - How the body should be encoded (json / form-data / urlencoded / binary / none)
|
|
1802
|
+
* @param bodyContentType - Content-Type header to inject (undefined means "let runtime decide", e.g. multipart boundary)
|
|
1018
1803
|
* @param shouldUseJSONResponse - Flag to use JSON parsing for the response
|
|
1019
|
-
* @param isEventStream - Flag indicating a text/event-stream response; when true the raw Response is returned unparsed
|
|
1020
1804
|
* @return - An array of generated TypeScript statements
|
|
1021
1805
|
*/
|
|
1022
|
-
client(uri, method, parameters, requestBody, response, adapter,
|
|
1806
|
+
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, shouldUseJSONResponse, errorMode, auth, requestControl) {
|
|
1023
1807
|
const statements = [];
|
|
1024
1808
|
const inBody = parameters.filter((p) => !p.in || p.in === "body");
|
|
1025
1809
|
const inHeader = parameters.filter((p) => p.in === "header");
|
|
@@ -1029,18 +1813,67 @@ var FetchAdapter = class extends Adapter {
|
|
|
1029
1813
|
* @returns - The constructed fetch options object
|
|
1030
1814
|
*/
|
|
1031
1815
|
const toLiterlExpression = () => {
|
|
1032
|
-
|
|
1816
|
+
const headerEntries = [];
|
|
1817
|
+
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))])])));
|
|
1818
|
+
if (bodyContentType !== void 0) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Content-Type"), factory.createStringLiteral(bodyContentType)));
|
|
1819
|
+
if (parameters.some((p) => p.in === "cookie") || auth?.injections.some((injection) => injection.location === "cookie")) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Cookie"), cookieHeaderExpression(parameters, auth)));
|
|
1820
|
+
if (auth) headerEntries.push(...authHeaderEntries(auth));
|
|
1821
|
+
const properties = [factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))];
|
|
1822
|
+
if (headerEntries.length > 0 || requestControl) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(withRequestHeaders(headerEntries, requestControl))));
|
|
1823
|
+
if (requestControl) properties.push(factory.createPropertyAssignment(factory.createIdentifier("signal"), fetchSignalExpression(requestControl)));
|
|
1824
|
+
let bodyExpr;
|
|
1825
|
+
switch (bodyKind) {
|
|
1826
|
+
case "form-data":
|
|
1827
|
+
bodyExpr = factory.createIdentifier("fd");
|
|
1828
|
+
break;
|
|
1829
|
+
case "urlencoded":
|
|
1830
|
+
bodyExpr = factory.createIdentifier("sp");
|
|
1831
|
+
break;
|
|
1832
|
+
case "json": {
|
|
1833
|
+
const arg = requestBody ? factory.createIdentifier("req") : factory.createObjectLiteralExpression(inBody.map((b) => factory.createShorthandPropertyAssignment(factory.createIdentifier(b.name))), true);
|
|
1834
|
+
bodyExpr = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), [], [arg]);
|
|
1835
|
+
break;
|
|
1836
|
+
}
|
|
1837
|
+
case "binary": bodyExpr = factory.createIdentifier("req");
|
|
1838
|
+
}
|
|
1839
|
+
if (bodyExpr) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
|
|
1840
|
+
return factory.createObjectLiteralExpression(properties, true);
|
|
1033
1841
|
};
|
|
1034
|
-
|
|
1035
|
-
|
|
1842
|
+
const fetchCall = factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters, "", auth), toLiterlExpression()]);
|
|
1843
|
+
const responseProp = (name) => factory.createPropertyAccessExpression(factory.createIdentifier("response"), factory.createIdentifier(name));
|
|
1844
|
+
const jsonExpression = factory.createAsExpression(factory.createParenthesizedExpression(factory.createAwaitExpression(factory.createCallExpression(responseProp("json"), void 0, []))), response?.schema ? Generator.toTypeNode(response.schema) : factory.createToken(SyntaxKind.UnknownKeyword));
|
|
1845
|
+
const successExpression = shouldUseJSONResponse ? jsonExpression : factory.createIdentifier("response");
|
|
1846
|
+
if (!errorMode) {
|
|
1847
|
+
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));
|
|
1036
1848
|
return statements;
|
|
1037
1849
|
}
|
|
1038
|
-
|
|
1850
|
+
const notOk = factory.createPrefixUnaryExpression(SyntaxKind.ExclamationToken, responseProp("ok"));
|
|
1851
|
+
const responseText = factory.createAwaitExpression(factory.createCallExpression(responseProp("text"), void 0, []));
|
|
1852
|
+
const thenStatements = [];
|
|
1853
|
+
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));
|
|
1854
|
+
else {
|
|
1855
|
+
const result = (ok, key, value) => factory.createObjectLiteralExpression([
|
|
1856
|
+
factory.createPropertyAssignment(factory.createIdentifier("ok"), factory.createAsExpression(ok ? factory.createTrue() : factory.createFalse(), factory.createTypeReferenceNode(factory.createIdentifier("const")))),
|
|
1857
|
+
factory.createPropertyAssignment(factory.createIdentifier("status"), responseProp("status")),
|
|
1858
|
+
factory.createPropertyAssignment(factory.createIdentifier(key), value)
|
|
1859
|
+
], true);
|
|
1860
|
+
thenStatements.push(factory.createIfStatement(notOk, factory.createBlock([factory.createReturnStatement(result(false, "error", responseText))], true)), factory.createReturnStatement(result(true, "data", successExpression)));
|
|
1861
|
+
}
|
|
1862
|
+
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))])));
|
|
1039
1863
|
return statements;
|
|
1040
1864
|
}
|
|
1041
1865
|
};
|
|
1042
|
-
|
|
1043
|
-
|
|
1866
|
+
// src/core/config.ts
|
|
1867
|
+
/**
|
|
1868
|
+
* Strings considered truthy for boolean env vars (verbose/watch/typeCheck).
|
|
1869
|
+
*/
|
|
1870
|
+
const TRUTHY_STRINGS = /* @__PURE__ */ new Set([
|
|
1871
|
+
"true",
|
|
1872
|
+
"1",
|
|
1873
|
+
"yes",
|
|
1874
|
+
"on",
|
|
1875
|
+
"enable"
|
|
1876
|
+
]);
|
|
1044
1877
|
/**
|
|
1045
1878
|
* Environment variable mappings
|
|
1046
1879
|
*/
|
|
@@ -1051,7 +1884,10 @@ const ENV_MAPPINGS = {
|
|
|
1051
1884
|
APICODEGEN_ADAPTOR: "adaptor",
|
|
1052
1885
|
APICODEGEN_VERBOSE: "verbose",
|
|
1053
1886
|
APICODEGEN_WATCH: "watch",
|
|
1054
|
-
APICODEGEN_TYPE_CHECK: "typeCheck"
|
|
1887
|
+
APICODEGEN_TYPE_CHECK: "typeCheck",
|
|
1888
|
+
APICODEGEN_CHECK: "check",
|
|
1889
|
+
APICODEGEN_ERROR_MODE: "errorMode",
|
|
1890
|
+
APICODEGEN_SPLIT_BY: "splitBy"
|
|
1055
1891
|
};
|
|
1056
1892
|
/**
|
|
1057
1893
|
* Load config from environment variables
|
|
@@ -1064,19 +1900,23 @@ function loadFromEnv() {
|
|
|
1064
1900
|
case "verbose":
|
|
1065
1901
|
case "watch":
|
|
1066
1902
|
case "typeCheck":
|
|
1067
|
-
|
|
1903
|
+
case "check":
|
|
1904
|
+
config[configKey] = TRUTHY_STRINGS.has(value.toLowerCase());
|
|
1068
1905
|
break;
|
|
1069
1906
|
case "adaptor":
|
|
1070
|
-
config[configKey] = value;
|
|
1907
|
+
if (Object.values(Adaptors).includes(value)) config[configKey] = value;
|
|
1908
|
+
break;
|
|
1909
|
+
case "errorMode":
|
|
1910
|
+
if (value === "throw" || value === "result") config.errorMode = value;
|
|
1911
|
+
break;
|
|
1912
|
+
case "splitBy":
|
|
1913
|
+
if (value === "tag") config.splitBy = value;
|
|
1071
1914
|
break;
|
|
1072
1915
|
default: config[configKey] = value;
|
|
1073
1916
|
}
|
|
1074
1917
|
}
|
|
1075
1918
|
return config;
|
|
1076
1919
|
}
|
|
1077
|
-
/**
|
|
1078
|
-
* Load config from a file
|
|
1079
|
-
*/
|
|
1080
1920
|
async function loadFromFile(filePath) {
|
|
1081
1921
|
const ext = path.extname(filePath).toLowerCase();
|
|
1082
1922
|
try {
|
|
@@ -1085,17 +1925,16 @@ async function loadFromFile(filePath) {
|
|
|
1085
1925
|
return JSON.parse(content);
|
|
1086
1926
|
}
|
|
1087
1927
|
if (ext === ".js" || ext === ".cjs" || ext === ".mjs") {
|
|
1088
|
-
const mod = await import(filePath);
|
|
1928
|
+
const mod = await import(pathToFileURL(filePath).href);
|
|
1089
1929
|
return mod.default || mod;
|
|
1090
1930
|
}
|
|
1091
|
-
if (ext === ".ts") {
|
|
1931
|
+
if (ext === ".ts" || ext === ".mts" || ext === ".cts") {
|
|
1092
1932
|
const content = await fs.readFile(filePath, "utf-8");
|
|
1093
1933
|
try {
|
|
1094
1934
|
return JSON.parse(content);
|
|
1095
|
-
} catch {
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
}
|
|
1935
|
+
} catch {}
|
|
1936
|
+
const mod = await import(pathToFileURL(filePath).href);
|
|
1937
|
+
return mod.default || mod;
|
|
1099
1938
|
}
|
|
1100
1939
|
const content = await fs.readFile(filePath, "utf-8");
|
|
1101
1940
|
return JSON.parse(content);
|
|
@@ -1111,10 +1950,13 @@ async function findConfigFile(cwd) {
|
|
|
1111
1950
|
"apicodegen.config.json",
|
|
1112
1951
|
"apicodegen.config.js",
|
|
1113
1952
|
"apicodegen.config.mjs",
|
|
1953
|
+
"apicodegen.config.ts",
|
|
1954
|
+
"apicodegen.config.mts",
|
|
1114
1955
|
".apicodegenrc",
|
|
1115
1956
|
".apicodegenrc.json",
|
|
1116
1957
|
".apicodegenrc.js",
|
|
1117
|
-
".apicodegenrc.mjs"
|
|
1958
|
+
".apicodegenrc.mjs",
|
|
1959
|
+
".apicodegenrc.ts"
|
|
1118
1960
|
]) {
|
|
1119
1961
|
const filePath = path.join(cwd, fileName);
|
|
1120
1962
|
if (await fs.pathExists(filePath)) return filePath;
|
|
@@ -1134,11 +1976,40 @@ function mergeConfigs(base, ...sources) {
|
|
|
1134
1976
|
const result = { ...base };
|
|
1135
1977
|
for (const source of sources) {
|
|
1136
1978
|
if (!source) continue;
|
|
1137
|
-
for (const [key, value] of Object.entries(source)) if (value !== void 0) result[key] = value;
|
|
1979
|
+
for (const [key, value] of Object.entries(source)) if (value !== void 0 && value !== null) result[key] = value;
|
|
1138
1980
|
}
|
|
1139
1981
|
return result;
|
|
1140
1982
|
}
|
|
1141
1983
|
/**
|
|
1984
|
+
* Validate field types before the values reach the generator.
|
|
1985
|
+
*/
|
|
1986
|
+
function validateConfigShape(config) {
|
|
1987
|
+
const fail = (key, expected) => {
|
|
1988
|
+
throw new Error(`Invalid config field "${key}": expected ${expected}`);
|
|
1989
|
+
};
|
|
1990
|
+
if (config.spec !== void 0 && typeof config.spec !== "string") fail("spec", "a string");
|
|
1991
|
+
if (config.output !== void 0 && typeof config.output !== "string") fail("output", "a string");
|
|
1992
|
+
for (const key of [
|
|
1993
|
+
"verbose",
|
|
1994
|
+
"watch",
|
|
1995
|
+
"typeCheck",
|
|
1996
|
+
"check"
|
|
1997
|
+
]) if (config[key] !== void 0 && typeof config[key] !== "boolean") fail(key, "a boolean");
|
|
1998
|
+
if (config.adaptor !== void 0 && !Object.values(Adaptors).includes(config.adaptor)) fail("adaptor", Object.values(Adaptors).join(" or "));
|
|
1999
|
+
if (config.errorMode !== void 0 && config.errorMode !== "throw" && config.errorMode !== "result") fail("errorMode", "throw or result");
|
|
2000
|
+
if (config.splitBy !== void 0 && config.splitBy !== "tag") fail("splitBy", "tag");
|
|
2001
|
+
for (const key of [
|
|
2002
|
+
"includeTags",
|
|
2003
|
+
"excludeTags",
|
|
2004
|
+
"includePaths",
|
|
2005
|
+
"excludePaths"
|
|
2006
|
+
]) {
|
|
2007
|
+
const value = config[key];
|
|
2008
|
+
if (value !== void 0 && (!Array.isArray(value) || value.some((item) => typeof item !== "string"))) fail(key, "an array of strings");
|
|
2009
|
+
}
|
|
2010
|
+
if (config.requestOptions !== void 0 && (typeof config.requestOptions !== "object" || config.requestOptions === null || Array.isArray(config.requestOptions))) fail("requestOptions", "an object");
|
|
2011
|
+
}
|
|
2012
|
+
/**
|
|
1142
2013
|
* Validate config has required fields
|
|
1143
2014
|
*/
|
|
1144
2015
|
function validateConfig(config) {
|
|
@@ -1146,9 +2017,10 @@ function validateConfig(config) {
|
|
|
1146
2017
|
return true;
|
|
1147
2018
|
}
|
|
1148
2019
|
/**
|
|
1149
|
-
* Load and resolve config
|
|
2020
|
+
* Load and resolve every config entry. A config file may define a single
|
|
2021
|
+
* object or a `specs` array for multi-spec projects.
|
|
1150
2022
|
*/
|
|
1151
|
-
async function
|
|
2023
|
+
async function loadConfigs(options = {}) {
|
|
1152
2024
|
const cwd = options.cwd || process.cwd();
|
|
1153
2025
|
const cliOptions = options.cliOptions || {};
|
|
1154
2026
|
const envConfig = loadFromEnv();
|
|
@@ -1170,17 +2042,56 @@ async function loadConfig(options = {}) {
|
|
|
1170
2042
|
const pkg = JSON.parse(await fs.readFile(packageJsonPath, "utf-8"));
|
|
1171
2043
|
if (pkg.apicodegen && typeof pkg.apicodegen === "object") inlineConfig = pkg.apicodegen;
|
|
1172
2044
|
} catch {}
|
|
1173
|
-
const
|
|
2045
|
+
const { specs, ...fileOptions } = fileConfig;
|
|
2046
|
+
const entries = Array.isArray(specs) && specs.length > 0 ? specs.map((entry) => mergeConfigs({
|
|
1174
2047
|
spec: "",
|
|
1175
2048
|
output: "./output.ts"
|
|
1176
|
-
},
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
2049
|
+
}, fileOptions, entry)) : [fileOptions];
|
|
2050
|
+
const sharedCliOptions = entries.length === 1 ? cliOptions : Object.fromEntries(Object.entries(cliOptions).filter(([key]) => key !== "spec" && key !== "output"));
|
|
2051
|
+
return entries.map((entry, index) => {
|
|
2052
|
+
const merged = mergeConfigs({
|
|
2053
|
+
spec: "",
|
|
2054
|
+
output: "./output.ts"
|
|
2055
|
+
}, envConfig, inlineConfig, entry, sharedCliOptions);
|
|
2056
|
+
validateConfigShape(merged);
|
|
2057
|
+
validateConfig(merged);
|
|
2058
|
+
const name = options.name || merged.name || merged.baseURL || merged.spec || `api-${index + 1}`;
|
|
2059
|
+
return {
|
|
2060
|
+
...merged,
|
|
2061
|
+
configFilePath,
|
|
2062
|
+
name
|
|
2063
|
+
};
|
|
2064
|
+
});
|
|
2065
|
+
}
|
|
2066
|
+
/**
|
|
2067
|
+
* Load a single config. Throws when the file defines no entries.
|
|
2068
|
+
*/
|
|
2069
|
+
async function loadConfig(options = {}) {
|
|
2070
|
+
const config = (await loadConfigs(options))[0];
|
|
2071
|
+
if (!config) throw new Error("No API configs found");
|
|
2072
|
+
return config;
|
|
2073
|
+
}
|
|
2074
|
+
/**
|
|
2075
|
+
* Create CLI options from config for commander
|
|
2076
|
+
*/
|
|
2077
|
+
function configToCLIOptions(config) {
|
|
2078
|
+
const options = {};
|
|
2079
|
+
if (config.spec) options.spec = config.spec;
|
|
2080
|
+
if (config.output) options.output = config.output;
|
|
2081
|
+
if (config.adaptor) options.adaptor = config.adaptor;
|
|
2082
|
+
if (config.errorMode) options.errorMode = config.errorMode;
|
|
2083
|
+
if (config.splitBy) options.splitBy = config.splitBy;
|
|
2084
|
+
if (config.includeTags) options.includeTags = config.includeTags;
|
|
2085
|
+
if (config.excludeTags) options.excludeTags = config.excludeTags;
|
|
2086
|
+
if (config.includePaths) options.includePaths = config.includePaths;
|
|
2087
|
+
if (config.excludePaths) options.excludePaths = config.excludePaths;
|
|
2088
|
+
if (config.baseURL !== void 0) options.baseURL = config.baseURL;
|
|
2089
|
+
if (config.verbose) options.verbose = config.verbose;
|
|
2090
|
+
if (config.typeCheck) options.typeCheck = config.typeCheck;
|
|
2091
|
+
if (config.watch) options.watch = config.watch;
|
|
2092
|
+
if (config.check) options.check = config.check;
|
|
2093
|
+
if (config.importClientSource) options.importClientSource = config.importClientSource;
|
|
2094
|
+
return options;
|
|
1184
2095
|
}
|
|
1185
2096
|
/**
|
|
1186
2097
|
* Convert resolved config to provider options format
|
|
@@ -1193,78 +2104,208 @@ function toProviderOptions(config) {
|
|
|
1193
2104
|
baseURL: config.baseURL,
|
|
1194
2105
|
importClientSource: config.importClientSource,
|
|
1195
2106
|
verbose: config.verbose,
|
|
1196
|
-
requestOptions: config.requestOptions
|
|
2107
|
+
requestOptions: config.requestOptions,
|
|
2108
|
+
errorMode: config.errorMode,
|
|
2109
|
+
splitBy: config.splitBy,
|
|
2110
|
+
includeTags: config.includeTags,
|
|
2111
|
+
excludeTags: config.excludeTags,
|
|
2112
|
+
includePaths: config.includePaths,
|
|
2113
|
+
excludePaths: config.excludePaths
|
|
1197
2114
|
};
|
|
1198
2115
|
}
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
2116
|
+
// src/openapi/filter.ts
|
|
2117
|
+
function matchesPrefix(path, prefixes) {
|
|
2118
|
+
return !!prefixes?.length && prefixes.some((prefix) => path.startsWith(prefix));
|
|
2119
|
+
}
|
|
2120
|
+
/**
|
|
2121
|
+
* Keep only the operations selected by tag and path filters.
|
|
2122
|
+
*
|
|
2123
|
+
* Paths use prefix matching (`/admin` covers `/admin/users`). Operations with
|
|
2124
|
+
* no tags are kept only when no `includeTags` filter is active.
|
|
2125
|
+
*/
|
|
2126
|
+
function filterApis(apis, filters) {
|
|
2127
|
+
const keepTag = (op) => {
|
|
2128
|
+
const tags = op.tags ?? [];
|
|
2129
|
+
if (filters.includeTags?.length && !tags.some((tag) => filters.includeTags?.includes(tag))) return false;
|
|
2130
|
+
if (filters.excludeTags?.length && tags.some((tag) => filters.excludeTags?.includes(tag))) return false;
|
|
2131
|
+
return true;
|
|
2132
|
+
};
|
|
2133
|
+
const filtered = {};
|
|
2134
|
+
for (const [path, operations] of Object.entries(apis)) {
|
|
2135
|
+
if (filters.includePaths?.length && !matchesPrefix(path, filters.includePaths)) continue;
|
|
2136
|
+
if (matchesPrefix(path, filters.excludePaths)) continue;
|
|
2137
|
+
const kept = operations.filter(keepTag);
|
|
2138
|
+
if (kept.length > 0) filtered[path] = kept;
|
|
2139
|
+
}
|
|
2140
|
+
return filtered;
|
|
2141
|
+
}
|
|
2142
|
+
// src/openapi/read-write.ts
|
|
2143
|
+
function single(schema) {
|
|
2144
|
+
return schema;
|
|
2145
|
+
}
|
|
2146
|
+
/** True when a schema carries the flag anywhere except through a `$ref`. */
|
|
2147
|
+
function containsFlag(schema, flag) {
|
|
2148
|
+
if (!schema) return false;
|
|
2149
|
+
const value = single(schema);
|
|
2150
|
+
if (value[flag]) return true;
|
|
2151
|
+
if (value.properties) {
|
|
2152
|
+
for (const prop of Object.values(value.properties)) if (containsFlag(prop, flag)) return true;
|
|
2153
|
+
}
|
|
2154
|
+
if (schema.type === "array") return containsFlag(schema.items, flag);
|
|
2155
|
+
for (const key of [
|
|
2156
|
+
"allOf",
|
|
2157
|
+
"anyOf",
|
|
2158
|
+
"oneOf"
|
|
2159
|
+
]) if (value[key]?.some((member) => containsFlag(member, flag))) return true;
|
|
2160
|
+
const additional = value.additionalProperties;
|
|
2161
|
+
return !!additional && typeof additional === "object" && containsFlag(additional, flag);
|
|
2162
|
+
}
|
|
2163
|
+
/** The referenced emitted type name, when a schema is only a reference. */
|
|
2164
|
+
function refType(schema) {
|
|
2165
|
+
const value = single(schema);
|
|
2166
|
+
if (value.ref) return Base.upperCamelCase(Base.ref2name(value.ref));
|
|
2167
|
+
if (value.properties || value.oneOf || value.anyOf || value.allOf) return;
|
|
2168
|
+
if (schema.type === "array") return void 0;
|
|
2169
|
+
return typeof value.type === "string" ? Base.upperCamelCase(value.type) : void 0;
|
|
2170
|
+
}
|
|
2171
|
+
function dependsOn(schema, names) {
|
|
2172
|
+
const ref = refType(schema);
|
|
2173
|
+
if (ref && names.has(ref)) return true;
|
|
2174
|
+
const value = single(schema);
|
|
2175
|
+
if (value.properties) {
|
|
2176
|
+
for (const prop of Object.values(value.properties)) if (dependsOn(prop, names)) return true;
|
|
2177
|
+
}
|
|
2178
|
+
if (schema.type === "array") {
|
|
2179
|
+
const items = schema.items;
|
|
2180
|
+
return !!items && dependsOn(items, names);
|
|
2181
|
+
}
|
|
2182
|
+
for (const key of [
|
|
2183
|
+
"allOf",
|
|
2184
|
+
"anyOf",
|
|
2185
|
+
"oneOf"
|
|
2186
|
+
]) if (value[key]?.some((member) => dependsOn(member, names))) return true;
|
|
2187
|
+
const additional = value.additionalProperties;
|
|
2188
|
+
return !!additional && typeof additional === "object" && dependsOn(additional, names);
|
|
2189
|
+
}
|
|
2190
|
+
/**
|
|
2191
|
+
* Pick the schemas that need an Input/Output variant.
|
|
2192
|
+
*
|
|
2193
|
+
* A schema qualifies when it contains the flag directly, or references a
|
|
2194
|
+
* schema that does. The fixed point makes nested references follow.
|
|
2195
|
+
*/
|
|
2196
|
+
function buildVariant(schemas, flag, suffix) {
|
|
2197
|
+
const seeded = /* @__PURE__ */ new Set();
|
|
2198
|
+
const emitted = /* @__PURE__ */ new Map();
|
|
2199
|
+
for (const key of Object.keys(schemas)) {
|
|
2200
|
+
emitted.set(Base.upperCamelCase(key), key);
|
|
2201
|
+
if (containsFlag(schemas[key], flag)) seeded.add(key);
|
|
2202
|
+
}
|
|
2203
|
+
let changed = true;
|
|
2204
|
+
while (changed) {
|
|
2205
|
+
changed = false;
|
|
2206
|
+
const seededNames = new Set([...seeded].map((key) => Base.upperCamelCase(key)));
|
|
2207
|
+
for (const key of Object.keys(schemas)) if (!seeded.has(key) && dependsOn(schemas[key], seededNames)) {
|
|
2208
|
+
seeded.add(key);
|
|
2209
|
+
changed = true;
|
|
2210
|
+
}
|
|
1259
2211
|
}
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
2212
|
+
const names = /* @__PURE__ */ new Map();
|
|
2213
|
+
const keys = /* @__PURE__ */ new Map();
|
|
2214
|
+
const taken = new Set(emitted.keys());
|
|
2215
|
+
for (const key of seeded) {
|
|
2216
|
+
const variantKey = key + suffix;
|
|
2217
|
+
const variantName = Base.upperCamelCase(variantKey);
|
|
2218
|
+
if (taken.has(variantName)) continue;
|
|
2219
|
+
taken.add(variantName);
|
|
2220
|
+
names.set(Base.upperCamelCase(key), variantName);
|
|
2221
|
+
keys.set(key, variantKey);
|
|
2222
|
+
}
|
|
2223
|
+
return {
|
|
2224
|
+
names,
|
|
2225
|
+
keys
|
|
2226
|
+
};
|
|
2227
|
+
}
|
|
2228
|
+
/** Clone a schema with flagged properties removed and variant refs remapped. */
|
|
2229
|
+
function transform(schema, flag, names) {
|
|
2230
|
+
const ref = refType(schema);
|
|
2231
|
+
if (ref && names.has(ref)) {
|
|
2232
|
+
const { ref: _ref, ...rest } = single(schema);
|
|
2233
|
+
return {
|
|
2234
|
+
...rest,
|
|
2235
|
+
type: names.get(ref)
|
|
2236
|
+
};
|
|
2237
|
+
}
|
|
2238
|
+
if (schema.type === "array") {
|
|
2239
|
+
const array = schema;
|
|
2240
|
+
return {
|
|
2241
|
+
...array,
|
|
2242
|
+
items: array.items ? transform(array.items, flag, names) : void 0
|
|
2243
|
+
};
|
|
2244
|
+
}
|
|
2245
|
+
const value = single(schema);
|
|
2246
|
+
const next = { ...value };
|
|
2247
|
+
if (value.properties) {
|
|
2248
|
+
const properties = {};
|
|
2249
|
+
for (const [key, prop] of Object.entries(value.properties)) {
|
|
2250
|
+
if (single(prop)[flag]) continue;
|
|
2251
|
+
properties[key] = transform(prop, flag, names);
|
|
2252
|
+
}
|
|
2253
|
+
next.properties = properties;
|
|
2254
|
+
if (Array.isArray(value.required)) next.required = value.required.filter((key) => key in properties);
|
|
2255
|
+
}
|
|
2256
|
+
for (const key of [
|
|
2257
|
+
"allOf",
|
|
2258
|
+
"anyOf",
|
|
2259
|
+
"oneOf"
|
|
2260
|
+
]) {
|
|
2261
|
+
const members = value[key];
|
|
2262
|
+
if (members) next[key] = members.map((m) => transform(m, flag, names));
|
|
2263
|
+
}
|
|
2264
|
+
const additional = value.additionalProperties;
|
|
2265
|
+
if (additional && typeof additional === "object") next.additionalProperties = transform(additional, flag, names);
|
|
2266
|
+
return next;
|
|
2267
|
+
}
|
|
2268
|
+
function transformMedia(media, flag, names) {
|
|
2269
|
+
return media.map((entry) => entry.schema ? {
|
|
2270
|
+
...entry,
|
|
2271
|
+
schema: transform(entry.schema, flag, names)
|
|
2272
|
+
} : entry);
|
|
2273
|
+
}
|
|
2274
|
+
function transformOperation(operation, input, output) {
|
|
2275
|
+
return {
|
|
2276
|
+
...operation,
|
|
2277
|
+
...operation.requestBody ? { requestBody: transformMedia(operation.requestBody, "readOnly", input) } : {},
|
|
2278
|
+
...operation.responses ? { responses: transformMedia(operation.responses, "writeOnly", output) } : {},
|
|
2279
|
+
...operation.responseTypes ? { responseTypes: Object.fromEntries(Object.entries(operation.responseTypes).map(([code, media]) => [code, transformMedia(media, "writeOnly", output)])) } : {}
|
|
2280
|
+
};
|
|
2281
|
+
}
|
|
1263
2282
|
/**
|
|
1264
|
-
*
|
|
1265
|
-
*
|
|
2283
|
+
* Add `XxxInput` / `XxxOutput` schema aliases and point operations at them:
|
|
2284
|
+
* requests drop `readOnly` properties, responses drop `writeOnly` ones.
|
|
2285
|
+
*
|
|
2286
|
+
* Existing type names are untouched; variants are only created when the name
|
|
2287
|
+
* is free. With no `readOnly` / `writeOnly` in the document this is a no-op.
|
|
1266
2288
|
*/
|
|
1267
|
-
|
|
2289
|
+
function splitReadWrite(parsed) {
|
|
2290
|
+
const input = buildVariant(parsed.schemas, "readOnly", "Input");
|
|
2291
|
+
const output = buildVariant(parsed.schemas, "writeOnly", "Output");
|
|
2292
|
+
if (input.keys.size === 0 && output.keys.size === 0) return parsed;
|
|
2293
|
+
const schemas = { ...parsed.schemas };
|
|
2294
|
+
for (const [key, variantKey] of input.keys) schemas[variantKey] = transform(parsed.schemas[key], "readOnly", input.names);
|
|
2295
|
+
for (const [key, variantKey] of output.keys) schemas[variantKey] = transform(parsed.schemas[key], "writeOnly", output.names);
|
|
2296
|
+
const apis = Object.fromEntries(Object.entries(parsed.apis).map(([path, operations]) => [path, operations.map((operation) => transformOperation(operation, input.names, output.names))]));
|
|
2297
|
+
return {
|
|
2298
|
+
...parsed,
|
|
2299
|
+
schemas,
|
|
2300
|
+
apis
|
|
2301
|
+
};
|
|
2302
|
+
}
|
|
2303
|
+
// src/openapi/V2.ts
|
|
2304
|
+
var V2 = class {
|
|
2305
|
+
doc;
|
|
2306
|
+
constructor(doc) {
|
|
2307
|
+
this.doc = doc;
|
|
2308
|
+
}
|
|
1268
2309
|
/**
|
|
1269
2310
|
* Resolves a path $ref to the actual path object.
|
|
1270
2311
|
*/
|
|
@@ -1276,37 +2317,295 @@ var VersionedProvider = class {
|
|
|
1276
2317
|
* Is array schema.
|
|
1277
2318
|
*/
|
|
1278
2319
|
isOpenAPIArraySchema(schema) {
|
|
1279
|
-
return typeof schema === "object" && schema
|
|
2320
|
+
return typeof schema === "object" && schema.type === "array";
|
|
1280
2321
|
}
|
|
1281
2322
|
/**
|
|
1282
|
-
* OpenAPI schema to base schema.
|
|
1283
|
-
* (V3_1 throws on missing ref; V3 returns `{ type: 'unknown' }`).
|
|
2323
|
+
* OpenAPI schema to base schema.
|
|
1284
2324
|
*/
|
|
1285
2325
|
getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
|
|
1286
2326
|
let refName = "";
|
|
1287
2327
|
if (Base.isRef(schema)) {
|
|
1288
|
-
refName =
|
|
2328
|
+
refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
|
|
1289
2329
|
if (reserveRef) return { type: upLevelSchemaKey + refName };
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
schema = resolvedSchema;
|
|
2330
|
+
if (!this.doc.definitions) this.doc.definitions = {};
|
|
2331
|
+
schema = this.doc.definitions[Base.ref2name(schema.$ref, this.doc)];
|
|
1293
2332
|
}
|
|
1294
2333
|
return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
|
|
1295
2334
|
}
|
|
1296
2335
|
/**
|
|
1297
|
-
*
|
|
1298
|
-
* V3 uses `capitalize`; V3_1 uses `upperCamelCase` (preserved for compat).
|
|
2336
|
+
* Transform all OpenAPI schema to Base Schema
|
|
1299
2337
|
*/
|
|
1300
|
-
|
|
1301
|
-
|
|
2338
|
+
toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
|
|
2339
|
+
if (!schema) return { type: "unknown" };
|
|
2340
|
+
if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
|
|
2341
|
+
if (this.isOpenAPIArraySchema(schema)) {
|
|
2342
|
+
const { type, description, items, required } = schema;
|
|
2343
|
+
return {
|
|
2344
|
+
type,
|
|
2345
|
+
required: !!required,
|
|
2346
|
+
description,
|
|
2347
|
+
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
2348
|
+
};
|
|
2349
|
+
} else {
|
|
2350
|
+
const { required = [], allOf, anyOf, description, discriminator, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
2351
|
+
let { type } = schema;
|
|
2352
|
+
if (enum_ && type !== "boolean") {
|
|
2353
|
+
const enumObject = {
|
|
2354
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
|
|
2355
|
+
enum: [...new Set(enum_)]
|
|
2356
|
+
};
|
|
2357
|
+
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
2358
|
+
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
2359
|
+
return {
|
|
2360
|
+
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
2361
|
+
required,
|
|
2362
|
+
description
|
|
2363
|
+
};
|
|
2364
|
+
}
|
|
2365
|
+
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
2366
|
+
return {
|
|
2367
|
+
type,
|
|
2368
|
+
required,
|
|
2369
|
+
description,
|
|
2370
|
+
discriminator: discriminator ? { propertyName: discriminator } : void 0,
|
|
2371
|
+
enum: enum_,
|
|
2372
|
+
format,
|
|
2373
|
+
readOnly: schema.readOnly,
|
|
2374
|
+
writeOnly: schema.writeOnly,
|
|
2375
|
+
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
2376
|
+
...s,
|
|
2377
|
+
ref: s.$ref,
|
|
2378
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2379
|
+
} : this.toBaseSchema(s, enums)),
|
|
2380
|
+
anyOf: anyOf?.map((s) => Base.isRef(s) ? {
|
|
2381
|
+
...s,
|
|
2382
|
+
ref: s.$ref,
|
|
2383
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2384
|
+
} : this.toBaseSchema(s, enums)),
|
|
2385
|
+
oneOf: oneOf?.map((s) => Base.isRef(s) ? {
|
|
2386
|
+
...s,
|
|
2387
|
+
ref: s.$ref,
|
|
2388
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2389
|
+
} : this.toBaseSchema(s, enums)),
|
|
2390
|
+
properties: Object.keys(properties).reduce((acc, p) => {
|
|
2391
|
+
const propSchema = properties[p];
|
|
2392
|
+
return {
|
|
2393
|
+
...acc,
|
|
2394
|
+
[p]: Base.isRef(propSchema) ? { type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)) } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
|
|
2395
|
+
};
|
|
2396
|
+
}, {})
|
|
2397
|
+
};
|
|
2398
|
+
}
|
|
1302
2399
|
}
|
|
1303
2400
|
/**
|
|
1304
|
-
* OpenAPI parameter to base parameter.
|
|
1305
|
-
|
|
2401
|
+
* OpenAPI parameter to base parameter.
|
|
2402
|
+
*/
|
|
2403
|
+
getParameterByRef(parameter, enums = [], upLevelSchemaKey = "") {
|
|
2404
|
+
if (Base.isRef(parameter)) {
|
|
2405
|
+
const refName = Base.ref2name(parameter.$ref, this.doc);
|
|
2406
|
+
const resolved = this.doc.parameters?.[refName];
|
|
2407
|
+
if (!resolved) throw new Error(`Parameter reference not found: ${parameter.$ref}`);
|
|
2408
|
+
parameter = resolved;
|
|
2409
|
+
}
|
|
2410
|
+
const p = parameter;
|
|
2411
|
+
const collectionFormat = p.collectionFormat;
|
|
2412
|
+
const style = collectionFormat === "ssv" ? "spaceDelimited" : collectionFormat === "pipes" ? "pipeDelimited" : "form";
|
|
2413
|
+
const explode = collectionFormat === "multi";
|
|
2414
|
+
const { name, required, description, type, items, enum: enum_, properties, schema } = p;
|
|
2415
|
+
if (enum_) {
|
|
2416
|
+
const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
|
|
2417
|
+
const enumSchema = {
|
|
2418
|
+
name: type,
|
|
2419
|
+
enum: [...new Set(enum_)]
|
|
2420
|
+
};
|
|
2421
|
+
const sameEnum = Base.findSameSchema(enumSchema, enums);
|
|
2422
|
+
if (!sameEnum && Base.isValidEnumType({
|
|
2423
|
+
type,
|
|
2424
|
+
enum: enum_
|
|
2425
|
+
})) enums.push(enumSchema);
|
|
2426
|
+
return {
|
|
2427
|
+
name,
|
|
2428
|
+
required,
|
|
2429
|
+
description,
|
|
2430
|
+
in: p.in,
|
|
2431
|
+
style,
|
|
2432
|
+
explode,
|
|
2433
|
+
schema: { type: sameEnum?.name ?? type }
|
|
2434
|
+
};
|
|
2435
|
+
}
|
|
2436
|
+
if (items) return {
|
|
2437
|
+
name,
|
|
2438
|
+
required,
|
|
2439
|
+
description,
|
|
2440
|
+
in: p.in,
|
|
2441
|
+
style,
|
|
2442
|
+
explode,
|
|
2443
|
+
schema: {
|
|
2444
|
+
type,
|
|
2445
|
+
items
|
|
2446
|
+
}
|
|
2447
|
+
};
|
|
2448
|
+
if (schema && Base.isRef(schema)) return {
|
|
2449
|
+
name,
|
|
2450
|
+
required,
|
|
2451
|
+
description,
|
|
2452
|
+
in: p.in,
|
|
2453
|
+
style,
|
|
2454
|
+
explode,
|
|
2455
|
+
schema: { type: Base.capitalize(Base.ref2name(schema.$ref)) }
|
|
2456
|
+
};
|
|
2457
|
+
return {
|
|
2458
|
+
name,
|
|
2459
|
+
required,
|
|
2460
|
+
description,
|
|
2461
|
+
in: p.in,
|
|
2462
|
+
style,
|
|
2463
|
+
explode,
|
|
2464
|
+
schema: {
|
|
2465
|
+
type,
|
|
2466
|
+
properties
|
|
2467
|
+
}
|
|
2468
|
+
};
|
|
2469
|
+
}
|
|
2470
|
+
/**
|
|
2471
|
+
* OpenAPI schema to base response
|
|
2472
|
+
*/
|
|
2473
|
+
getResponseByRef(schema, enums = []) {
|
|
2474
|
+
if (Base.isRef(schema)) schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
|
|
2475
|
+
const { schema: responseSchema } = schema;
|
|
2476
|
+
return [{
|
|
2477
|
+
type: "application/json",
|
|
2478
|
+
schema: responseSchema && this.getSchemaByRef(responseSchema, true, enums)
|
|
2479
|
+
}];
|
|
2480
|
+
}
|
|
2481
|
+
init() {
|
|
2482
|
+
const { definitions = {}, responses = {}, paths = {}, security = [], securityDefinitions = {} } = this.doc;
|
|
2483
|
+
const enums = [];
|
|
2484
|
+
const definitions_ = Object.keys(definitions).reduce((acc, key) => {
|
|
2485
|
+
const schema = definitions[key];
|
|
2486
|
+
return {
|
|
2487
|
+
...acc,
|
|
2488
|
+
[key]: this.getSchemaByRef(schema, false, enums, key)
|
|
2489
|
+
};
|
|
2490
|
+
}, {});
|
|
2491
|
+
const responses_ = Object.keys(responses).reduce((acc, key) => {
|
|
2492
|
+
const response = responses[key];
|
|
2493
|
+
return {
|
|
2494
|
+
...acc,
|
|
2495
|
+
[key]: this.getResponseByRef(response, enums)
|
|
2496
|
+
};
|
|
2497
|
+
}, {});
|
|
2498
|
+
const apis = Object.keys(paths).reduce((acc, path) => {
|
|
2499
|
+
let pathObject = paths[path] ?? {};
|
|
2500
|
+
if (pathObject.$ref) {
|
|
2501
|
+
const resolved = this.resolvePathRef(pathObject.$ref);
|
|
2502
|
+
if (resolved) pathObject = resolved;
|
|
2503
|
+
}
|
|
2504
|
+
const { parameters = [] } = pathObject;
|
|
2505
|
+
const methodApis = [];
|
|
2506
|
+
Object.values(HttpMethods).forEach((method) => {
|
|
2507
|
+
const methodObject = pathObject[method];
|
|
2508
|
+
if (methodObject) {
|
|
2509
|
+
const { deprecated, operationId, summary: summary_, description: description_, responses = {} } = methodObject;
|
|
2510
|
+
const { parameters: parameters_ = [] } = methodObject;
|
|
2511
|
+
const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
|
|
2512
|
+
const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
|
|
2513
|
+
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
2514
|
+
const inBody = baseParameters.filter((p) => p.in === "body" || p.in === "formData");
|
|
2515
|
+
const notInBody = baseParameters.filter((p) => p.in !== "body" && p.in !== "formData");
|
|
2516
|
+
const httpCodes = Object.keys(responses).filter((code) => code in responses);
|
|
2517
|
+
const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
|
|
2518
|
+
const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
|
|
2519
|
+
const inBodyOnlyHasBody = inBody && inBody.length === 1 && inBody[0].in === "body" && inBody[0].name === "body";
|
|
2520
|
+
methodApis.push({
|
|
2521
|
+
method,
|
|
2522
|
+
operationId,
|
|
2523
|
+
summary: summary_,
|
|
2524
|
+
deprecated,
|
|
2525
|
+
description: description_,
|
|
2526
|
+
parameters: uniqueParameterName.map((name) => notInBody.find((p) => p.name === name)).filter(Boolean),
|
|
2527
|
+
responses: responseTypes[successCode] ?? [],
|
|
2528
|
+
responseTypes,
|
|
2529
|
+
tags: methodObject.tags,
|
|
2530
|
+
security: methodObject.security ?? security,
|
|
2531
|
+
requestBody: inBody.length > 0 ? inBodyOnlyHasBody ? [{
|
|
2532
|
+
type: "application/json",
|
|
2533
|
+
schema: inBody[0].schema
|
|
2534
|
+
}] : [{
|
|
2535
|
+
type: "application/json",
|
|
2536
|
+
schema: {
|
|
2537
|
+
type: "object",
|
|
2538
|
+
properties: inBody.reduce((a, p) => {
|
|
2539
|
+
return {
|
|
2540
|
+
...a,
|
|
2541
|
+
[p.name]: {
|
|
2542
|
+
type: p.schema?.type ?? "unknown",
|
|
2543
|
+
required: p.schema?.required,
|
|
2544
|
+
items: p.schema?.items,
|
|
2545
|
+
description: p.schema?.description
|
|
2546
|
+
}
|
|
2547
|
+
};
|
|
2548
|
+
}, {})
|
|
2549
|
+
}
|
|
2550
|
+
}] : void 0
|
|
2551
|
+
});
|
|
2552
|
+
}
|
|
2553
|
+
});
|
|
2554
|
+
return {
|
|
2555
|
+
...acc,
|
|
2556
|
+
[path]: methodApis
|
|
2557
|
+
};
|
|
2558
|
+
}, {});
|
|
2559
|
+
return {
|
|
2560
|
+
enums: Base.uniqueEnums(enums),
|
|
2561
|
+
schemas: definitions_,
|
|
2562
|
+
responses: responses_,
|
|
2563
|
+
parameters: {},
|
|
2564
|
+
requestBodies: {},
|
|
2565
|
+
securitySchemes: securityDefinitions,
|
|
2566
|
+
apis
|
|
2567
|
+
};
|
|
2568
|
+
}
|
|
2569
|
+
};
|
|
2570
|
+
// src/openapi/V3.ts
|
|
2571
|
+
var V3 = class {
|
|
2572
|
+
doc;
|
|
2573
|
+
constructor(doc) {
|
|
2574
|
+
this.doc = doc;
|
|
2575
|
+
}
|
|
2576
|
+
/**
|
|
2577
|
+
* Resolves a path $ref to the actual path object.
|
|
2578
|
+
*/
|
|
2579
|
+
resolvePathRef($ref) {
|
|
2580
|
+
const refName = Base.ref2name($ref, this.doc);
|
|
2581
|
+
return this.doc.paths?.[refName];
|
|
2582
|
+
}
|
|
2583
|
+
/**
|
|
2584
|
+
* Is array schema.
|
|
2585
|
+
*/
|
|
2586
|
+
isOpenAPIArraySchema(schema) {
|
|
2587
|
+
return typeof schema === "object" && schema.type === "array";
|
|
2588
|
+
}
|
|
2589
|
+
/**
|
|
2590
|
+
* OpenAPI schema to base schema.
|
|
2591
|
+
*/
|
|
2592
|
+
getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
|
|
2593
|
+
let refName = "";
|
|
2594
|
+
if (Base.isRef(schema)) {
|
|
2595
|
+
refName = Base.capitalize(Base.ref2name(schema.$ref));
|
|
2596
|
+
if (reserveRef) return { type: upLevelSchemaKey + refName };
|
|
2597
|
+
const resolvedSchema = this.doc.components?.schemas?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2598
|
+
if (!resolvedSchema) return { type: "unknown" };
|
|
2599
|
+
schema = resolvedSchema;
|
|
2600
|
+
}
|
|
2601
|
+
return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
|
|
2602
|
+
}
|
|
2603
|
+
/**
|
|
2604
|
+
* OpenAPI parameter to base parameter.
|
|
1306
2605
|
*/
|
|
1307
2606
|
getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
|
|
1308
2607
|
if (Base.isRef(schema)) {
|
|
1309
|
-
const resolvedSchema = this.
|
|
2608
|
+
const resolvedSchema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1310
2609
|
if (!resolvedSchema) return {
|
|
1311
2610
|
name: "unknown",
|
|
1312
2611
|
in: "query"
|
|
@@ -1328,7 +2627,9 @@ var VersionedProvider = class {
|
|
|
1328
2627
|
description,
|
|
1329
2628
|
deprecated,
|
|
1330
2629
|
in: schema.in,
|
|
1331
|
-
schema: { type: sameEnum?.name ?? type }
|
|
2630
|
+
schema: { type: sameEnum?.name ?? type },
|
|
2631
|
+
style: schema.style,
|
|
2632
|
+
explode: schema.explode
|
|
1332
2633
|
};
|
|
1333
2634
|
}
|
|
1334
2635
|
return {
|
|
@@ -1337,38 +2638,39 @@ var VersionedProvider = class {
|
|
|
1337
2638
|
description,
|
|
1338
2639
|
deprecated,
|
|
1339
2640
|
in: schema.in,
|
|
1340
|
-
|
|
2641
|
+
style: schema.style,
|
|
2642
|
+
explode: schema.explode,
|
|
2643
|
+
schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
|
|
1341
2644
|
};
|
|
1342
2645
|
}
|
|
1343
2646
|
/**
|
|
1344
|
-
* OpenAPI schema to base response
|
|
1345
|
-
* lacks the `content` wrapper).
|
|
2647
|
+
* OpenAPI schema to base response
|
|
1346
2648
|
*/
|
|
1347
|
-
getResponseByRef(schema) {
|
|
2649
|
+
getResponseByRef(schema, enums = []) {
|
|
1348
2650
|
if (Base.isRef(schema)) {
|
|
1349
|
-
const resolvedSchema = this.
|
|
2651
|
+
const resolvedSchema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1350
2652
|
if (!resolvedSchema) return [];
|
|
1351
2653
|
schema = resolvedSchema;
|
|
1352
2654
|
}
|
|
1353
2655
|
const { content = {} } = schema;
|
|
1354
2656
|
return Object.keys(content).map((c) => ({
|
|
1355
2657
|
type: c,
|
|
1356
|
-
schema: content[c].schema
|
|
2658
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
|
|
1357
2659
|
}));
|
|
1358
2660
|
}
|
|
1359
2661
|
/**
|
|
1360
|
-
* OpenAPI schema to requestBody.
|
|
2662
|
+
* OpenAPI schema to requestBody.
|
|
1361
2663
|
*/
|
|
1362
2664
|
getRequestBodyByRef(schema, enums = []) {
|
|
1363
2665
|
if (Base.isRef(schema)) {
|
|
1364
|
-
const resolvedSchema = this.
|
|
2666
|
+
const resolvedSchema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1365
2667
|
if (!resolvedSchema) return [];
|
|
1366
2668
|
schema = resolvedSchema;
|
|
1367
2669
|
}
|
|
1368
2670
|
const { content = {} } = schema;
|
|
1369
2671
|
return Object.keys(content).map((c) => ({
|
|
1370
2672
|
type: c,
|
|
1371
|
-
schema: content[c].schema
|
|
2673
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, false, enums)
|
|
1372
2674
|
}));
|
|
1373
2675
|
}
|
|
1374
2676
|
/**
|
|
@@ -1378,99 +2680,100 @@ var VersionedProvider = class {
|
|
|
1378
2680
|
if (!schema) return { type: "unknown" };
|
|
1379
2681
|
if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
|
|
1380
2682
|
if (this.isOpenAPIArraySchema(schema)) {
|
|
1381
|
-
const { type, description, items, required } = schema;
|
|
1382
|
-
const itemsSchema = items ? this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey) : { type: "unknown" };
|
|
2683
|
+
const { type, description, items, required, nullable } = schema;
|
|
1383
2684
|
return {
|
|
1384
2685
|
type,
|
|
2686
|
+
nullable,
|
|
1385
2687
|
required: !!required,
|
|
1386
2688
|
description,
|
|
1387
|
-
items:
|
|
2689
|
+
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
1388
2690
|
};
|
|
1389
|
-
}
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
return {
|
|
1400
|
-
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
1401
|
-
required,
|
|
1402
|
-
description,
|
|
1403
|
-
deprecated
|
|
1404
|
-
};
|
|
1405
|
-
}
|
|
1406
|
-
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
1407
|
-
return {
|
|
1408
|
-
type,
|
|
1409
|
-
required,
|
|
1410
|
-
description,
|
|
1411
|
-
deprecated,
|
|
1412
|
-
enum: enum_,
|
|
1413
|
-
format,
|
|
1414
|
-
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
1415
|
-
...s,
|
|
1416
|
-
ref: s.$ref,
|
|
1417
|
-
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1418
|
-
} : this.toBaseSchema(s, enums)),
|
|
1419
|
-
anyOf: anyOf?.map((s) => Base.isRef(s) ? {
|
|
1420
|
-
...s,
|
|
1421
|
-
ref: s.$ref,
|
|
1422
|
-
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1423
|
-
} : this.toBaseSchema(s, enums)),
|
|
1424
|
-
oneOf: oneOf?.map((s) => Base.isRef(s) ? {
|
|
1425
|
-
...s,
|
|
1426
|
-
ref: s.$ref,
|
|
1427
|
-
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1428
|
-
} : this.toBaseSchema(s, enums)),
|
|
1429
|
-
properties: Object.keys(properties).reduce((acc, p) => {
|
|
1430
|
-
const propSchema = properties[p];
|
|
2691
|
+
} else {
|
|
2692
|
+
const { required = [], allOf, anyOf, description, deprecated, discriminator, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
2693
|
+
let { type } = schema;
|
|
2694
|
+
if (enum_ && type !== "boolean") {
|
|
2695
|
+
const enumObject = {
|
|
2696
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
|
|
2697
|
+
enum: [...new Set(enum_)]
|
|
2698
|
+
};
|
|
2699
|
+
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
2700
|
+
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
1431
2701
|
return {
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
2702
|
+
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
2703
|
+
nullable: schema.nullable,
|
|
2704
|
+
required,
|
|
2705
|
+
description,
|
|
2706
|
+
deprecated
|
|
1437
2707
|
};
|
|
1438
|
-
}
|
|
1439
|
-
|
|
2708
|
+
}
|
|
2709
|
+
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
2710
|
+
return {
|
|
2711
|
+
type,
|
|
2712
|
+
nullable: schema.nullable,
|
|
2713
|
+
additionalProperties: schema.additionalProperties && typeof schema.additionalProperties === "object" ? this.toBaseSchema(schema.additionalProperties, enums) : schema.additionalProperties,
|
|
2714
|
+
required,
|
|
2715
|
+
description,
|
|
2716
|
+
deprecated,
|
|
2717
|
+
discriminator,
|
|
2718
|
+
enum: enum_,
|
|
2719
|
+
format,
|
|
2720
|
+
readOnly: schema.readOnly,
|
|
2721
|
+
writeOnly: schema.writeOnly,
|
|
2722
|
+
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
2723
|
+
...s,
|
|
2724
|
+
ref: s.$ref,
|
|
2725
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2726
|
+
} : this.toBaseSchema(s, enums)),
|
|
2727
|
+
anyOf: anyOf?.map((s) => Base.isRef(s) ? {
|
|
2728
|
+
...s,
|
|
2729
|
+
ref: s.$ref,
|
|
2730
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2731
|
+
} : this.toBaseSchema(s, enums)),
|
|
2732
|
+
oneOf: oneOf?.map((s) => Base.isRef(s) ? {
|
|
2733
|
+
...s,
|
|
2734
|
+
ref: s.$ref,
|
|
2735
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2736
|
+
} : this.toBaseSchema(s, enums)),
|
|
2737
|
+
properties: Object.keys(properties).reduce((acc, p) => {
|
|
2738
|
+
const propSchema = properties[p];
|
|
2739
|
+
return {
|
|
2740
|
+
...acc,
|
|
2741
|
+
[p]: Base.isRef(propSchema) ? {
|
|
2742
|
+
type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)),
|
|
2743
|
+
isRef: true
|
|
2744
|
+
} : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
|
|
2745
|
+
};
|
|
2746
|
+
}, {})
|
|
2747
|
+
};
|
|
2748
|
+
}
|
|
1440
2749
|
}
|
|
1441
|
-
/**
|
|
1442
|
-
* Run the parsing pipeline and return a ProviderInitResult.
|
|
1443
|
-
*/
|
|
1444
2750
|
init() {
|
|
1445
|
-
const { paths = {} } = this.doc;
|
|
2751
|
+
const { components = {}, paths = {}, security = [] } = this.doc;
|
|
1446
2752
|
const enums = [];
|
|
1447
|
-
const
|
|
1448
|
-
const
|
|
1449
|
-
|
|
1450
|
-
const requestBodyContainer = this.getRequestBodyContainer() ?? {};
|
|
1451
|
-
const schemas_ = Object.keys(schemaContainer).reduce((acc, key) => {
|
|
1452
|
-
const schema = schemaContainer[key];
|
|
2753
|
+
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {}, securitySchemes = {} } = components;
|
|
2754
|
+
const schemas_ = Object.keys(schemas).reduce((acc, key) => {
|
|
2755
|
+
const schema = schemas[key];
|
|
1453
2756
|
return {
|
|
1454
2757
|
...acc,
|
|
1455
2758
|
[key]: this.getSchemaByRef(schema, false, enums, key)
|
|
1456
2759
|
};
|
|
1457
2760
|
}, {});
|
|
1458
|
-
const parameters_ = Object.keys(
|
|
1459
|
-
const parameter =
|
|
2761
|
+
const parameters_ = Object.keys(parameters).reduce((acc, key) => {
|
|
2762
|
+
const parameter = parameters[key];
|
|
1460
2763
|
return {
|
|
1461
2764
|
...acc,
|
|
1462
2765
|
[key]: this.getParameterByRef(parameter, enums, key)
|
|
1463
2766
|
};
|
|
1464
2767
|
}, {});
|
|
1465
|
-
const responses_ = Object.keys(
|
|
1466
|
-
const response =
|
|
2768
|
+
const responses_ = Object.keys(responses).reduce((acc, key) => {
|
|
2769
|
+
const response = responses[key];
|
|
1467
2770
|
return {
|
|
1468
2771
|
...acc,
|
|
1469
|
-
[key]: this.getResponseByRef(response)
|
|
2772
|
+
[key]: this.getResponseByRef(response, enums)
|
|
1470
2773
|
};
|
|
1471
2774
|
}, {});
|
|
1472
|
-
const requestBodies_ = Object.keys(
|
|
1473
|
-
const requestBody =
|
|
2775
|
+
const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
|
|
2776
|
+
const requestBody = requestBodies[key];
|
|
1474
2777
|
return {
|
|
1475
2778
|
...acc,
|
|
1476
2779
|
[key]: this.getRequestBodyByRef(requestBody, enums)
|
|
@@ -1487,29 +2790,28 @@ var VersionedProvider = class {
|
|
|
1487
2790
|
Object.values(HttpMethods).forEach((method) => {
|
|
1488
2791
|
const methodObject = pathObject[method];
|
|
1489
2792
|
if (methodObject) {
|
|
1490
|
-
const { deprecated, operationId, responses, summary: summary_, description: description_, requestBody = { content: {} } } = methodObject;
|
|
1491
|
-
const responsesClone = responses ? { ...responses } : {};
|
|
2793
|
+
const { deprecated, operationId, responses = {}, summary: summary_, description: description_, requestBody = { content: {} } } = methodObject;
|
|
1492
2794
|
const { parameters: parameters_ = [] } = methodObject;
|
|
1493
2795
|
const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
|
|
1494
2796
|
const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
|
|
1495
2797
|
const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
|
|
1496
|
-
if (Object.keys(
|
|
1497
|
-
const httpCodes = Object.keys(
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
}
|
|
2798
|
+
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
2799
|
+
const httpCodes = Object.keys(responses).filter((code) => code in responses);
|
|
2800
|
+
const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
|
|
2801
|
+
const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
|
|
2802
|
+
methodApis.push({
|
|
2803
|
+
method,
|
|
2804
|
+
operationId,
|
|
2805
|
+
summary: summary_ ?? summary,
|
|
2806
|
+
description: description_ ?? description,
|
|
2807
|
+
deprecated,
|
|
2808
|
+
parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
|
|
2809
|
+
responses: responseTypes[successCode] ?? [],
|
|
2810
|
+
responseTypes,
|
|
2811
|
+
tags: methodObject.tags,
|
|
2812
|
+
security: methodObject.security ?? security,
|
|
2813
|
+
requestBody: baseRequestBody
|
|
2814
|
+
});
|
|
1513
2815
|
}
|
|
1514
2816
|
});
|
|
1515
2817
|
return {
|
|
@@ -1523,252 +2825,275 @@ var VersionedProvider = class {
|
|
|
1523
2825
|
responses: responses_,
|
|
1524
2826
|
parameters: parameters_,
|
|
1525
2827
|
requestBodies: requestBodies_,
|
|
2828
|
+
securitySchemes,
|
|
1526
2829
|
apis
|
|
1527
2830
|
};
|
|
1528
2831
|
}
|
|
1529
2832
|
};
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
var V2 = class extends VersionedProvider {
|
|
2833
|
+
// src/openapi/V3_1.ts
|
|
2834
|
+
var V3_1 = class {
|
|
1533
2835
|
doc;
|
|
1534
|
-
version = "v2";
|
|
1535
2836
|
constructor(doc) {
|
|
1536
|
-
super();
|
|
1537
2837
|
this.doc = doc;
|
|
1538
2838
|
}
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
2839
|
+
/**
|
|
2840
|
+
* Resolves a path $ref to the actual path object.
|
|
2841
|
+
*/
|
|
2842
|
+
resolvePathRef($ref) {
|
|
2843
|
+
const refName = Base.ref2name($ref, this.doc);
|
|
2844
|
+
return this.doc.paths?.[refName];
|
|
1544
2845
|
}
|
|
1545
|
-
|
|
1546
|
-
|
|
2846
|
+
/**
|
|
2847
|
+
* Is array schema.
|
|
2848
|
+
*/
|
|
2849
|
+
isOpenAPIArraySchema(schema) {
|
|
2850
|
+
if (typeof schema !== "object") return false;
|
|
2851
|
+
return schema.type === "array" || Array.isArray(schema.type) && schema.type.includes("array");
|
|
1547
2852
|
}
|
|
1548
|
-
getRequestBodyContainer() {}
|
|
1549
2853
|
/**
|
|
1550
|
-
*
|
|
1551
|
-
* rather than nested under `schema`. Override accordingly.
|
|
2854
|
+
* OpenAPI schema to base schema.
|
|
1552
2855
|
*/
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
if (
|
|
1558
|
-
|
|
2856
|
+
getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
|
|
2857
|
+
let refName = "";
|
|
2858
|
+
if (Base.isRef(schema)) {
|
|
2859
|
+
refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
|
|
2860
|
+
if (reserveRef) return { type: upLevelSchemaKey + refName };
|
|
2861
|
+
if (!this.doc.components) this.doc.components = { schemas: {} };
|
|
2862
|
+
const resolvedSchema = this.doc.components.schemas?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2863
|
+
if (!resolvedSchema) throw new Error(`Schema reference not found: ${refName}`);
|
|
2864
|
+
schema = resolvedSchema;
|
|
1559
2865
|
}
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
2866
|
+
return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
|
|
2867
|
+
}
|
|
2868
|
+
/**
|
|
2869
|
+
* OpenAPI parameter to base parameter.
|
|
2870
|
+
*/
|
|
2871
|
+
getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
|
|
2872
|
+
if (Base.isRef(schema)) schema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2873
|
+
const { name, required, deprecated, description, schema: parameterSchema } = schema;
|
|
2874
|
+
if (parameterSchema && !Base.isRef(parameterSchema) && parameterSchema.enum) {
|
|
2875
|
+
const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
|
|
1564
2876
|
const enumSchema = {
|
|
1565
|
-
name:
|
|
1566
|
-
enum: [...new Set(
|
|
2877
|
+
name: type,
|
|
2878
|
+
enum: [...new Set(parameterSchema.enum)]
|
|
1567
2879
|
};
|
|
1568
2880
|
const sameEnum = Base.findSameSchema(enumSchema, enums);
|
|
1569
|
-
if (!sameEnum && Base.isValidEnumType(
|
|
1570
|
-
type: enumType,
|
|
1571
|
-
enum: enum_
|
|
1572
|
-
})) enums.push(enumSchema);
|
|
2881
|
+
if (!sameEnum && Base.isValidEnumType(parameterSchema)) enums.push(enumSchema);
|
|
1573
2882
|
return {
|
|
1574
2883
|
name,
|
|
1575
2884
|
required,
|
|
1576
2885
|
description,
|
|
1577
|
-
|
|
1578
|
-
|
|
2886
|
+
deprecated,
|
|
2887
|
+
in: schema.in,
|
|
2888
|
+
schema: { type: sameEnum?.name ?? type },
|
|
2889
|
+
style: schema.style,
|
|
2890
|
+
explode: schema.explode
|
|
1579
2891
|
};
|
|
1580
2892
|
}
|
|
1581
|
-
if (items) return {
|
|
1582
|
-
name,
|
|
1583
|
-
required,
|
|
1584
|
-
description,
|
|
1585
|
-
in: p.in,
|
|
1586
|
-
schema: {
|
|
1587
|
-
type,
|
|
1588
|
-
items
|
|
1589
|
-
}
|
|
1590
|
-
};
|
|
1591
|
-
if (schema && Base.isRef(schema)) return {
|
|
1592
|
-
name,
|
|
1593
|
-
required,
|
|
1594
|
-
description,
|
|
1595
|
-
in: p.in,
|
|
1596
|
-
schema: { type: Base.capitalize(Base.ref2name(schema.$ref)) }
|
|
1597
|
-
};
|
|
1598
2893
|
return {
|
|
1599
2894
|
name,
|
|
1600
2895
|
required,
|
|
1601
2896
|
description,
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
2897
|
+
deprecated,
|
|
2898
|
+
in: schema.in,
|
|
2899
|
+
style: schema.style,
|
|
2900
|
+
explode: schema.explode,
|
|
2901
|
+
schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
|
|
1607
2902
|
};
|
|
1608
2903
|
}
|
|
1609
2904
|
/**
|
|
1610
|
-
*
|
|
1611
|
-
* emits JSON.
|
|
2905
|
+
* OpenAPI schema to base response
|
|
1612
2906
|
*/
|
|
1613
|
-
getResponseByRef(schema) {
|
|
1614
|
-
if (Base.isRef(schema)) schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
|
|
1615
|
-
const {
|
|
1616
|
-
return
|
|
1617
|
-
type:
|
|
1618
|
-
schema:
|
|
1619
|
-
}
|
|
2907
|
+
getResponseByRef(schema, enums = []) {
|
|
2908
|
+
if (Base.isRef(schema)) schema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2909
|
+
const { content = {} } = schema;
|
|
2910
|
+
return Object.keys(content).map((c) => ({
|
|
2911
|
+
type: c,
|
|
2912
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
|
|
2913
|
+
}));
|
|
2914
|
+
}
|
|
2915
|
+
/**
|
|
2916
|
+
* OpenAPI schema to requestBody.
|
|
2917
|
+
*/
|
|
2918
|
+
getRequestBodyByRef(schema, enums = []) {
|
|
2919
|
+
if (Base.isRef(schema)) schema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2920
|
+
const { content = {} } = schema;
|
|
2921
|
+
return Object.keys(content).map((c) => ({
|
|
2922
|
+
type: c,
|
|
2923
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
|
|
2924
|
+
}));
|
|
1620
2925
|
}
|
|
1621
2926
|
/**
|
|
1622
|
-
*
|
|
1623
|
-
* `in: formData` are split out and turned into a synthetic requestBody
|
|
1624
|
-
* here. A single body param named `body` is used directly; otherwise
|
|
1625
|
-
* the body / formData params are wrapped in a synthetic object.
|
|
2927
|
+
* Transform all OpenAPI schema to Base Schema
|
|
1626
2928
|
*/
|
|
2929
|
+
toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
|
|
2930
|
+
if (!schema) return { type: "unknown" };
|
|
2931
|
+
if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
|
|
2932
|
+
if (this.isOpenAPIArraySchema(schema)) {
|
|
2933
|
+
const { description, items, required } = schema;
|
|
2934
|
+
const rawType = schema.type;
|
|
2935
|
+
return {
|
|
2936
|
+
type: "array",
|
|
2937
|
+
nullable: Array.isArray(rawType) && rawType.includes("null"),
|
|
2938
|
+
required: !!required,
|
|
2939
|
+
description,
|
|
2940
|
+
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
2941
|
+
};
|
|
2942
|
+
} else {
|
|
2943
|
+
const { required = [], allOf, anyOf, description, deprecated, discriminator, enum: enum_, format, oneOf, properties = {}, const: constValue, additionalProperties } = schema;
|
|
2944
|
+
const rawType = schema.type;
|
|
2945
|
+
const typeArray = Array.isArray(rawType) ? rawType.filter((t) => t !== "null") : void 0;
|
|
2946
|
+
let type = Array.isArray(rawType) ? typeArray?.[0] : schema.type;
|
|
2947
|
+
const nullableByType = Array.isArray(rawType) && rawType.includes("null");
|
|
2948
|
+
if (constValue !== void 0) return {
|
|
2949
|
+
type: typeof constValue === "number" ? "number" : typeof constValue === "boolean" ? "boolean" : "string",
|
|
2950
|
+
const: constValue,
|
|
2951
|
+
required,
|
|
2952
|
+
description,
|
|
2953
|
+
deprecated
|
|
2954
|
+
};
|
|
2955
|
+
if (enum_ && type !== "boolean") {
|
|
2956
|
+
const enumObject = {
|
|
2957
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
|
|
2958
|
+
enum: [...new Set(enum_)]
|
|
2959
|
+
};
|
|
2960
|
+
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
2961
|
+
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
2962
|
+
return {
|
|
2963
|
+
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
2964
|
+
nullable: nullableByType,
|
|
2965
|
+
required,
|
|
2966
|
+
description,
|
|
2967
|
+
deprecated
|
|
2968
|
+
};
|
|
2969
|
+
}
|
|
2970
|
+
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
2971
|
+
return {
|
|
2972
|
+
type,
|
|
2973
|
+
types: typeArray,
|
|
2974
|
+
nullable: nullableByType,
|
|
2975
|
+
const: constValue,
|
|
2976
|
+
additionalProperties: additionalProperties && typeof additionalProperties === "object" ? this.toBaseSchema(additionalProperties, enums) : additionalProperties,
|
|
2977
|
+
required,
|
|
2978
|
+
description,
|
|
2979
|
+
deprecated,
|
|
2980
|
+
discriminator,
|
|
2981
|
+
enum: enum_,
|
|
2982
|
+
format,
|
|
2983
|
+
readOnly: schema.readOnly,
|
|
2984
|
+
writeOnly: schema.writeOnly,
|
|
2985
|
+
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
2986
|
+
...s,
|
|
2987
|
+
ref: s.$ref,
|
|
2988
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2989
|
+
} : this.toBaseSchema(s, enums)),
|
|
2990
|
+
anyOf: anyOf?.map((s) => Base.isRef(s) ? {
|
|
2991
|
+
...s,
|
|
2992
|
+
ref: s.$ref,
|
|
2993
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2994
|
+
} : this.toBaseSchema(s, enums)),
|
|
2995
|
+
oneOf: oneOf?.map((s) => Base.isRef(s) ? {
|
|
2996
|
+
...s,
|
|
2997
|
+
ref: s.$ref,
|
|
2998
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2999
|
+
} : this.toBaseSchema(s, enums)),
|
|
3000
|
+
properties: Object.keys(properties).reduce((acc, p) => {
|
|
3001
|
+
const propSchema = properties[p];
|
|
3002
|
+
return {
|
|
3003
|
+
...acc,
|
|
3004
|
+
[p]: Base.isRef(propSchema) ? {
|
|
3005
|
+
type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)),
|
|
3006
|
+
isRef: true
|
|
3007
|
+
} : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
|
|
3008
|
+
};
|
|
3009
|
+
}, {})
|
|
3010
|
+
};
|
|
3011
|
+
}
|
|
3012
|
+
}
|
|
1627
3013
|
init() {
|
|
1628
|
-
const { paths = {} } = this.doc;
|
|
3014
|
+
const { components = {}, paths = {}, security = [] } = this.doc;
|
|
1629
3015
|
const enums = [];
|
|
1630
|
-
const
|
|
1631
|
-
const
|
|
1632
|
-
|
|
1633
|
-
const schemas_ = Object.keys(schemaContainer).reduce((acc, key) => {
|
|
1634
|
-
const schema = schemaContainer[key];
|
|
3016
|
+
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {}, securitySchemes = {} } = components;
|
|
3017
|
+
const schemas_ = Object.keys(schemas).reduce((acc, key) => {
|
|
3018
|
+
const schema = schemas[key];
|
|
1635
3019
|
return {
|
|
1636
3020
|
...acc,
|
|
1637
3021
|
[key]: this.getSchemaByRef(schema, false, enums, key)
|
|
1638
3022
|
};
|
|
1639
3023
|
}, {});
|
|
1640
|
-
const parameters_ = Object.keys(
|
|
1641
|
-
const parameter =
|
|
3024
|
+
const parameters_ = Object.keys(parameters).reduce((acc, key) => {
|
|
3025
|
+
const parameter = parameters[key];
|
|
1642
3026
|
return {
|
|
1643
3027
|
...acc,
|
|
1644
3028
|
[key]: this.getParameterByRef(parameter, enums, key)
|
|
1645
3029
|
};
|
|
1646
3030
|
}, {});
|
|
1647
|
-
const responses_ = Object.keys(
|
|
1648
|
-
const response =
|
|
3031
|
+
const responses_ = Object.keys(responses).reduce((acc, key) => {
|
|
3032
|
+
const response = responses[key];
|
|
3033
|
+
return {
|
|
3034
|
+
...acc,
|
|
3035
|
+
[key]: this.getResponseByRef(response, enums)
|
|
3036
|
+
};
|
|
3037
|
+
}, {});
|
|
3038
|
+
const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
|
|
3039
|
+
const requestBody = requestBodies[key];
|
|
1649
3040
|
return {
|
|
1650
3041
|
...acc,
|
|
1651
|
-
[key]: this.
|
|
3042
|
+
[key]: this.getRequestBodyByRef(requestBody, enums)
|
|
1652
3043
|
};
|
|
1653
3044
|
}, {});
|
|
1654
|
-
const apis = {
|
|
1655
|
-
for (const path of Object.keys(paths)) {
|
|
3045
|
+
const apis = Object.keys(paths).reduce((acc, path) => {
|
|
1656
3046
|
let pathObject = paths[path] ?? {};
|
|
1657
3047
|
if (pathObject.$ref) {
|
|
1658
3048
|
const resolved = this.resolvePathRef(pathObject.$ref);
|
|
1659
3049
|
if (resolved) pathObject = resolved;
|
|
1660
3050
|
}
|
|
1661
|
-
const { parameters = [] } = pathObject;
|
|
3051
|
+
const { parameters = [], description, summary } = pathObject;
|
|
1662
3052
|
const methodApis = [];
|
|
1663
3053
|
Object.values(HttpMethods).forEach((method) => {
|
|
1664
3054
|
const methodObject = pathObject[method];
|
|
1665
|
-
if (
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
for (const code of httpCodes) if (code in responsesClone) {
|
|
1676
|
-
const response = responsesClone[code];
|
|
1677
|
-
const responseSchema = this.getResponseByRef(response);
|
|
1678
|
-
const inBodyOnlyHasBody = inBody.length === 1 && inBody[0].in === "body" && inBody[0].name === "body";
|
|
3055
|
+
if (methodObject) {
|
|
3056
|
+
const { deprecated, operationId, summary: summary_, description: description_, responses = {}, requestBody = { content: {} } } = methodObject;
|
|
3057
|
+
const { parameters: parameters_ = [] } = methodObject;
|
|
3058
|
+
const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
|
|
3059
|
+
const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
|
|
3060
|
+
const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
|
|
3061
|
+
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
3062
|
+
const httpCodes = Object.keys(responses).filter((code) => code in responses);
|
|
3063
|
+
const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
|
|
3064
|
+
const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
|
|
1679
3065
|
methodApis.push({
|
|
1680
3066
|
method,
|
|
1681
3067
|
operationId,
|
|
1682
|
-
summary: summary_,
|
|
3068
|
+
summary: summary_ ?? summary,
|
|
3069
|
+
description: description_ ?? description,
|
|
1683
3070
|
deprecated,
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
}] : [{
|
|
1691
|
-
type: "application/json",
|
|
1692
|
-
schema: {
|
|
1693
|
-
type: "object",
|
|
1694
|
-
properties: inBody.reduce((a, p) => {
|
|
1695
|
-
return {
|
|
1696
|
-
...a,
|
|
1697
|
-
[p.name]: {
|
|
1698
|
-
type: p.schema?.type ?? "unknown",
|
|
1699
|
-
required: p.schema?.required,
|
|
1700
|
-
items: p.schema?.items,
|
|
1701
|
-
description: p.schema?.description
|
|
1702
|
-
}
|
|
1703
|
-
};
|
|
1704
|
-
}, {})
|
|
1705
|
-
}
|
|
1706
|
-
}] : void 0
|
|
3071
|
+
parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
|
|
3072
|
+
responses: responseTypes[successCode] ?? [],
|
|
3073
|
+
responseTypes,
|
|
3074
|
+
tags: methodObject.tags,
|
|
3075
|
+
security: methodObject.security ?? security,
|
|
3076
|
+
requestBody: baseRequestBody
|
|
1707
3077
|
});
|
|
1708
|
-
break;
|
|
1709
3078
|
}
|
|
1710
3079
|
});
|
|
1711
|
-
|
|
1712
|
-
|
|
3080
|
+
return {
|
|
3081
|
+
...acc,
|
|
3082
|
+
[path]: methodApis
|
|
3083
|
+
};
|
|
3084
|
+
}, {});
|
|
1713
3085
|
return {
|
|
1714
3086
|
enums: Base.uniqueEnums(enums),
|
|
1715
3087
|
schemas: schemas_,
|
|
1716
3088
|
responses: responses_,
|
|
1717
3089
|
parameters: parameters_,
|
|
1718
|
-
requestBodies:
|
|
3090
|
+
requestBodies: requestBodies_,
|
|
3091
|
+
securitySchemes,
|
|
1719
3092
|
apis
|
|
1720
3093
|
};
|
|
1721
3094
|
}
|
|
1722
3095
|
};
|
|
1723
|
-
|
|
1724
|
-
//#region src/openapi/V3.ts
|
|
1725
|
-
var V3 = class extends VersionedProvider {
|
|
1726
|
-
doc;
|
|
1727
|
-
version = "v3";
|
|
1728
|
-
constructor(doc) {
|
|
1729
|
-
super();
|
|
1730
|
-
this.doc = doc;
|
|
1731
|
-
}
|
|
1732
|
-
getSchemaContainer() {
|
|
1733
|
-
return this.doc.components?.schemas;
|
|
1734
|
-
}
|
|
1735
|
-
getParameterContainer() {
|
|
1736
|
-
return this.doc.components?.parameters;
|
|
1737
|
-
}
|
|
1738
|
-
getResponseContainer() {
|
|
1739
|
-
return this.doc.components?.responses;
|
|
1740
|
-
}
|
|
1741
|
-
getRequestBodyContainer() {
|
|
1742
|
-
return this.doc.components?.requestBodies;
|
|
1743
|
-
}
|
|
1744
|
-
};
|
|
1745
|
-
//#endregion
|
|
1746
|
-
//#region src/openapi/V3_1.ts
|
|
1747
|
-
var V3_1 = class extends VersionedProvider {
|
|
1748
|
-
doc;
|
|
1749
|
-
version = "v3_1";
|
|
1750
|
-
constructor(doc) {
|
|
1751
|
-
super();
|
|
1752
|
-
this.doc = doc;
|
|
1753
|
-
}
|
|
1754
|
-
formatRefName(name) {
|
|
1755
|
-
return Base.upperCamelCase(name);
|
|
1756
|
-
}
|
|
1757
|
-
getSchemaContainer() {
|
|
1758
|
-
return this.doc.components?.schemas;
|
|
1759
|
-
}
|
|
1760
|
-
getParameterContainer() {
|
|
1761
|
-
return this.doc.components?.parameters;
|
|
1762
|
-
}
|
|
1763
|
-
getResponseContainer() {
|
|
1764
|
-
return this.doc.components?.responses;
|
|
1765
|
-
}
|
|
1766
|
-
getRequestBodyContainer() {
|
|
1767
|
-
return this.doc.components?.requestBodies;
|
|
1768
|
-
}
|
|
1769
|
-
};
|
|
1770
|
-
//#endregion
|
|
1771
|
-
//#region src/openapi/index.ts
|
|
3096
|
+
// src/openapi/index.ts
|
|
1772
3097
|
const logger$1 = createScopedLogger("OpenAPI");
|
|
1773
3098
|
let OpenAPIVersion = /* @__PURE__ */ function(OpenAPIVersion) {
|
|
1774
3099
|
OpenAPIVersion["v2"] = "v2";
|
|
@@ -1778,7 +3103,9 @@ let OpenAPIVersion = /* @__PURE__ */ function(OpenAPIVersion) {
|
|
|
1778
3103
|
return OpenAPIVersion;
|
|
1779
3104
|
}({});
|
|
1780
3105
|
function getDocVersion(doc) {
|
|
1781
|
-
|
|
3106
|
+
const raw = doc.openapi || doc.swagger;
|
|
3107
|
+
if (typeof raw !== "string" || raw.length === 0) return "unknown";
|
|
3108
|
+
switch (raw.slice(0, 3)) {
|
|
1782
3109
|
case "3.1": return "v3_1";
|
|
1783
3110
|
case "3.0": return "v3";
|
|
1784
3111
|
case "2.0": return "v2";
|
|
@@ -1803,92 +3130,170 @@ function getAdaptor(type) {
|
|
|
1803
3130
|
default: return new FetchAdapter();
|
|
1804
3131
|
}
|
|
1805
3132
|
}
|
|
3133
|
+
/**
|
|
3134
|
+
* Use the document's first server when the caller did not configure a base URL.
|
|
3135
|
+
* Server variables fall back to their declared defaults.
|
|
3136
|
+
*/
|
|
3137
|
+
function inferBaseURL(doc) {
|
|
3138
|
+
const server = doc.servers?.[0];
|
|
3139
|
+
if (server?.url) return server.url.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
3140
|
+
return server.variables?.[name]?.default ?? `{${name}}`;
|
|
3141
|
+
}).replace(/\/+$/, "");
|
|
3142
|
+
const v2 = doc;
|
|
3143
|
+
if (v2.host) return `${v2.schemes?.[0] ?? "https"}://${v2.host}${(v2.basePath ?? "").replace(/\/+$/, "")}`;
|
|
3144
|
+
}
|
|
1806
3145
|
async function codeGen(initOptions) {
|
|
1807
3146
|
const startTime = Date.now();
|
|
1808
3147
|
const { verbose } = initOptions;
|
|
1809
3148
|
if (verbose) logger$1.setLevel("debug");
|
|
1810
3149
|
else logger$1.setLevel("info");
|
|
1811
3150
|
logger$1.info(`Fetch document from ${initOptions.docURL}`);
|
|
1812
|
-
const {
|
|
3151
|
+
const { transport, source } = Base.resolveSpecURL(initOptions.docURL);
|
|
3152
|
+
const rawDoc = transport === "file" ? await (async () => {
|
|
3153
|
+
let raw;
|
|
3154
|
+
try {
|
|
3155
|
+
raw = await readFile(source, "utf8");
|
|
3156
|
+
} catch (error) {
|
|
3157
|
+
if (error?.code === "ENOENT") throw createErrors.specNotFound(source, error);
|
|
3158
|
+
throw new Error(`Failed to read OpenAPI spec from ${source}: ${error instanceof Error ? error.message : String(error)}`);
|
|
3159
|
+
}
|
|
3160
|
+
return Base.parseDoc(raw, source);
|
|
3161
|
+
})() : await Base.fetchDoc(source, initOptions.requestOptions);
|
|
3162
|
+
const doc = await Base.bundleExternalRefs(rawDoc, source, initOptions.requestOptions);
|
|
3163
|
+
const options = {
|
|
3164
|
+
...initOptions,
|
|
3165
|
+
baseURL: initOptions.baseURL ?? inferBaseURL(doc)
|
|
3166
|
+
};
|
|
3167
|
+
const { enums, schemas, parameters, responses, requestBodies, securitySchemes, apis } = new OpenAPIProvider(options, doc);
|
|
1813
3168
|
const adaptor = getAdaptor(initOptions.adaptor ?? "fetch");
|
|
1814
|
-
const
|
|
3169
|
+
const split = splitReadWrite({
|
|
1815
3170
|
enums,
|
|
1816
3171
|
schemas,
|
|
1817
3172
|
parameters,
|
|
1818
3173
|
responses,
|
|
1819
3174
|
requestBodies,
|
|
3175
|
+
securitySchemes,
|
|
1820
3176
|
apis
|
|
1821
|
-
}
|
|
1822
|
-
|
|
3177
|
+
});
|
|
3178
|
+
const parsed = {
|
|
3179
|
+
...split,
|
|
3180
|
+
apis: filterApis(split.apis, options)
|
|
3181
|
+
};
|
|
3182
|
+
const multi = initOptions.splitBy === "tag" ? await Generator.genCodeMulti(parsed, options, adaptor) : void 0;
|
|
3183
|
+
const code = multi?.code ?? await Generator.genCode(parsed, options, adaptor);
|
|
3184
|
+
if (initOptions.output) {
|
|
3185
|
+
if (multi) for (const [name, content] of Object.entries(multi.files)) await Generator.write(content, join(initOptions.output, name));
|
|
3186
|
+
else await Generator.write(code, initOptions.output);
|
|
3187
|
+
}
|
|
1823
3188
|
const duration = Date.now() - startTime;
|
|
3189
|
+
const endpoints = Object.keys(apis).length;
|
|
3190
|
+
const schemasCount = Object.keys(schemas).length;
|
|
1824
3191
|
return {
|
|
1825
3192
|
code,
|
|
3193
|
+
...multi ? { files: multi.files } : {},
|
|
1826
3194
|
stats: {
|
|
1827
|
-
endpoints
|
|
1828
|
-
schemas:
|
|
3195
|
+
endpoints,
|
|
3196
|
+
schemas: schemasCount,
|
|
1829
3197
|
duration
|
|
1830
3198
|
}
|
|
1831
3199
|
};
|
|
1832
3200
|
}
|
|
1833
|
-
|
|
1834
|
-
//#region src/vite-plugin/index.ts
|
|
1835
|
-
const PLUGIN_NAME = "api-code-gen";
|
|
1836
|
-
const pluginLogger = createScopedLogger("api-code-gen");
|
|
3201
|
+
// src/core/typecheck.ts
|
|
1837
3202
|
/**
|
|
1838
|
-
*
|
|
1839
|
-
*
|
|
1840
|
-
*
|
|
3203
|
+
* Type-check a generated file with the project's TypeScript.
|
|
3204
|
+
*
|
|
3205
|
+
* @param filePath - Path to the generated file.
|
|
3206
|
+
* @returns Collected error messages; an empty array means success.
|
|
1841
3207
|
*/
|
|
1842
|
-
async function
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
const configPath = path.join(dir, name);
|
|
1849
|
-
if (await fs.pathExists(configPath)) return configPath;
|
|
1850
|
-
}
|
|
1851
|
-
if (dir === rootDir || dir === fsRoot) break;
|
|
1852
|
-
dir = path.dirname(dir);
|
|
3208
|
+
async function runTypeCheck(filePath) {
|
|
3209
|
+
try {
|
|
3210
|
+
await execaCommand(`npx tsc ${filePath} --noEmit`, { shell: true });
|
|
3211
|
+
return [];
|
|
3212
|
+
} catch (error) {
|
|
3213
|
+
return [error instanceof Error ? error.message : String(error)];
|
|
1853
3214
|
}
|
|
1854
|
-
return null;
|
|
1855
3215
|
}
|
|
3216
|
+
// package.json
|
|
3217
|
+
var version = "1.0.0";
|
|
3218
|
+
// src/vite-plugin/cache.ts
|
|
1856
3219
|
/**
|
|
1857
|
-
*
|
|
3220
|
+
* Cache for a single vite-plugin codegen run. Lives only for the duration
|
|
3221
|
+
* of one plugin invocation — there is no module-level state.
|
|
3222
|
+
*
|
|
3223
|
+
* Cache files are stored at:
|
|
3224
|
+
*
|
|
3225
|
+
* <cacheDir>/<optionsHash>.json
|
|
3226
|
+
*
|
|
3227
|
+
* where `<cacheDir>` defaults to `node_modules/.cache/apicodegen` but can
|
|
3228
|
+
* be overridden via `cacheDir`.
|
|
1858
3229
|
*/
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
3230
|
+
var CodegenCache = class CodegenCache {
|
|
3231
|
+
cacheDir;
|
|
3232
|
+
constructor(cacheDir) {
|
|
3233
|
+
this.cacheDir = cacheDir;
|
|
3234
|
+
}
|
|
3235
|
+
/** Hash the options that affect generated output (excluding the spec). */
|
|
3236
|
+
static hashOptions(options) {
|
|
3237
|
+
const keys = Object.keys(options).sort();
|
|
3238
|
+
const payload = [`generatorVersion=${version}`, ...keys.filter((k) => k !== "verbose" && k !== "typeCheck" && k !== "cache").map((k) => `${k}=${JSON.stringify(options[k])}`)].join("|");
|
|
3239
|
+
return createHash("sha256").update(payload).digest("hex").slice(0, 16);
|
|
3240
|
+
}
|
|
3241
|
+
/** Hash the raw spec content so unrelated edits are detected. */
|
|
3242
|
+
static hashContent(content) {
|
|
3243
|
+
return createHash("sha256").update(content).digest("hex").slice(0, 16);
|
|
3244
|
+
}
|
|
3245
|
+
/**
|
|
3246
|
+
* Look up a cached entry. Returns `null` on miss / corruption / disabled.
|
|
3247
|
+
*
|
|
3248
|
+
* @param optionsHash Options hash from `hashOptions`.
|
|
3249
|
+
* @param specSource Resolved spec path or URL. Local paths use mtime +
|
|
3250
|
+
* content hash; URLs always miss (no cache).
|
|
3251
|
+
*/
|
|
3252
|
+
async lookup(optionsHash, specSource) {
|
|
3253
|
+
const cachePath = path.join(this.cacheDir, `${optionsHash}.json`);
|
|
3254
|
+
let raw;
|
|
1865
3255
|
try {
|
|
1866
|
-
await
|
|
1867
|
-
} catch
|
|
1868
|
-
|
|
3256
|
+
raw = await readFile(cachePath, "utf8");
|
|
3257
|
+
} catch {
|
|
3258
|
+
return null;
|
|
1869
3259
|
}
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
};
|
|
1880
|
-
try {
|
|
1881
|
-
await fs.writeJson(tempConfigPath, tempConfig);
|
|
1882
|
-
await execaCommand(`npx tsc --project "${tempConfigPath}" --noEmit`, { shell: true });
|
|
1883
|
-
} catch (error) {
|
|
1884
|
-
if (error instanceof Error) errors.push(error.message);
|
|
1885
|
-
} finally {
|
|
3260
|
+
let entry;
|
|
3261
|
+
try {
|
|
3262
|
+
entry = JSON.parse(raw);
|
|
3263
|
+
} catch {
|
|
3264
|
+
return null;
|
|
3265
|
+
}
|
|
3266
|
+
if (entry.optionsHash !== optionsHash) return null;
|
|
3267
|
+
if (specSource.startsWith("http://") || specSource.startsWith("https://")) return null;
|
|
3268
|
+
let currentMtimeMs;
|
|
1886
3269
|
try {
|
|
1887
|
-
await
|
|
1888
|
-
} catch {
|
|
3270
|
+
currentMtimeMs = (await stat(specSource)).mtimeMs;
|
|
3271
|
+
} catch {
|
|
3272
|
+
return null;
|
|
3273
|
+
}
|
|
3274
|
+
if (currentMtimeMs !== entry.specMtimeMs) return null;
|
|
3275
|
+
if (entry.specContentHash) {
|
|
3276
|
+
let content;
|
|
3277
|
+
try {
|
|
3278
|
+
content = await readFile(specSource, "utf8");
|
|
3279
|
+
} catch {
|
|
3280
|
+
return null;
|
|
3281
|
+
}
|
|
3282
|
+
if (CodegenCache.hashContent(content) !== entry.specContentHash) return null;
|
|
3283
|
+
}
|
|
3284
|
+
return entry;
|
|
1889
3285
|
}
|
|
1890
|
-
|
|
1891
|
-
|
|
3286
|
+
/** Persist a successful codegen result. */
|
|
3287
|
+
async store(entry) {
|
|
3288
|
+
const cachePath = path.join(this.cacheDir, `${entry.optionsHash}.json`);
|
|
3289
|
+
const dir = path.dirname(cachePath);
|
|
3290
|
+
await import("fs-extra").then((fs) => fs.ensureDir(dir));
|
|
3291
|
+
await writeFile(cachePath, JSON.stringify(entry));
|
|
3292
|
+
}
|
|
3293
|
+
};
|
|
3294
|
+
// src/vite-plugin/index.ts
|
|
3295
|
+
const PLUGIN_NAME = "api-code-gen";
|
|
3296
|
+
const logger = createScopedLogger("api-code-gen");
|
|
1892
3297
|
/**
|
|
1893
3298
|
* Validate spec path exists
|
|
1894
3299
|
*/
|
|
@@ -1898,13 +3303,19 @@ async function validateSpecPath(specPath) {
|
|
|
1898
3303
|
const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
|
|
1899
3304
|
if (!await fs.pathExists(absolutePath)) throw createErrors.specNotFound(absolutePath);
|
|
1900
3305
|
}
|
|
3306
|
+
/** Resolve a local spec to an absolute path; remote specs return null. */
|
|
3307
|
+
function toWatchPath(spec) {
|
|
3308
|
+
if (!spec || spec.startsWith("http://") || spec.startsWith("https://")) return null;
|
|
3309
|
+
const filePath = spec.replace(/^file:\/\//, "");
|
|
3310
|
+
return path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
|
|
3311
|
+
}
|
|
1901
3312
|
/**
|
|
1902
3313
|
* Generate code for a single API configuration
|
|
1903
3314
|
*/
|
|
1904
3315
|
async function generateForOption(option) {
|
|
1905
|
-
const { name, typeCheck = true, verbose, ...restOptions } = option;
|
|
3316
|
+
const { name, typeCheck = true, verbose, cache = true, cacheDir, ...restOptions } = option;
|
|
1906
3317
|
try {
|
|
1907
|
-
|
|
3318
|
+
console.log(`\x1b[36m├─\x1b[0m ${name}`);
|
|
1908
3319
|
const config = await loadConfig({
|
|
1909
3320
|
name,
|
|
1910
3321
|
cliOptions: {
|
|
@@ -1913,30 +3324,82 @@ async function generateForOption(option) {
|
|
|
1913
3324
|
}
|
|
1914
3325
|
});
|
|
1915
3326
|
await validateSpecPath(config.spec);
|
|
1916
|
-
if (config.output) {
|
|
1917
|
-
const outputDir = path.dirname(config.output);
|
|
1918
|
-
await fs.ensureDir(outputDir);
|
|
1919
|
-
}
|
|
1920
3327
|
let docURL = config.spec;
|
|
1921
|
-
if (!docURL.startsWith("http://") && !docURL.startsWith("https://")
|
|
1922
|
-
|
|
1923
|
-
const
|
|
1924
|
-
|
|
1925
|
-
|
|
3328
|
+
if (!docURL.startsWith("http://") && !docURL.startsWith("https://") && !docURL.startsWith("file://") && !docURL.startsWith("/") && !/^[A-Za-z]:[\\/]/.test(docURL)) docURL = path.resolve(process.cwd(), docURL);
|
|
3329
|
+
const resolvedCacheDir = cacheDir ?? path.join(process.cwd(), "node_modules", ".cache", "apicodegen");
|
|
3330
|
+
const codegenCache = cache && !config.splitBy ? new CodegenCache(resolvedCacheDir) : null;
|
|
3331
|
+
const optionsHash = CodegenCache.hashOptions({
|
|
3332
|
+
name,
|
|
3333
|
+
spec: docURL,
|
|
3334
|
+
output: config.output,
|
|
3335
|
+
adaptor: config.adaptor,
|
|
3336
|
+
errorMode: config.errorMode,
|
|
3337
|
+
splitBy: config.splitBy,
|
|
3338
|
+
includeTags: config.includeTags,
|
|
3339
|
+
excludeTags: config.excludeTags,
|
|
3340
|
+
includePaths: config.includePaths,
|
|
3341
|
+
excludePaths: config.excludePaths,
|
|
3342
|
+
baseURL: config.baseURL,
|
|
3343
|
+
importClientSource: config.importClientSource
|
|
1926
3344
|
});
|
|
1927
|
-
|
|
3345
|
+
let result = null;
|
|
3346
|
+
let cached = false;
|
|
3347
|
+
if (codegenCache) {
|
|
3348
|
+
const cachedEntry = await codegenCache.lookup(optionsHash, docURL);
|
|
3349
|
+
if (cachedEntry) {
|
|
3350
|
+
result = {
|
|
3351
|
+
code: cachedEntry.code,
|
|
3352
|
+
stats: cachedEntry.stats
|
|
3353
|
+
};
|
|
3354
|
+
cached = true;
|
|
3355
|
+
if (verbose) logger.debug(`Cache hit for ${name} (${optionsHash})`);
|
|
3356
|
+
}
|
|
3357
|
+
}
|
|
3358
|
+
if (!result) {
|
|
3359
|
+
result = await codeGen({
|
|
3360
|
+
...toProviderOptions(config),
|
|
3361
|
+
docURL
|
|
3362
|
+
});
|
|
3363
|
+
if (codegenCache) try {
|
|
3364
|
+
const fsPromises = await import("node:fs/promises");
|
|
3365
|
+
let specMtimeMs;
|
|
3366
|
+
let specContentHash;
|
|
3367
|
+
if (!(docURL.startsWith("http://") || docURL.startsWith("https://"))) try {
|
|
3368
|
+
specMtimeMs = (await fsPromises.stat(docURL)).mtimeMs;
|
|
3369
|
+
const content = await fsPromises.readFile(docURL, "utf8");
|
|
3370
|
+
specContentHash = CodegenCache.hashContent(content);
|
|
3371
|
+
} catch {}
|
|
3372
|
+
await codegenCache.store({
|
|
3373
|
+
optionsHash,
|
|
3374
|
+
specMtimeMs,
|
|
3375
|
+
specContentHash,
|
|
3376
|
+
code: result.code,
|
|
3377
|
+
stats: result.stats
|
|
3378
|
+
});
|
|
3379
|
+
} catch (cacheError) {
|
|
3380
|
+
if (verbose) logger.warn(`Cache write failed for ${name}: ${cacheError.message}`);
|
|
3381
|
+
}
|
|
3382
|
+
}
|
|
3383
|
+
if (config.output) {
|
|
3384
|
+
if (result.files) {
|
|
3385
|
+
const dir = path.dirname(config.output);
|
|
3386
|
+
for (const [name, content] of Object.entries(result.files)) if (name !== "index.ts") await fs.outputFile(path.join(dir, name), content);
|
|
3387
|
+
}
|
|
3388
|
+
await fs.outputFile(config.output, result.code);
|
|
3389
|
+
}
|
|
1928
3390
|
if (typeCheck && config.output) {
|
|
1929
3391
|
const typeErrors = await runTypeCheck(config.output);
|
|
1930
3392
|
if (typeErrors.length > 0) {
|
|
1931
|
-
|
|
1932
|
-
if (verbose) for (const error of typeErrors)
|
|
3393
|
+
logger.warn(`Type check failed for ${config.output}`);
|
|
3394
|
+
if (verbose) for (const error of typeErrors) logger.warn(` ${error}`);
|
|
1933
3395
|
}
|
|
1934
3396
|
}
|
|
1935
3397
|
return {
|
|
1936
3398
|
success: true,
|
|
1937
3399
|
name,
|
|
1938
3400
|
output: config.output,
|
|
1939
|
-
stats: result.stats
|
|
3401
|
+
stats: result.stats,
|
|
3402
|
+
cached
|
|
1940
3403
|
};
|
|
1941
3404
|
} catch (error) {
|
|
1942
3405
|
return {
|
|
@@ -1970,52 +3433,75 @@ async function generateForOption(option) {
|
|
|
1970
3433
|
*/
|
|
1971
3434
|
function apiCodeGenPlugin(options) {
|
|
1972
3435
|
if (!Array.isArray(options) || options.length === 0) {
|
|
1973
|
-
|
|
3436
|
+
logger.warn("No API configurations provided to apiCodeGenPlugin");
|
|
1974
3437
|
return { name: PLUGIN_NAME };
|
|
1975
3438
|
}
|
|
3439
|
+
let mode = "unknown";
|
|
3440
|
+
const watched = /* @__PURE__ */ new Set();
|
|
3441
|
+
const printResults = (results) => {
|
|
3442
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3443
|
+
console.log(`\x1b[1m\x1b[36mAPI Code Gen\x1b[0m`);
|
|
3444
|
+
console.log(`\x1b[90mMode:\x1b[0m ${mode}`);
|
|
3445
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3446
|
+
const successCount = results.filter((r) => r.success).length;
|
|
3447
|
+
const failCount = results.length - successCount;
|
|
3448
|
+
for (const result of results) if (result.success) {
|
|
3449
|
+
const { name, output, stats, cached } = result;
|
|
3450
|
+
if (stats) {
|
|
3451
|
+
const cachedTag = cached ? " \x1B[90m[cached]\x1B[0m" : "";
|
|
3452
|
+
console.log(`\x1b[32m✓\x1b[0m ${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms${cachedTag}`);
|
|
3453
|
+
} else console.log(`\x1b[32m✓\x1b[0m ${name} → ${output || "N/A"}`);
|
|
3454
|
+
} else {
|
|
3455
|
+
const { name, error } = result;
|
|
3456
|
+
const wrapped = isApicodegenError(error) ? error : wrapError(error, {
|
|
3457
|
+
code: "E_GENERATION_FAILED",
|
|
3458
|
+
message: `Failed to generate API "${name}"`
|
|
3459
|
+
});
|
|
3460
|
+
console.log(`\x1b[31m✗\x1b[0m ${name}`);
|
|
3461
|
+
console.log(`\x1b[90m${formatError(wrapped, true)}\x1b[0m`);
|
|
3462
|
+
}
|
|
3463
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3464
|
+
const totalDuration = results.reduce((sum, r) => sum + (r.stats?.duration || 0), 0);
|
|
3465
|
+
const totalEndpoints = results.reduce((sum, r) => sum + (r.stats?.endpoints || 0), 0);
|
|
3466
|
+
const totalSchemas = results.reduce((sum, r) => sum + (r.stats?.schemas || 0), 0);
|
|
3467
|
+
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)`);
|
|
3468
|
+
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)`);
|
|
3469
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3470
|
+
};
|
|
3471
|
+
const regenerate = async (option) => {
|
|
3472
|
+
const result = await generateForOption(option);
|
|
3473
|
+
printResults([result]);
|
|
3474
|
+
};
|
|
1976
3475
|
return {
|
|
1977
3476
|
name: PLUGIN_NAME,
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
const results = await Promise.all(options.map(generateForOption));
|
|
1981
|
-
const successCount = results.filter((r) => r.success).length;
|
|
1982
|
-
const failCount = options.length - successCount;
|
|
1983
|
-
logger.divider();
|
|
1984
|
-
for (const result of results) if (result.success) {
|
|
1985
|
-
const { name, output, stats } = result;
|
|
1986
|
-
if (stats) logger.item(`${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms`, "green");
|
|
1987
|
-
else logger.item(`${name} → ${output || "N/A"}`, "green");
|
|
1988
|
-
} else {
|
|
1989
|
-
const { name, error } = result;
|
|
1990
|
-
if (isApicodegenError(error)) {
|
|
1991
|
-
logger.item(name, "red");
|
|
1992
|
-
logger.error(error, true);
|
|
1993
|
-
} else {
|
|
1994
|
-
const wrapped = wrapError(error, {
|
|
1995
|
-
code: ErrorCodes.GENERATION_FAILED,
|
|
1996
|
-
message: `Failed to generate API "${name}"`
|
|
1997
|
-
});
|
|
1998
|
-
logger.item(name, "red");
|
|
1999
|
-
logger.error(wrapped, true);
|
|
2000
|
-
}
|
|
2001
|
-
}
|
|
2002
|
-
logger.divider();
|
|
2003
|
-
const totalDuration = results.reduce((sum, r) => sum + (r.stats?.duration || 0), 0);
|
|
2004
|
-
const totalEndpoints = results.reduce((sum, r) => sum + (r.stats?.endpoints || 0), 0);
|
|
2005
|
-
const totalSchemas = results.reduce((sum, r) => sum + (r.stats?.schemas || 0), 0);
|
|
2006
|
-
logger.summary({
|
|
2007
|
-
succeeded: successCount,
|
|
2008
|
-
failed: failCount,
|
|
2009
|
-
endpoints: totalEndpoints,
|
|
2010
|
-
schemas: totalSchemas,
|
|
2011
|
-
duration: totalDuration
|
|
2012
|
-
});
|
|
2013
|
-
logger.divider();
|
|
3477
|
+
config(_config, env) {
|
|
3478
|
+
mode = env?.command || "unknown";
|
|
2014
3479
|
return {};
|
|
3480
|
+
},
|
|
3481
|
+
async buildStart() {
|
|
3482
|
+
for (const option of options) {
|
|
3483
|
+
const specPath = toWatchPath(option.spec);
|
|
3484
|
+
if (specPath) this.addWatchFile(specPath);
|
|
3485
|
+
}
|
|
3486
|
+
printResults(await Promise.all(options.map(generateForOption)));
|
|
3487
|
+
},
|
|
3488
|
+
configureServer(server) {
|
|
3489
|
+
for (const option of options) {
|
|
3490
|
+
const specPath = toWatchPath(option.spec);
|
|
3491
|
+
if (!specPath || watched.has(specPath)) continue;
|
|
3492
|
+
watched.add(specPath);
|
|
3493
|
+
server.watcher.add(specPath);
|
|
3494
|
+
const onChange = async (changed) => {
|
|
3495
|
+
if (path.resolve(changed) !== path.resolve(specPath)) return;
|
|
3496
|
+
await regenerate(option);
|
|
3497
|
+
server.ws.send({ type: "full-reload" });
|
|
3498
|
+
};
|
|
3499
|
+
server.watcher.on("change", onChange);
|
|
3500
|
+
server.watcher.on("add", onChange);
|
|
3501
|
+
}
|
|
2015
3502
|
}
|
|
2016
3503
|
};
|
|
2017
3504
|
}
|
|
2018
|
-
|
|
2019
|
-
export { Adapter, Adaptors, ApicodegenError, ArraySchemaType, AxiosAdapter, Base, Colors, ErrorCodes, FetchAdapter, Generator, HttpMethods, MediaTypes, NonArraySchemaType, OpenAPIProvider, OpenAPIVersion, ParameterIn, Provider, SchemaFormatType, SchemaType, SuccessHttpStatusCode, apiCodeGenPlugin, codeGen, createErrors, formatError, isApicodegenError, loadConfig, logger, printError, toProviderOptions, wrapError };
|
|
3505
|
+
export { Adapter, Adaptors, ApicodegenError, ArraySchemaType, AxiosAdapter, Base, Colors, ErrorCodes, FetchAdapter, Generator, HttpMethods, MediaTypes, NonArraySchemaType, OpenAPIProvider, OpenAPIVersion, ParameterIn, Provider, SchemaFormatType, SchemaType, SuccessHttpStatusCode, apiCodeGenPlugin, authAccess, authHeaderEntries, codeGen, configToCLIOptions, cookieHeaderExpression, createErrors, fetchSignalExpression, formatError, isApicodegenError, loadConfig, loadConfigs, mergeConfigs, optionalAccess, printError, toProviderOptions, validateConfig, validateConfigShape, withRequestHeaders, wrapError };
|
|
2020
3506
|
|
|
2021
3507
|
//# sourceMappingURL=index.mjs.map
|