@moccona/apicodegen 0.1.2 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +312 -29
- package/bin/cli.cjs +9 -6
- package/npm/index.cjs +1279 -311
- package/npm/index.cjs.map +1 -1
- package/npm/index.d.cts +293 -51
- package/npm/index.d.cts.map +1 -1
- package/npm/index.d.mts +293 -51
- package/npm/index.d.mts.map +1 -1
- package/npm/index.mjs +1271 -310
- package/npm/index.mjs.map +1 -1
- package/npm/vite/index.d.mts +27 -10
- package/npm/vite/index.d.mts.map +1 -1
- package/npm/vite/index.mjs +1259 -306
- package/npm/vite/index.mjs.map +1 -1
- package/package.json +36 -20
package/npm/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
|
|
2
|
+
// \0rolldown/runtime.js
|
|
3
3
|
var __create = Object.create;
|
|
4
4
|
var __defProp = Object.defineProperty;
|
|
5
5
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -16,30 +16,25 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
16
16
|
}
|
|
17
17
|
return to;
|
|
18
18
|
};
|
|
19
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
20
|
value: mod,
|
|
21
21
|
enumerable: true
|
|
22
22
|
}) : target, mod));
|
|
23
|
-
|
|
23
|
+
let typescript = require("typescript");
|
|
24
24
|
let node_fs_promises = require("node:fs/promises");
|
|
25
|
+
let node_url = require("node:url");
|
|
25
26
|
let undici = require("undici");
|
|
26
|
-
let
|
|
27
|
-
let prettier = require("prettier");
|
|
27
|
+
let yaml = require("yaml");
|
|
28
28
|
let node_path = require("node:path");
|
|
29
29
|
node_path = __toESM(node_path, 1);
|
|
30
|
+
let prettier = require("prettier");
|
|
30
31
|
let fs_extra = require("fs-extra");
|
|
31
32
|
fs_extra = __toESM(fs_extra, 1);
|
|
32
33
|
let _moccona_logger = require("@moccona/logger");
|
|
34
|
+
let execa = require("execa");
|
|
33
35
|
let node_crypto = require("node:crypto");
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
* Base adapter for tool
|
|
37
|
-
* This abstract class serves as the foundation for implementing adapters for different code generation tools
|
|
38
|
-
*/
|
|
39
|
-
var Adapter = class {};
|
|
40
|
-
//#endregion
|
|
41
|
-
//#region src/core/constants/keywords.ts
|
|
42
|
-
const typescriptKeywords = new Set([
|
|
36
|
+
// src/core/constants/keywords.ts
|
|
37
|
+
const typescriptKeywords = /* @__PURE__ */ new Set([
|
|
43
38
|
"break",
|
|
44
39
|
"case",
|
|
45
40
|
"catch",
|
|
@@ -115,8 +110,7 @@ const typescriptKeywords = new Set([
|
|
|
115
110
|
"undefined",
|
|
116
111
|
"bigint"
|
|
117
112
|
]);
|
|
118
|
-
|
|
119
|
-
//#region src/core/errors.ts
|
|
113
|
+
// src/core/errors.ts
|
|
120
114
|
/**
|
|
121
115
|
* Error handling utilities for api-codegen
|
|
122
116
|
*/
|
|
@@ -313,6 +307,15 @@ const createErrors = {
|
|
|
313
307
|
cause
|
|
314
308
|
});
|
|
315
309
|
},
|
|
310
|
+
writeFailed(path, cause) {
|
|
311
|
+
return new ApicodegenError({
|
|
312
|
+
code: ErrorCodes.GENERATION_FAILED,
|
|
313
|
+
message: "Failed to write generated code",
|
|
314
|
+
location: path,
|
|
315
|
+
suggestions: ["Check that the output path is writable", "Ensure the output directory can be created"],
|
|
316
|
+
cause
|
|
317
|
+
});
|
|
318
|
+
},
|
|
316
319
|
typeCheckFailed(path, _errors, cause) {
|
|
317
320
|
return new ApicodegenError({
|
|
318
321
|
code: ErrorCodes.TYPE_CHECK_FAILED,
|
|
@@ -360,8 +363,7 @@ function wrapError(error, context) {
|
|
|
360
363
|
function isApicodegenError(error) {
|
|
361
364
|
return error instanceof ApicodegenError;
|
|
362
365
|
}
|
|
363
|
-
|
|
364
|
-
//#region src/core/interface.ts
|
|
366
|
+
// src/core/interface.ts
|
|
365
367
|
let SchemaType = /* @__PURE__ */ function(SchemaType) {
|
|
366
368
|
SchemaType["schemas"] = "schemas";
|
|
367
369
|
SchemaType["parameters"] = "parameters";
|
|
@@ -425,8 +427,7 @@ let Adaptors = /* @__PURE__ */ function(Adaptors) {
|
|
|
425
427
|
Adaptors["axios"] = "axios";
|
|
426
428
|
return Adaptors;
|
|
427
429
|
}({});
|
|
428
|
-
|
|
429
|
-
//#region src/core/base/Base.ts
|
|
430
|
+
// src/core/base/Base.ts
|
|
430
431
|
/**
|
|
431
432
|
* @file Base class implementation
|
|
432
433
|
* @author wp.l
|
|
@@ -497,6 +498,17 @@ var Base = class Base {
|
|
|
497
498
|
return name + suffix;
|
|
498
499
|
}
|
|
499
500
|
/**
|
|
501
|
+
* Converts arbitrary text into a legal TypeScript variable identifier.
|
|
502
|
+
* Keywords keep the `_` suffix that `normalize` adds, since `camelCase`
|
|
503
|
+
* would otherwise strip it and emit a reserved word.
|
|
504
|
+
* @param text - Input text.
|
|
505
|
+
* @returns - A legal identifier.
|
|
506
|
+
*/
|
|
507
|
+
static toIdentifier(text) {
|
|
508
|
+
const name = Base.camelCase(Base.normalize(text));
|
|
509
|
+
return typescriptKeywords.has(name) ? `${name}_` : name;
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
500
512
|
* Normalizes a string by replacing special characters and avoiding TypeScript keywords.
|
|
501
513
|
* @param text - Input text to normalize.
|
|
502
514
|
* @returns - The normalized string.
|
|
@@ -610,18 +622,39 @@ var Base = class Base {
|
|
|
610
622
|
if (error?.code === "ENOENT") throw createErrors.specNotFound(filePath, error);
|
|
611
623
|
throw new Error(`Failed to read OpenAPI spec from ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
612
624
|
}
|
|
625
|
+
return Base.parseDoc(raw, filePath);
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Parses an OpenAPI document from JSON or YAML text.
|
|
629
|
+
*
|
|
630
|
+
* JSON is attempted first for a clearer syntax error on JSON files; YAML
|
|
631
|
+
* then handles `.yaml` / `.yml` specs. Any failure is reported as
|
|
632
|
+
* `E_SPEC_PARSE_FAILED` with the source path attached.
|
|
633
|
+
*
|
|
634
|
+
* @param raw - Raw spec content.
|
|
635
|
+
* @param source - Path or URL used in error messages.
|
|
636
|
+
* @returns - The parsed document.
|
|
637
|
+
*/
|
|
638
|
+
static parseDoc(raw, source) {
|
|
639
|
+
let parsed;
|
|
613
640
|
try {
|
|
614
|
-
|
|
615
|
-
} catch
|
|
616
|
-
|
|
641
|
+
parsed = JSON.parse(raw);
|
|
642
|
+
} catch {
|
|
643
|
+
try {
|
|
644
|
+
parsed = (0, yaml.parse)(raw);
|
|
645
|
+
} catch (error) {
|
|
646
|
+
throw createErrors.specParseFailed(source, void 0, void 0, error);
|
|
647
|
+
}
|
|
617
648
|
}
|
|
649
|
+
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"));
|
|
650
|
+
return parsed;
|
|
618
651
|
}
|
|
619
652
|
/**
|
|
620
653
|
* Fetches documentation from a given URL.
|
|
621
654
|
*
|
|
622
655
|
* Supports three transport modes:
|
|
623
|
-
* - `file://...` URLs → read from filesystem (
|
|
624
|
-
* - absolute filesystem paths → read from filesystem (
|
|
656
|
+
* - `file://...` URLs → read from filesystem (JSON or YAML)
|
|
657
|
+
* - absolute filesystem paths → read from filesystem (JSON or YAML)
|
|
625
658
|
* - `http(s)://...` URLs (and unrecognised inputs like relative paths)
|
|
626
659
|
* → fetched via undici (existing behavior)
|
|
627
660
|
*
|
|
@@ -631,22 +664,139 @@ var Base = class Base {
|
|
|
631
664
|
*
|
|
632
665
|
* @param url - The URL or filesystem path to fetch the documentation from.
|
|
633
666
|
* @param requestInit - Additional request parameters (only used for http(s)).
|
|
667
|
+
* TLS certificates are verified by default; set `insecure: true` to opt out.
|
|
634
668
|
* @returns - A promise resolving to the fetched documentation data.
|
|
635
669
|
*/
|
|
636
670
|
static async fetchDoc(url, requestInit = {}) {
|
|
637
671
|
const { transport, source } = Base.resolveSpecURL(url);
|
|
638
672
|
if (transport === "file") return Base.readLocalDoc(source);
|
|
673
|
+
const { insecure = false, ...init } = requestInit;
|
|
639
674
|
const { body, statusCode } = await (0, undici.request)(source, {
|
|
640
675
|
method: "GET",
|
|
641
|
-
dispatcher: new undici.Agent({ connect: { rejectUnauthorized: false } }),
|
|
642
|
-
...
|
|
676
|
+
...insecure ? { dispatcher: new undici.Agent({ connect: { rejectUnauthorized: false } }) } : {},
|
|
677
|
+
...init
|
|
643
678
|
});
|
|
644
679
|
if (statusCode >= 400) throw new Error(`Failed to fetch OpenAPI documentation from ${source}: HTTP ${statusCode}`);
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
680
|
+
return Base.parseDoc(await body.text(), source);
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Copies external `$ref` targets (other files or remote URLs) into the root
|
|
684
|
+
* document and rewrites the refs to local ones. Objects are registered
|
|
685
|
+
* before their children are walked, so cycles keep working.
|
|
686
|
+
*
|
|
687
|
+
* External refs are placed in the component section implied by their
|
|
688
|
+
* fragment (`schemas` by default); a generated local `$ref` points at the
|
|
689
|
+
* copy.
|
|
690
|
+
*
|
|
691
|
+
* @param doc - Parsed root document (mutated in place).
|
|
692
|
+
* @param source - Absolute path or URL of the root document.
|
|
693
|
+
* @param requestInit - Request options for remote refs.
|
|
694
|
+
* @returns - The same document with external refs resolved.
|
|
695
|
+
*/
|
|
696
|
+
static async bundleExternalRefs(doc, source, requestInit = {}) {
|
|
697
|
+
const root = doc;
|
|
698
|
+
const isV2 = typeof root.swagger === "string";
|
|
699
|
+
const rootURL = Base.resolveSpecURL(source).transport === "file" ? (0, node_url.pathToFileURL)(source).href : source;
|
|
700
|
+
const docs = /* @__PURE__ */ new Map([[rootURL, root]]);
|
|
701
|
+
const registered = /* @__PURE__ */ new Map();
|
|
702
|
+
const loadDoc = async (url) => {
|
|
703
|
+
const cached = docs.get(url);
|
|
704
|
+
if (cached !== void 0) return cached;
|
|
705
|
+
const loaded = await Base.fetchDoc(url, requestInit);
|
|
706
|
+
docs.set(url, loaded);
|
|
707
|
+
return loaded;
|
|
708
|
+
};
|
|
709
|
+
const containerFor = (ref) => {
|
|
710
|
+
const section = Base.externalRefSection(ref, isV2);
|
|
711
|
+
if (isV2) {
|
|
712
|
+
root[section] ??= {};
|
|
713
|
+
return {
|
|
714
|
+
record: root[section],
|
|
715
|
+
prefix: `#/${section}/`
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
root.components ??= {};
|
|
719
|
+
root.components[section] ??= {};
|
|
720
|
+
return {
|
|
721
|
+
record: root.components[section],
|
|
722
|
+
prefix: `#/components/${section}/`
|
|
723
|
+
};
|
|
724
|
+
};
|
|
725
|
+
const register = async (absolute) => {
|
|
726
|
+
const existing = registered.get(absolute);
|
|
727
|
+
if (existing) return existing;
|
|
728
|
+
const hashIndex = absolute.indexOf("#");
|
|
729
|
+
const docURL = hashIndex === -1 ? absolute : absolute.slice(0, hashIndex);
|
|
730
|
+
const fragment = hashIndex === -1 ? "" : absolute.slice(hashIndex);
|
|
731
|
+
const externalDoc = await loadDoc(docURL);
|
|
732
|
+
const { record, prefix } = containerFor(fragment);
|
|
733
|
+
const target = Base.resolveJSONPointer(externalDoc, fragment);
|
|
734
|
+
if (target === void 0) return `${prefix}unknown`;
|
|
735
|
+
const baseName = Base.externalRefName(fragment, docURL);
|
|
736
|
+
let name = baseName;
|
|
737
|
+
let suffix = 2;
|
|
738
|
+
while (name in record) {
|
|
739
|
+
name = `${baseName}${suffix}`;
|
|
740
|
+
suffix++;
|
|
741
|
+
}
|
|
742
|
+
registered.set(absolute, prefix + name);
|
|
743
|
+
record[name] = target;
|
|
744
|
+
await walk(target, docURL);
|
|
745
|
+
return prefix + name;
|
|
746
|
+
};
|
|
747
|
+
const walk = async (value, docURL) => {
|
|
748
|
+
if (Array.isArray(value)) {
|
|
749
|
+
for (const item of value) await walk(item, docURL);
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
if (value === null || typeof value !== "object") return;
|
|
753
|
+
const object = value;
|
|
754
|
+
if (typeof object.$ref === "string") {
|
|
755
|
+
const ref = object.$ref;
|
|
756
|
+
if (ref.startsWith("#") && docURL === rootURL) return;
|
|
757
|
+
const absolute = ref.startsWith("#") ? docURL + ref : new URL(ref, docURL).href;
|
|
758
|
+
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}`);
|
|
759
|
+
object.$ref = await register(absolute);
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
for (const key of Object.keys(object)) await walk(object[key], docURL);
|
|
763
|
+
};
|
|
764
|
+
await walk(root, rootURL);
|
|
765
|
+
return doc;
|
|
766
|
+
}
|
|
767
|
+
/** Component section an external ref belongs to. */
|
|
768
|
+
static externalRefSection(ref, isV2) {
|
|
769
|
+
if (isV2) {
|
|
770
|
+
if (ref.includes("/parameters/")) return "parameters";
|
|
771
|
+
if (ref.includes("/responses/")) return "responses";
|
|
772
|
+
return "definitions";
|
|
773
|
+
}
|
|
774
|
+
if (ref.includes("/parameters/")) return "parameters";
|
|
775
|
+
if (ref.includes("/responses/")) return "responses";
|
|
776
|
+
if (ref.includes("/requestBodies/")) return "requestBodies";
|
|
777
|
+
return "schemas";
|
|
778
|
+
}
|
|
779
|
+
/** Local component name derived from the ref fragment or file name. */
|
|
780
|
+
static externalRefName(fragment, docURL) {
|
|
781
|
+
let name = fragment.replace(/^#/, "").split("/").filter(Boolean).map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")).at(-1) ?? "";
|
|
782
|
+
if (!name) try {
|
|
783
|
+
name = new URL(docURL).pathname.split("/").pop() ?? "";
|
|
784
|
+
} catch {
|
|
785
|
+
name = "";
|
|
786
|
+
}
|
|
787
|
+
name = name.replace(/\.(json|ya?ml)$/i, "").replace(/[^A-Za-z0-9_.-]/g, "_");
|
|
788
|
+
return name || "External";
|
|
789
|
+
}
|
|
790
|
+
/** Resolves a `#/a/b` JSON pointer inside a parsed document. */
|
|
791
|
+
static resolveJSONPointer(doc, fragment) {
|
|
792
|
+
if (!fragment) return doc;
|
|
793
|
+
const parts = fragment.replace(/^#\/?/, "").split("/").filter(Boolean).map((part) => decodeURIComponent(part).replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
794
|
+
let current = doc;
|
|
795
|
+
for (const part of parts) {
|
|
796
|
+
if (current === null || typeof current !== "object") return void 0;
|
|
797
|
+
current = current[part];
|
|
649
798
|
}
|
|
799
|
+
return current;
|
|
650
800
|
}
|
|
651
801
|
/**
|
|
652
802
|
* Determines the media type from a given media type string.
|
|
@@ -716,8 +866,72 @@ var Base = class Base {
|
|
|
716
866
|
return typeof schema === "object" && schema !== null && "$ref" in schema && typeof schema.$ref === "string";
|
|
717
867
|
}
|
|
718
868
|
};
|
|
719
|
-
|
|
720
|
-
|
|
869
|
+
// src/core/base/Adaptor.ts
|
|
870
|
+
/** `options?.name` */
|
|
871
|
+
function optionalAccess(control, name) {
|
|
872
|
+
return typescript.factory.createPropertyAccessChain(typescript.factory.createIdentifier(control.name), typescript.factory.createToken(typescript.SyntaxKind.QuestionDotToken), typescript.factory.createIdentifier(name));
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* `options?.signal && options?.timeout ? AbortSignal.any([...]) : ...`,
|
|
876
|
+
* combining a caller signal with a timeout when both are present.
|
|
877
|
+
*/
|
|
878
|
+
function fetchSignalExpression(control) {
|
|
879
|
+
const signal = optionalAccess(control, "signal");
|
|
880
|
+
const timeout = optionalAccess(control, "timeout");
|
|
881
|
+
const timeoutSignal = () => typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("AbortSignal"), typescript.factory.createIdentifier("timeout")), void 0, [timeout]);
|
|
882
|
+
const both = typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("AbortSignal"), typescript.factory.createIdentifier("any")), void 0, [typescript.factory.createArrayLiteralExpression([signal, timeoutSignal()])]);
|
|
883
|
+
return typescript.factory.createConditionalExpression(signal, typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createConditionalExpression(timeout, typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), both, typescript.factory.createToken(typescript.SyntaxKind.ColonToken), signal), typescript.factory.createToken(typescript.SyntaxKind.ColonToken), typescript.factory.createConditionalExpression(timeout, typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), timeoutSignal(), typescript.factory.createToken(typescript.SyntaxKind.ColonToken), typescript.factory.createIdentifier("undefined")));
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Header entries plus a spread of caller-supplied headers.
|
|
887
|
+
*/
|
|
888
|
+
function withRequestHeaders(entries, control) {
|
|
889
|
+
if (!control) return entries;
|
|
890
|
+
return [...entries, typescript.factory.createSpreadAssignment(optionalAccess(control, "headers"))];
|
|
891
|
+
}
|
|
892
|
+
/** `auth?.["scheme"]` */
|
|
893
|
+
function authAccess(auth, scheme) {
|
|
894
|
+
return typescript.factory.createElementAccessChain(typescript.factory.createIdentifier(auth.name), typescript.factory.createToken(typescript.SyntaxKind.QuestionDotToken), typescript.factory.createStringLiteral(scheme));
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* Header entries (conditional spreads) for auth schemes sent as headers.
|
|
898
|
+
*/
|
|
899
|
+
function authHeaderEntries(auth) {
|
|
900
|
+
return auth.injections.filter((injection) => injection.location === "header").map((injection) => {
|
|
901
|
+
const access = authAccess(auth, injection.scheme);
|
|
902
|
+
const hasValue = typescript.factory.createBinaryExpression(access, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword));
|
|
903
|
+
let value;
|
|
904
|
+
let condition = hasValue;
|
|
905
|
+
if (injection.kind === "basic") {
|
|
906
|
+
condition = typescript.factory.createBinaryExpression(access, typescript.factory.createToken(typescript.SyntaxKind.AmpersandAmpersandToken), typescript.factory.createBinaryExpression(typescript.factory.createTypeOfExpression(access), typescript.factory.createToken(typescript.SyntaxKind.EqualsEqualsEqualsToken), typescript.factory.createStringLiteral("object")));
|
|
907
|
+
const credentials = typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead(""), [typescript.factory.createTemplateSpan(typescript.factory.createPropertyAccessExpression(access, "username"), typescript.factory.createTemplateMiddle(":")), typescript.factory.createTemplateSpan(typescript.factory.createPropertyAccessExpression(access, "password"), typescript.factory.createTemplateTail(""))]);
|
|
908
|
+
value = typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead("Basic "), [typescript.factory.createTemplateSpan(typescript.factory.createCallExpression(typescript.factory.createIdentifier("btoa"), void 0, [credentials]), typescript.factory.createTemplateTail(""))]);
|
|
909
|
+
} else if (injection.kind === "bearer") value = typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead("Bearer "), [typescript.factory.createTemplateSpan(typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [access]), typescript.factory.createTemplateTail(""))]);
|
|
910
|
+
else value = typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [access]);
|
|
911
|
+
return typescript.factory.createSpreadAssignment(typescript.factory.createConditionalExpression(condition, typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createObjectLiteralExpression([typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral(injection.name), value)], false), typescript.factory.createToken(typescript.SyntaxKind.ColonToken), typescript.factory.createObjectLiteralExpression([], false)));
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* Builds a `Cookie` header value from OpenAPI cookie parameters.
|
|
916
|
+
* Undefined/null values are filtered out at runtime.
|
|
917
|
+
*/
|
|
918
|
+
function cookieHeaderExpression(parameters, auth) {
|
|
919
|
+
const entries = parameters.filter((p) => p.in === "cookie").map((parameter) => {
|
|
920
|
+
const id = typescript.factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
921
|
+
return typescript.factory.createConditionalExpression(typescript.factory.createBinaryExpression(id, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword)), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead(`${parameter.name}=`), [typescript.factory.createTemplateSpan(typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [id])]), typescript.factory.createTemplateTail(""))]), typescript.factory.createToken(typescript.SyntaxKind.ColonToken), typescript.factory.createStringLiteral(""));
|
|
922
|
+
});
|
|
923
|
+
const authEntries = auth ? auth.injections.filter((injection) => injection.location === "cookie").map((injection) => {
|
|
924
|
+
const access = authAccess(auth, injection.scheme);
|
|
925
|
+
return typescript.factory.createConditionalExpression(typescript.factory.createBinaryExpression(access, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword)), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead(`${injection.name}=`), [typescript.factory.createTemplateSpan(typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [access])]), typescript.factory.createTemplateTail(""))]), typescript.factory.createToken(typescript.SyntaxKind.ColonToken), typescript.factory.createStringLiteral(""));
|
|
926
|
+
}) : [];
|
|
927
|
+
return typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createArrayLiteralExpression([...entries, ...authEntries], true), typescript.factory.createIdentifier("filter")), void 0, [typescript.factory.createIdentifier("Boolean")]), typescript.factory.createIdentifier("join")), void 0, [typescript.factory.createStringLiteral("; ")]);
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Base adapter for tool
|
|
931
|
+
* This abstract class serves as the foundation for implementing adapters for different code generation tools
|
|
932
|
+
*/
|
|
933
|
+
var Adapter = class {};
|
|
934
|
+
// src/core/base/Provider.ts
|
|
721
935
|
/**
|
|
722
936
|
* Abstract Provider Class.
|
|
723
937
|
*
|
|
@@ -761,6 +975,8 @@ var Provider = class {
|
|
|
761
975
|
responses = {};
|
|
762
976
|
/** collection of request bodies indexed by name */
|
|
763
977
|
requestBodies = {};
|
|
978
|
+
/** security schemes declared by the document */
|
|
979
|
+
securitySchemes = {};
|
|
764
980
|
/** collection of API endpoints (operations) indexed by path */
|
|
765
981
|
apis = {};
|
|
766
982
|
/** URL for fetching API documentation */
|
|
@@ -784,17 +1000,17 @@ var Provider = class {
|
|
|
784
1000
|
this.output = initOptions.output ?? ".";
|
|
785
1001
|
this.requestOptions = initOptions.requestOptions ?? {};
|
|
786
1002
|
this.importClientSource = initOptions.importClientSource ?? "";
|
|
787
|
-
const { enums, schemas, requestBodies, responses, parameters, apis } = this.parse(doc);
|
|
1003
|
+
const { enums, schemas, requestBodies, responses, parameters, securitySchemes, apis } = this.parse(doc);
|
|
788
1004
|
this.enums = enums;
|
|
789
1005
|
this.schemas = schemas;
|
|
790
1006
|
this.responses = responses;
|
|
791
1007
|
this.parameters = parameters;
|
|
792
1008
|
this.requestBodies = requestBodies;
|
|
1009
|
+
this.securitySchemes = securitySchemes;
|
|
793
1010
|
this.apis = apis;
|
|
794
1011
|
}
|
|
795
1012
|
};
|
|
796
|
-
|
|
797
|
-
//#region src/core/generator/naming.ts
|
|
1013
|
+
// src/core/generator/naming.ts
|
|
798
1014
|
/**
|
|
799
1015
|
* Create a per-generation unique-name resolver.
|
|
800
1016
|
*
|
|
@@ -817,8 +1033,7 @@ const createUniqueNameResolver = () => {
|
|
|
817
1033
|
return next === 1 ? name : `${name}${next}`;
|
|
818
1034
|
};
|
|
819
1035
|
};
|
|
820
|
-
|
|
821
|
-
//#region src/core/generator/index.ts
|
|
1036
|
+
// src/core/generator/index.ts
|
|
822
1037
|
var Generator = class Generator {
|
|
823
1038
|
/**
|
|
824
1039
|
* Converts an array of TypeScript statements into a formatted string of code.
|
|
@@ -834,9 +1049,10 @@ var Generator = class Generator {
|
|
|
834
1049
|
}
|
|
835
1050
|
static async write(code, filepath) {
|
|
836
1051
|
try {
|
|
1052
|
+
await (0, node_fs_promises.mkdir)((0, node_path.dirname)(filepath), { recursive: true });
|
|
837
1053
|
await (0, node_fs_promises.writeFile)(filepath, code);
|
|
838
1054
|
} catch (error) {
|
|
839
|
-
|
|
1055
|
+
throw createErrors.writeFailed(filepath, error instanceof Error ? error : new Error(String(error)));
|
|
840
1056
|
}
|
|
841
1057
|
}
|
|
842
1058
|
/**
|
|
@@ -848,22 +1064,84 @@ var Generator = class Generator {
|
|
|
848
1064
|
* @param basePath - Optional base path to prepend (default: "").
|
|
849
1065
|
* @returns A TypeScript template expressi
|
|
850
1066
|
*/
|
|
851
|
-
static toUrlTemplate(path, parameters, basePath = "") {
|
|
1067
|
+
static toUrlTemplate(path, parameters, basePath = "", auth) {
|
|
1068
|
+
const pathExpression = Generator.toPathTemplate(path, basePath);
|
|
852
1069
|
const queryParameters = parameters.filter((p) => p.in === "query");
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
1070
|
+
const hasAuthQuery = auth?.injections.some((injection) => injection.location === "query");
|
|
1071
|
+
if (queryParameters.length === 0 && !hasAuthQuery) return pathExpression;
|
|
1072
|
+
return typescript.factory.createBinaryExpression(pathExpression, typescript.factory.createToken(typescript.SyntaxKind.PlusToken), Generator.toQueryStringExpression(queryParameters, auth));
|
|
1073
|
+
}
|
|
1074
|
+
/**
|
|
1075
|
+
* Builds the path part of a URL, encoding every `{param}` interpolation.
|
|
1076
|
+
*/
|
|
1077
|
+
static toPathTemplate(path, basePath) {
|
|
857
1078
|
const pathSegments = path.replaceAll("{", "${").split("$").filter(Boolean);
|
|
858
1079
|
if (pathSegments.length === 1) return typescript.factory.createNoSubstitutionTemplateLiteral(basePath + path);
|
|
859
1080
|
return typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead(basePath + pathSegments[0]), pathSegments.slice(1).map((segment, index) => {
|
|
860
1081
|
const match = /^{(.+)}(.+)?/gm.exec(segment);
|
|
861
1082
|
const isLastSegment = index === pathSegments.length - 2;
|
|
862
1083
|
if (!match) throw new Error(`Invalid path segment: ${segment}`);
|
|
863
|
-
return typescript.factory.createTemplateSpan(typescript.factory.createIdentifier(match[1]), !isLastSegment ? typescript.factory.createTemplateMiddle(match[2]) : typescript.factory.createTemplateTail(match[2] || ""));
|
|
1084
|
+
return typescript.factory.createTemplateSpan(typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createIdentifier(Base.toIdentifier(match[1]))])]), !isLastSegment ? typescript.factory.createTemplateMiddle(match[2]) : typescript.factory.createTemplateTail(match[2] || ""));
|
|
864
1085
|
}));
|
|
865
1086
|
}
|
|
866
1087
|
/**
|
|
1088
|
+
* Emits an IIFE that builds a query string, omitting undefined/null
|
|
1089
|
+
* values and honouring array `explode` / delimiter styles.
|
|
1090
|
+
*/
|
|
1091
|
+
static toQueryStringExpression(parameters, auth) {
|
|
1092
|
+
const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
|
|
1093
|
+
const unique = (base) => {
|
|
1094
|
+
let name = base;
|
|
1095
|
+
let suffix = 2;
|
|
1096
|
+
while (taken.has(name)) name = `${base}${suffix++}`;
|
|
1097
|
+
taken.add(name);
|
|
1098
|
+
return name;
|
|
1099
|
+
};
|
|
1100
|
+
const qName = unique("q");
|
|
1101
|
+
const vName = unique("v");
|
|
1102
|
+
const sName = unique("s");
|
|
1103
|
+
const statements = [typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier(qName), void 0, void 0, typescript.factory.createNewExpression(typescript.factory.createIdentifier("URLSearchParams"), void 0, []))], typescript.NodeFlags.Const))];
|
|
1104
|
+
const append = (name, value) => typescript.factory.createExpressionStatement(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier(qName), typescript.factory.createIdentifier("append")), void 0, [typeof name === "string" ? typescript.factory.createStringLiteral(name) : name, value]));
|
|
1105
|
+
const stringify = (value) => typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [value]);
|
|
1106
|
+
const isNotNull = (value) => typescript.factory.createBinaryExpression(value, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword));
|
|
1107
|
+
for (const parameter of parameters) {
|
|
1108
|
+
const id = typescript.factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
1109
|
+
const isArray = parameter.schema?.type === "array";
|
|
1110
|
+
if (parameter.style === "deepObject" && !isArray) {
|
|
1111
|
+
const addName = unique("addDeepObject");
|
|
1112
|
+
const prefix = typescript.factory.createIdentifier("prefix");
|
|
1113
|
+
const value = typescript.factory.createIdentifier("value");
|
|
1114
|
+
const key = typescript.factory.createIdentifier("k");
|
|
1115
|
+
const entry = typescript.factory.createIdentifier("v");
|
|
1116
|
+
const path = typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead(""), [typescript.factory.createTemplateSpan(prefix, typescript.factory.createTemplateMiddle("[")), typescript.factory.createTemplateSpan(key, typescript.factory.createTemplateTail("]"))]);
|
|
1117
|
+
const recurse = typescript.factory.createCallExpression(typescript.factory.createIdentifier(addName), void 0, [path, typescript.factory.createAsExpression(entry, typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [typescript.factory.createToken(typescript.SyntaxKind.StringKeyword), typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword)]))]);
|
|
1118
|
+
const forOf = typescript.factory.createForOfStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createArrayBindingPattern([typescript.factory.createBindingElement(void 0, void 0, key), typescript.factory.createBindingElement(void 0, void 0, entry)]))], typescript.NodeFlags.Const), typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("Object"), typescript.factory.createIdentifier("entries")), void 0, [value]), typescript.factory.createBlock([typescript.factory.createIfStatement(typescript.factory.createBinaryExpression(entry, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword)), typescript.factory.createBlock([typescript.factory.createIfStatement(typescript.factory.createBinaryExpression(typescript.factory.createTypeOfExpression(entry), typescript.factory.createToken(typescript.SyntaxKind.EqualsEqualsEqualsToken), typescript.factory.createStringLiteral("object")), typescript.factory.createExpressionStatement(recurse), append(path, stringify(entry)))], true))], true));
|
|
1119
|
+
const declaration = typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier(addName), void 0, void 0, typescript.factory.createArrowFunction(void 0, void 0, [typescript.factory.createParameterDeclaration(void 0, void 0, prefix, void 0, typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.StringKeyword)), typescript.factory.createParameterDeclaration(void 0, void 0, value, void 0, typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [typescript.factory.createToken(typescript.SyntaxKind.StringKeyword), typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword)]))], void 0, typescript.factory.createToken(typescript.SyntaxKind.EqualsGreaterThanToken), typescript.factory.createBlock([forOf], true)))], typescript.NodeFlags.Const));
|
|
1120
|
+
const invoke = typescript.factory.createExpressionStatement(typescript.factory.createCallExpression(typescript.factory.createIdentifier(addName), void 0, [typescript.factory.createStringLiteral(parameter.name), typescript.factory.createAsExpression(id, typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [typescript.factory.createToken(typescript.SyntaxKind.StringKeyword), typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword)]))]));
|
|
1121
|
+
statements.push(parameter.required ? typescript.factory.createBlock([declaration, invoke], true) : typescript.factory.createIfStatement(isNotNull(id), typescript.factory.createBlock([declaration, invoke], true)));
|
|
1122
|
+
continue;
|
|
1123
|
+
}
|
|
1124
|
+
if (isArray) {
|
|
1125
|
+
if (parameter.explode ?? (parameter.style === void 0 || parameter.style === "form")) {
|
|
1126
|
+
statements.push(typescript.factory.createForOfStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier(vName), void 0, void 0, void 0)], typescript.NodeFlags.Const), typescript.factory.createBinaryExpression(id, typescript.factory.createToken(typescript.SyntaxKind.QuestionQuestionToken), typescript.factory.createArrayLiteralExpression([])), typescript.factory.createBlock([append(parameter.name, stringify(typescript.factory.createIdentifier(vName)))], true)));
|
|
1127
|
+
continue;
|
|
1128
|
+
}
|
|
1129
|
+
const separator = parameter.style === "spaceDelimited" ? " " : parameter.style === "pipeDelimited" ? "|" : ",";
|
|
1130
|
+
const join = typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(id, typescript.factory.createIdentifier("join")), void 0, [typescript.factory.createStringLiteral(separator)]);
|
|
1131
|
+
statements.push(typescript.factory.createIfStatement(isNotNull(id), typescript.factory.createBlock([append(parameter.name, join)], true)));
|
|
1132
|
+
continue;
|
|
1133
|
+
}
|
|
1134
|
+
const statement = append(parameter.name, stringify(id));
|
|
1135
|
+
statements.push(parameter.required ? statement : typescript.factory.createIfStatement(isNotNull(id), typescript.factory.createBlock([statement], true)));
|
|
1136
|
+
}
|
|
1137
|
+
if (auth) for (const injection of auth.injections.filter((item) => item.location === "query")) {
|
|
1138
|
+
const access = authAccess(auth, injection.scheme);
|
|
1139
|
+
statements.push(typescript.factory.createIfStatement(typescript.factory.createBinaryExpression(access, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword)), typescript.factory.createBlock([append(injection.name, stringify(access))], true)));
|
|
1140
|
+
}
|
|
1141
|
+
statements.push(typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier(sName), void 0, void 0, typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier(qName), typescript.factory.createIdentifier("toString")), void 0, []))], typescript.NodeFlags.Const)), typescript.factory.createReturnStatement(typescript.factory.createConditionalExpression(typescript.factory.createIdentifier(sName), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead("?"), [typescript.factory.createTemplateSpan(typescript.factory.createIdentifier(sName), typescript.factory.createTemplateTail(""))]), typescript.factory.createToken(typescript.SyntaxKind.ColonToken), typescript.factory.createStringLiteral(""))));
|
|
1142
|
+
return typescript.factory.createCallExpression(typescript.factory.createParenthesizedExpression(typescript.factory.createArrowFunction(void 0, void 0, [], void 0, typescript.factory.createToken(typescript.SyntaxKind.EqualsGreaterThanToken), typescript.factory.createBlock(statements, true))), void 0, []);
|
|
1143
|
+
}
|
|
1144
|
+
/**
|
|
867
1145
|
* Adds synthetic comments to a TypeScript AST node.
|
|
868
1146
|
*
|
|
869
1147
|
* @param node - The target AST node.
|
|
@@ -880,7 +1158,7 @@ var Generator = class Generator {
|
|
|
880
1158
|
if (comment.tag) return `* @${comment.tag} ${comment.comment ?? ""}`;
|
|
881
1159
|
return `* ${comment.comment}`;
|
|
882
1160
|
};
|
|
883
|
-
const formattedComments = comments.map(formatComment).join("\n").trim() + "\n";
|
|
1161
|
+
const formattedComments = comments.map(formatComment).join("\n").replaceAll("*/", "*\\/").trim() + "\n";
|
|
884
1162
|
(0, typescript.addSyntheticLeadingComment)(node, typescript.SyntaxKind.MultiLineCommentTrivia, formattedComments, true);
|
|
885
1163
|
}
|
|
886
1164
|
/**
|
|
@@ -897,6 +1175,16 @@ var Generator = class Generator {
|
|
|
897
1175
|
const nonArraySchema = schema;
|
|
898
1176
|
return nonArraySchema.format === "blob" || nonArraySchema.format === "binary" || nonArraySchema.type === "file";
|
|
899
1177
|
}
|
|
1178
|
+
/** Whether a schema is a primitive text part (not binary, ref, or object). */
|
|
1179
|
+
static isTextSchema(schema) {
|
|
1180
|
+
if (!schema || schema.isRef) return false;
|
|
1181
|
+
if (Generator.isBinarySchema(schema)) return false;
|
|
1182
|
+
if (schema.type === "array") {
|
|
1183
|
+
const items = schema.items;
|
|
1184
|
+
return items ? Generator.isTextSchema(items) : false;
|
|
1185
|
+
}
|
|
1186
|
+
return schema.type === "string" || schema.type === "integer" || schema.type === "number" || schema.type === "boolean";
|
|
1187
|
+
}
|
|
900
1188
|
static schemaToTypeString(schema) {
|
|
901
1189
|
if (schema.type === "array") {
|
|
902
1190
|
const arraySchema = schema;
|
|
@@ -915,7 +1203,7 @@ var Generator = class Generator {
|
|
|
915
1203
|
static generateParamTags(parameters, requestBody) {
|
|
916
1204
|
const tags = [];
|
|
917
1205
|
for (const p of parameters) {
|
|
918
|
-
const paramName = Base.
|
|
1206
|
+
const paramName = Base.toIdentifier(p.name);
|
|
919
1207
|
let paramType = "unknown";
|
|
920
1208
|
if (p.schema) paramType = Generator.schemaToTypeString(p.schema);
|
|
921
1209
|
const isOptional = p.required === false;
|
|
@@ -924,7 +1212,7 @@ var Generator = class Generator {
|
|
|
924
1212
|
tag: "param",
|
|
925
1213
|
paramName,
|
|
926
1214
|
type: `${paramType}${isOptional ? " | undefined" : ""}`,
|
|
927
|
-
comment: `${inPrefix}${p.description ?? ""}`
|
|
1215
|
+
comment: `${inPrefix}${p.description?.trim() ?? ""}`
|
|
928
1216
|
});
|
|
929
1217
|
}
|
|
930
1218
|
if (requestBody?.schema && "properties" in requestBody.schema) {
|
|
@@ -939,7 +1227,7 @@ var Generator = class Generator {
|
|
|
939
1227
|
tag: "param",
|
|
940
1228
|
paramName,
|
|
941
1229
|
type: `${paramType}${isOptional ? " | undefined" : ""}`,
|
|
942
|
-
comment: schema.description ?? ""
|
|
1230
|
+
comment: schema.description?.trim() ?? ""
|
|
943
1231
|
});
|
|
944
1232
|
}
|
|
945
1233
|
}
|
|
@@ -948,8 +1236,47 @@ var Generator = class Generator {
|
|
|
948
1236
|
static toRequestBodyTypeNode(schema) {
|
|
949
1237
|
return typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier("req"), void 0, Generator.toTypeNode(schema));
|
|
950
1238
|
}
|
|
1239
|
+
/**
|
|
1240
|
+
* Narrows a `oneOf` member with its discriminator mapping value:
|
|
1241
|
+
* `Cat & { petType: 'cat' }`.
|
|
1242
|
+
*/
|
|
1243
|
+
static discriminatedMember(schema, discriminator) {
|
|
1244
|
+
const node = Generator.toTypeNode(schema);
|
|
1245
|
+
const ref = schema.ref;
|
|
1246
|
+
if (!ref) return node;
|
|
1247
|
+
const name = Base.ref2name(ref);
|
|
1248
|
+
const value = Object.entries(discriminator.mapping ?? {}).find(([, target]) => Base.ref2name(target) === name)?.[0];
|
|
1249
|
+
if (value === void 0) return node;
|
|
1250
|
+
return typescript.factory.createIntersectionTypeNode([node, typescript.factory.createTypeLiteralNode([typescript.factory.createPropertySignature(void 0, typescript.factory.createStringLiteral(discriminator.propertyName), void 0, typescript.factory.createLiteralTypeNode(typescript.factory.createStringLiteral(value)))])]);
|
|
1251
|
+
}
|
|
951
1252
|
static toTypeNode(schema) {
|
|
1253
|
+
if ("const" in schema && schema.const !== void 0) return Generator.toLiteralTypeNode(schema.const);
|
|
1254
|
+
const base = Generator.toTypeNodeInner(schema);
|
|
1255
|
+
if (schema.nullable) return typescript.factory.createUnionTypeNode([base, typescript.factory.createLiteralTypeNode(typescript.factory.createNull())]);
|
|
1256
|
+
return base;
|
|
1257
|
+
}
|
|
1258
|
+
static toLiteralTypeNode(value) {
|
|
1259
|
+
if (typeof value === "string") return typescript.factory.createLiteralTypeNode(typescript.factory.createStringLiteral(value));
|
|
1260
|
+
if (typeof value === "number") return typescript.factory.createLiteralTypeNode(typescript.factory.createNumericLiteral(value));
|
|
1261
|
+
return typescript.factory.createLiteralTypeNode(value ? typescript.factory.createTrue() : typescript.factory.createFalse());
|
|
1262
|
+
}
|
|
1263
|
+
static primitiveTypeNode(type) {
|
|
1264
|
+
switch (type) {
|
|
1265
|
+
case "string": return typescript.factory.createToken(typescript.SyntaxKind.StringKeyword);
|
|
1266
|
+
case "integer":
|
|
1267
|
+
case "number": return typescript.factory.createToken(typescript.SyntaxKind.NumberKeyword);
|
|
1268
|
+
case "boolean": return typescript.factory.createToken(typescript.SyntaxKind.BooleanKeyword);
|
|
1269
|
+
case "object": return typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [typescript.factory.createToken(typescript.SyntaxKind.StringKeyword), typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword)]);
|
|
1270
|
+
default: return typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier(Base.upperCamelCase(type)));
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
static toTypeNodeInner(schema) {
|
|
952
1274
|
const { type, ref } = schema;
|
|
1275
|
+
const unionTypes = schema.types;
|
|
1276
|
+
if (unionTypes && unionTypes.length > 0) {
|
|
1277
|
+
const nodes = Generator.deduplicateTypes(unionTypes.map((name) => Generator.primitiveTypeNode(name)));
|
|
1278
|
+
return nodes.length === 1 ? nodes[0] : typescript.factory.createUnionTypeNode(nodes);
|
|
1279
|
+
}
|
|
953
1280
|
if (ref) {
|
|
954
1281
|
const identify = Base.ref2name(ref);
|
|
955
1282
|
return typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier(identify === "unknown" ? identify : Base.upperCamelCase(identify)));
|
|
@@ -961,20 +1288,28 @@ var Generator = class Generator {
|
|
|
961
1288
|
}
|
|
962
1289
|
case "object": {
|
|
963
1290
|
const propsCount = Object.keys(schema.properties ?? {}).length;
|
|
964
|
-
|
|
1291
|
+
const additional = schema.additionalProperties;
|
|
1292
|
+
const additionalValue = additional && additional !== true ? Generator.toTypeNode(additional) : typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword);
|
|
1293
|
+
if (!schema.properties || propsCount === 0) return typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [typescript.factory.createToken(typescript.SyntaxKind.StringKeyword), additionalValue]);
|
|
965
1294
|
const props = Object.keys(schema.properties);
|
|
966
1295
|
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
967
|
-
|
|
1296
|
+
const literal = typescript.factory.createTypeLiteralNode(props.map((propKey) => {
|
|
968
1297
|
const propSchema = schema.properties[propKey];
|
|
969
1298
|
return typescript.factory.createPropertySignature(void 0, typescript.factory.createStringLiteral(propKey), required.includes(propKey) ? void 0 : typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), Generator.toTypeNode(propSchema));
|
|
970
1299
|
}));
|
|
1300
|
+
const additionalProps = schema.additionalProperties;
|
|
1301
|
+
if (additionalProps === void 0 || additionalProps === false) return literal;
|
|
1302
|
+
return typescript.factory.createIntersectionTypeNode([literal, typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [typescript.factory.createToken(typescript.SyntaxKind.StringKeyword), additionalProps === true ? typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword) : Generator.toTypeNode(additionalProps)])]);
|
|
971
1303
|
}
|
|
972
1304
|
case "integer":
|
|
973
1305
|
case "number":
|
|
974
|
-
if (schema.enum)
|
|
1306
|
+
if (schema.enum) {
|
|
1307
|
+
const values = schema.enum.filter((value) => typeof value === "number");
|
|
1308
|
+
if (values.length > 0) return typescript.factory.createUnionTypeNode(values.map((value) => typescript.factory.createLiteralTypeNode(typescript.factory.createNumericLiteral(value))));
|
|
1309
|
+
}
|
|
975
1310
|
return typescript.factory.createToken(typescript.SyntaxKind.NumberKeyword);
|
|
976
1311
|
case "boolean": return typescript.factory.createToken(typescript.SyntaxKind.BooleanKeyword);
|
|
977
|
-
case "file": return typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Blob"));
|
|
1312
|
+
case "file": return typescript.factory.createTypeReferenceNode(typescript.factory.createQualifiedName(typescript.factory.createIdentifier("globalThis"), typescript.factory.createIdentifier("Blob")));
|
|
978
1313
|
default: {
|
|
979
1314
|
const { format, oneOf, allOf, anyOf, type, enum: enum_ } = schema;
|
|
980
1315
|
switch (format) {
|
|
@@ -982,12 +1317,16 @@ var Generator = class Generator {
|
|
|
982
1317
|
case "string": return typescript.factory.createToken(typescript.SyntaxKind.StringKeyword);
|
|
983
1318
|
case "boolean": return typescript.factory.createToken(typescript.SyntaxKind.BooleanKeyword);
|
|
984
1319
|
case "blob":
|
|
985
|
-
case "binary": return typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Blob"));
|
|
986
|
-
|
|
1320
|
+
case "binary": return typescript.factory.createTypeReferenceNode(typescript.factory.createQualifiedName(typescript.factory.createIdentifier("globalThis"), typescript.factory.createIdentifier("Blob")));
|
|
1321
|
+
}
|
|
1322
|
+
if (enum_) {
|
|
1323
|
+
const values = enum_.filter((value) => typeof value === "string");
|
|
1324
|
+
if (values.length > 0) return typescript.factory.createUnionTypeNode(values.map((value) => typescript.factory.createLiteralTypeNode(typescript.factory.createStringLiteral(value))));
|
|
987
1325
|
}
|
|
988
|
-
if (enum_) return typescript.factory.createUnionTypeNode(enum_.map((e) => typescript.factory.createLiteralTypeNode(typescript.factory.createStringLiteral(e))));
|
|
989
1326
|
if (type === "string") return typescript.factory.createToken(typescript.SyntaxKind.StringKeyword);
|
|
990
1327
|
if (oneOf) {
|
|
1328
|
+
const discriminator = schema.discriminator;
|
|
1329
|
+
if (discriminator?.mapping) return typescript.factory.createUnionTypeNode(Generator.deduplicateTypes(oneOf.map((member) => Generator.discriminatedMember(member, discriminator))));
|
|
991
1330
|
const uniqueTypes = Generator.deduplicateTypes(oneOf.map((s) => Generator.toTypeNode(s)));
|
|
992
1331
|
return typescript.factory.createUnionTypeNode(uniqueTypes);
|
|
993
1332
|
}
|
|
@@ -1001,6 +1340,12 @@ var Generator = class Generator {
|
|
|
1001
1340
|
}
|
|
1002
1341
|
return typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword);
|
|
1003
1342
|
}
|
|
1343
|
+
static toResponsesTypeNode(responses) {
|
|
1344
|
+
return typescript.factory.createTypeLiteralNode(Object.entries(responses).map(([code, mediaTypes]) => {
|
|
1345
|
+
const schema = mediaTypes[0]?.schema;
|
|
1346
|
+
return typescript.factory.createPropertySignature(void 0, typescript.factory.createStringLiteral(code), void 0, schema ? Generator.toTypeNode(schema) : typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword));
|
|
1347
|
+
}));
|
|
1348
|
+
}
|
|
1004
1349
|
static deduplicateTypes(types) {
|
|
1005
1350
|
const seen = /* @__PURE__ */ new Set();
|
|
1006
1351
|
const unique = [];
|
|
@@ -1022,30 +1367,41 @@ var Generator = class Generator {
|
|
|
1022
1367
|
const refParameters = [];
|
|
1023
1368
|
for (const parameter of parameters) if (parameter.ref) {
|
|
1024
1369
|
const refName = Base.ref2name(parameter.ref);
|
|
1025
|
-
refParameters.push(typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier(Base.
|
|
1370
|
+
refParameters.push(typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier(Base.toIdentifier(refName)), void 0, typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier(Base.upperCamelCase(Base.normalize(refName)))), void 0));
|
|
1026
1371
|
} else {
|
|
1027
1372
|
const { name, schema, required } = parameter;
|
|
1028
|
-
|
|
1029
|
-
|
|
1373
|
+
const key = Base.camelCase(Base.normalize(name));
|
|
1374
|
+
const id = Base.toIdentifier(name);
|
|
1375
|
+
objectElements.push(typescript.factory.createBindingElement(void 0, key === id ? void 0 : typescript.factory.createIdentifier(key), typescript.factory.createIdentifier(id)));
|
|
1376
|
+
typeObjectElements.push(typescript.factory.createPropertySignature([], typescript.factory.createIdentifier(key), required ? void 0 : typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), !schema ? typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword) : Generator.toTypeNode(schema)));
|
|
1030
1377
|
}
|
|
1031
1378
|
if (objectElements.length > 0) return [typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createObjectBindingPattern(objectElements), void 0, typescript.factory.createTypeLiteralNode(typeObjectElements), void 0), ...refParameters];
|
|
1032
1379
|
return refParameters;
|
|
1033
1380
|
}
|
|
1381
|
+
/** Property keys listed in a parent schema's `required` array. */
|
|
1382
|
+
static requiredPropertyKeys(schema) {
|
|
1383
|
+
return schema && Array.isArray(schema.required) ? schema.required : [];
|
|
1384
|
+
}
|
|
1034
1385
|
static toFormDataStatement(parameters, requestBody) {
|
|
1035
1386
|
const statements = [];
|
|
1387
|
+
const requiredKeys = Generator.requiredPropertyKeys(requestBody);
|
|
1036
1388
|
const fdDeclaration = typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier("fd"), void 0, void 0, typescript.factory.createNewExpression(typescript.factory.createIdentifier("FormData"), void 0, []))], typescript.NodeFlags.Const));
|
|
1037
1389
|
statements.push(fdDeclaration);
|
|
1038
1390
|
parameters.forEach((parameter) => {
|
|
1039
|
-
|
|
1391
|
+
const id = typescript.factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
1392
|
+
statements.push(typescript.factory.createExpressionStatement(typescript.factory.createBinaryExpression(id, typescript.factory.createToken(typescript.SyntaxKind.AmpersandAmpersandToken), typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("fd"), typescript.factory.createIdentifier("append")), void 0, [typescript.factory.createStringLiteral(parameter.name), id]))));
|
|
1040
1393
|
});
|
|
1041
1394
|
if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) Object.keys(requestBody.properties).forEach((key) => {
|
|
1042
1395
|
const schemaByKey = requestBody.properties[key];
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
typescript.factory.
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1396
|
+
const accessor = typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key));
|
|
1397
|
+
if (schemaByKey.type === "array" && Generator.isBinarySchema(schemaByKey)) {
|
|
1398
|
+
const loop = typescript.factory.createForOfStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration("file")], typescript.NodeFlags.Const), accessor, typescript.factory.createBlock([typescript.factory.createExpressionStatement(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("fd"), typescript.factory.createIdentifier("append")), [], [
|
|
1399
|
+
typescript.factory.createStringLiteral(key),
|
|
1400
|
+
typescript.factory.createIdentifier("file"),
|
|
1401
|
+
typescript.factory.createPropertyAccessExpression(typescript.factory.createAsExpression(typescript.factory.createIdentifier("file"), typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("File"), void 0)), typescript.factory.createIdentifier("name"))
|
|
1402
|
+
]))]));
|
|
1403
|
+
statements.push(requiredKeys.includes(key) ? loop : typescript.factory.createIfStatement(typescript.factory.createBinaryExpression(accessor, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword)), typescript.factory.createBlock([loop], true)));
|
|
1404
|
+
} else if (requiredKeys.includes(key)) statements.push(typescript.factory.createExpressionStatement(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("fd"), typescript.factory.createIdentifier("append")), void 0, [typescript.factory.createStringLiteral(key), schemaByKey.type === "string" || Generator.isBinarySchema(schemaByKey) || schemaByKey.isRef ? typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key)) : schemaByKey.type === "array" || schemaByKey.type === "object" ? typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("JSON"), typescript.factory.createIdentifier("stringify")), void 0, [typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key))]) : typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key))])])));
|
|
1049
1405
|
else statements.push(typescript.factory.createExpressionStatement(typescript.factory.createBinaryExpression(typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key)), typescript.factory.createToken(typescript.SyntaxKind.AmpersandAmpersandToken), typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("fd"), typescript.factory.createIdentifier("append")), void 0, [typescript.factory.createStringLiteral(key), schemaByKey.type === "string" || Generator.isBinarySchema(schemaByKey) || schemaByKey.isRef ? typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key)) : schemaByKey.type === "array" || schemaByKey.type === "object" ? typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("JSON"), typescript.factory.createIdentifier("stringify")), void 0, [typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key))]) : typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key))])]))));
|
|
1050
1406
|
});
|
|
1051
1407
|
return statements;
|
|
@@ -1065,17 +1421,26 @@ var Generator = class Generator {
|
|
|
1065
1421
|
const spDeclaration = typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier("sp"), void 0, void 0, typescript.factory.createNewExpression(typescript.factory.createIdentifier("URLSearchParams"), void 0, []))], typescript.NodeFlags.Const));
|
|
1066
1422
|
statements.push(spDeclaration);
|
|
1067
1423
|
const appendValue = (key, valueExpr) => typescript.factory.createExpressionStatement(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("sp"), typescript.factory.createIdentifier("append")), void 0, [typescript.factory.createStringLiteral(key), valueExpr]));
|
|
1068
|
-
if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0)
|
|
1069
|
-
const
|
|
1070
|
-
const
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1424
|
+
if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) {
|
|
1425
|
+
const requiredKeys = Generator.requiredPropertyKeys(requestBody);
|
|
1426
|
+
for (const key of Object.keys(requestBody.properties)) {
|
|
1427
|
+
const fieldSchema = requestBody.properties[key];
|
|
1428
|
+
const required = requiredKeys.includes(key);
|
|
1429
|
+
const accessor = typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key));
|
|
1430
|
+
const nonNull = typescript.factory.createBinaryExpression(accessor, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword));
|
|
1431
|
+
if (fieldSchema.type === "array") {
|
|
1432
|
+
const item = typescript.factory.createIdentifier("item");
|
|
1433
|
+
const loop = typescript.factory.createForOfStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(item)], typescript.NodeFlags.Const), accessor, typescript.factory.createBlock([appendValue(key, Generator.toFormDataCompatibleString(item, fieldSchema.items))], true));
|
|
1434
|
+
statements.push(required ? loop : typescript.factory.createIfStatement(nonNull, typescript.factory.createBlock([loop], true)));
|
|
1435
|
+
continue;
|
|
1436
|
+
}
|
|
1437
|
+
const append = appendValue(key, Generator.toFormDataCompatibleString(accessor, fieldSchema));
|
|
1438
|
+
statements.push(required ? append : typescript.factory.createIfStatement(nonNull, typescript.factory.createBlock([append], true)));
|
|
1439
|
+
}
|
|
1075
1440
|
}
|
|
1076
1441
|
for (const parameter of parameters) {
|
|
1077
1442
|
if (parameter.in === "header" || parameter.in === "cookie" || parameter.in === "path") continue;
|
|
1078
|
-
const accessor = typescript.factory.createIdentifier(Base.
|
|
1443
|
+
const accessor = typescript.factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
1079
1444
|
statements.push(typescript.factory.createIfStatement(typescript.factory.createBinaryExpression(accessor, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword)), typescript.factory.createBlock([appendValue(parameter.name, Generator.toFormDataCompatibleString(accessor))], true)));
|
|
1080
1445
|
}
|
|
1081
1446
|
return statements;
|
|
@@ -1089,7 +1454,7 @@ var Generator = class Generator {
|
|
|
1089
1454
|
if (schema && (schema.type === "object" || schema.type === "array")) return typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("JSON"), typescript.factory.createIdentifier("stringify")), void 0, [expr]);
|
|
1090
1455
|
return typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [expr]);
|
|
1091
1456
|
}
|
|
1092
|
-
static bodyBlock(uri, method, parameters, requestBody, response, adapter) {
|
|
1457
|
+
static bodyBlock(uri, method, parameters, requestBody, response, adapter, errorMode, auth, requestControl) {
|
|
1093
1458
|
const shouldParseResponseToJSON = "application/json" === response?.type;
|
|
1094
1459
|
const parametersShouldPutInFormData = parameters.filter((p) => p.in === "formData" || p.schema && Generator.isBinarySchema(p.schema));
|
|
1095
1460
|
const parametersShouldNotPutInFormData = parameters.filter((p) => !parametersShouldPutInFormData.includes(p));
|
|
@@ -1098,10 +1463,12 @@ var Generator = class Generator {
|
|
|
1098
1463
|
const hasBinaryInParameters = parameters.some((p) => p?.schema && Generator.isBinarySchema(p.schema));
|
|
1099
1464
|
const mediaType = (requestBody?.type ?? "").toLowerCase().split(";")[0]?.trim();
|
|
1100
1465
|
const requestSchemaIsBinary = requestBody?.schema && Generator.isBinarySchema(requestBody.schema);
|
|
1466
|
+
const multipartParts = requestBody?.schema && "properties" in requestBody.schema && requestBody.schema.properties ? Object.values(requestBody.schema.properties) : [];
|
|
1467
|
+
const hasOnlyTextParts = multipartParts.length > 0 && multipartParts.every((part) => Generator.isTextSchema(part));
|
|
1101
1468
|
let bodyKind = "none";
|
|
1102
1469
|
let bodyContentType;
|
|
1103
1470
|
if (mediaType === "multipart/form-data") {
|
|
1104
|
-
if (hasBinaryInParameters || isRequestBodyContainsBinary || parametersShouldPutInFormData.length > 0) bodyKind = "form-data";
|
|
1471
|
+
if (hasBinaryInParameters || isRequestBodyContainsBinary || hasOnlyTextParts || parametersShouldPutInFormData.length > 0) bodyKind = "form-data";
|
|
1105
1472
|
} else if (mediaType === "application/x-www-form-urlencoded") {
|
|
1106
1473
|
bodyKind = "urlencoded";
|
|
1107
1474
|
bodyContentType = "application/x-www-form-urlencoded";
|
|
@@ -1120,39 +1487,164 @@ var Generator = class Generator {
|
|
|
1120
1487
|
const preStatements = [];
|
|
1121
1488
|
if (bodyKind === "form-data") preStatements.push(...Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema));
|
|
1122
1489
|
else if (bodyKind === "urlencoded") preStatements.push(...Generator.toURLSearchParamsStatement(parametersShouldNotPutInFormData, requestBody?.schema));
|
|
1123
|
-
return typescript.factory.createBlock([...preStatements, ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, bodyKind, bodyContentType, shouldParseResponseToJSON)]);
|
|
1490
|
+
return typescript.factory.createBlock([...preStatements, ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, bodyKind, bodyContentType, shouldParseResponseToJSON, errorMode, auth, requestControl)]);
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* Resolves effective security requirements into concrete injections.
|
|
1494
|
+
* Requirements are OR-ed by the spec; we inject every credential the
|
|
1495
|
+
* caller provides, so either branch of an OR works.
|
|
1496
|
+
*/
|
|
1497
|
+
static toAuthInjections(security, schemes) {
|
|
1498
|
+
const injections = [];
|
|
1499
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1500
|
+
for (const requirement of security ?? []) for (const schemeName of Object.keys(requirement)) {
|
|
1501
|
+
const scheme = schemes[schemeName];
|
|
1502
|
+
if (!scheme) continue;
|
|
1503
|
+
let injection;
|
|
1504
|
+
if (scheme.type === "apiKey" && scheme.in && scheme.name) injection = {
|
|
1505
|
+
scheme: schemeName,
|
|
1506
|
+
location: scheme.in,
|
|
1507
|
+
name: scheme.name,
|
|
1508
|
+
kind: "raw"
|
|
1509
|
+
};
|
|
1510
|
+
else if (scheme.type === "http") injection = {
|
|
1511
|
+
scheme: schemeName,
|
|
1512
|
+
location: "header",
|
|
1513
|
+
name: "Authorization",
|
|
1514
|
+
kind: scheme.scheme === "basic" ? "basic" : "bearer"
|
|
1515
|
+
};
|
|
1516
|
+
else if (scheme.type === "basic" || scheme.type === "oauth2" || scheme.type === "openIdConnect") injection = {
|
|
1517
|
+
scheme: schemeName,
|
|
1518
|
+
location: "header",
|
|
1519
|
+
name: "Authorization",
|
|
1520
|
+
kind: scheme.type === "basic" ? "basic" : "bearer"
|
|
1521
|
+
};
|
|
1522
|
+
if (!injection) continue;
|
|
1523
|
+
const key = `${injection.location}:${injection.name}`;
|
|
1524
|
+
if (seen.has(key)) continue;
|
|
1525
|
+
seen.add(key);
|
|
1526
|
+
injections.push(injection);
|
|
1527
|
+
}
|
|
1528
|
+
return injections;
|
|
1529
|
+
}
|
|
1530
|
+
/** `{ [scheme: string]: string | { username: string; password: string } }` */
|
|
1531
|
+
static authOptionsTypeNode() {
|
|
1532
|
+
return typescript.factory.createTypeLiteralNode([typescript.factory.createIndexSignature(void 0, [typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier("scheme"), void 0, typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.StringKeyword))], typescript.factory.createUnionTypeNode([typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.StringKeyword), typescript.factory.createTypeLiteralNode([typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("username"), void 0, typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.StringKeyword)), typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("password"), void 0, typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.StringKeyword))])]))]);
|
|
1533
|
+
}
|
|
1534
|
+
/** `{ signal?: AbortSignal; headers?: Record<string, string>; timeout?: number }` */
|
|
1535
|
+
static requestOptionsTypeNode() {
|
|
1536
|
+
const stringType = typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.StringKeyword);
|
|
1537
|
+
return typescript.factory.createTypeLiteralNode([
|
|
1538
|
+
typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("signal"), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("AbortSignal"))),
|
|
1539
|
+
typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("headers"), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [stringType, stringType])),
|
|
1540
|
+
typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("timeout"), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.NumberKeyword))
|
|
1541
|
+
]);
|
|
1124
1542
|
}
|
|
1125
1543
|
static schemaToStatemets(parsedDoc, adaptor, options) {
|
|
1126
1544
|
const statements = [];
|
|
1127
|
-
const { apis, schemas = {}, enums } = parsedDoc;
|
|
1545
|
+
const { apis, schemas = {}, enums, securitySchemes = {} } = parsedDoc;
|
|
1128
1546
|
const enumNames = [];
|
|
1129
1547
|
for (const enumObject of enums) {
|
|
1130
1548
|
enumNames.push(Base.upperCamelCase(enumObject.name));
|
|
1131
|
-
|
|
1132
|
-
|
|
1549
|
+
const usedKeys = /* @__PURE__ */ new Set();
|
|
1550
|
+
const members = enumObject.enum.filter((member) => typeof member === "string" || typeof member === "number").map((member, index) => {
|
|
1551
|
+
let key = typeof member === "string" && !/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(member) ? member : `Value_${String(member).replace(/[^A-Za-z0-9]/g, "_")}`;
|
|
1552
|
+
if (usedKeys.has(key)) key = `${key}_${index}`;
|
|
1553
|
+
usedKeys.add(key);
|
|
1133
1554
|
return typescript.factory.createEnumMember(typescript.factory.createStringLiteral(key), typeof member === "string" ? typescript.factory.createStringLiteral(member) : typescript.factory.createNumericLiteral(member));
|
|
1134
|
-
})
|
|
1555
|
+
});
|
|
1556
|
+
statements.push(typescript.factory.createEnumDeclaration([typescript.factory.createToken(typescript.SyntaxKind.ExportKeyword)], typescript.factory.createIdentifier(Base.upperCamelCase(enumObject.name)), members));
|
|
1135
1557
|
}
|
|
1136
1558
|
for (const schemaKey in schemas) if (Object.hasOwn(schemas, schemaKey) && !enumNames.includes(Base.upperCamelCase(schemaKey))) {
|
|
1137
1559
|
const schema = schemas[schemaKey];
|
|
1138
1560
|
statements.push(typescript.factory.createTypeAliasDeclaration([typescript.factory.createModifier(typescript.SyntaxKind.ExportKeyword)], typescript.factory.createIdentifier(Base.upperCamelCase(schemaKey)), void 0, Generator.toTypeNode(schema)));
|
|
1139
1561
|
}
|
|
1140
1562
|
const reserveUnique = createUniqueNameResolver();
|
|
1563
|
+
let authTypeName;
|
|
1564
|
+
let requestOptionsTypeName;
|
|
1141
1565
|
for (const uri in apis) {
|
|
1142
1566
|
const operations = apis[uri];
|
|
1143
1567
|
for (const operation of operations) {
|
|
1144
1568
|
const { method, operationId, requestBody = [], responses = [], summary, deprecated, description } = operation;
|
|
1145
|
-
|
|
1146
|
-
|
|
1569
|
+
const { parameters = [] } = operation;
|
|
1570
|
+
const authInjections = Generator.toAuthInjections(operation.security, securitySchemes);
|
|
1571
|
+
let authArgument;
|
|
1572
|
+
let authTypeReference;
|
|
1573
|
+
if (authInjections.length > 0) {
|
|
1574
|
+
const typeName = authTypeName ?? (() => {
|
|
1575
|
+
let candidate = "AuthOptions";
|
|
1576
|
+
while (Object.keys(schemas).some((key) => Base.upperCamelCase(key) === candidate) || enumNames.includes(candidate)) candidate += "2";
|
|
1577
|
+
return candidate;
|
|
1578
|
+
})();
|
|
1579
|
+
if (!authTypeName) {
|
|
1580
|
+
authTypeName = typeName;
|
|
1581
|
+
statements.push(typescript.factory.createTypeAliasDeclaration([typescript.factory.createModifier(typescript.SyntaxKind.ExportKeyword)], typescript.factory.createIdentifier(typeName), void 0, Generator.authOptionsTypeNode()));
|
|
1582
|
+
}
|
|
1583
|
+
const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
|
|
1584
|
+
taken.add("req");
|
|
1585
|
+
let name = "auth";
|
|
1586
|
+
let suffix = 2;
|
|
1587
|
+
while (taken.has(name)) {
|
|
1588
|
+
name = `auth${suffix}`;
|
|
1589
|
+
suffix++;
|
|
1590
|
+
}
|
|
1591
|
+
authArgument = {
|
|
1592
|
+
name,
|
|
1593
|
+
injections: authInjections
|
|
1594
|
+
};
|
|
1595
|
+
authTypeReference = typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier(typeName));
|
|
1596
|
+
}
|
|
1597
|
+
const optionsTypeName = requestOptionsTypeName ?? (() => {
|
|
1598
|
+
let candidate = "RequestOptions";
|
|
1599
|
+
while (Object.keys(schemas).some((key) => Base.upperCamelCase(key) === candidate) || enumNames.includes(candidate)) candidate += "2";
|
|
1600
|
+
return candidate;
|
|
1601
|
+
})();
|
|
1602
|
+
if (!requestOptionsTypeName) {
|
|
1603
|
+
requestOptionsTypeName = optionsTypeName;
|
|
1604
|
+
statements.push(typescript.factory.createTypeAliasDeclaration([typescript.factory.createModifier(typescript.SyntaxKind.ExportKeyword)], typescript.factory.createIdentifier(optionsTypeName), void 0, Generator.requestOptionsTypeNode()));
|
|
1605
|
+
}
|
|
1606
|
+
const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
|
|
1607
|
+
taken.add("req");
|
|
1608
|
+
if (authArgument) taken.add(authArgument.name);
|
|
1609
|
+
let requestControlName = "options";
|
|
1610
|
+
let requestControlSuffix = 2;
|
|
1611
|
+
while (taken.has(requestControlName)) {
|
|
1612
|
+
requestControlName = `options${requestControlSuffix}`;
|
|
1613
|
+
requestControlSuffix++;
|
|
1614
|
+
}
|
|
1615
|
+
const requestControl = { name: requestControlName };
|
|
1147
1616
|
if (requestBody.length === 0) requestBody.push({ type: "application/json" });
|
|
1617
|
+
const { responseTypes } = operation;
|
|
1618
|
+
const responseCodes = Object.keys(responseTypes ?? {});
|
|
1619
|
+
if (responseTypes && (responseCodes.length > 1 || !/^2\d\d$/.test(responseCodes[0] ?? ""))) {
|
|
1620
|
+
const responsesName = reserveUnique(`${Base.pathToFnName(uri, method, operationId)}Responses`);
|
|
1621
|
+
statements.push(typescript.factory.createTypeAliasDeclaration([typescript.factory.createModifier(typescript.SyntaxKind.ExportKeyword)], typescript.factory.createIdentifier(responsesName), void 0, Generator.toResponsesTypeNode(responseTypes)));
|
|
1622
|
+
}
|
|
1148
1623
|
const shouldAddExtraMethodNameSuffix = requestBody.length > 1;
|
|
1149
1624
|
for (const req of requestBody) {
|
|
1150
|
-
const statement = typescript.factory.createFunctionDeclaration([typescript.factory.createModifier(typescript.SyntaxKind.ExportKeyword), typescript.factory.createModifier(typescript.SyntaxKind.AsyncKeyword)], void 0, reserveUnique(Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.mediaTypeToSuffix(req.type) : "")), void 0, [
|
|
1151
|
-
|
|
1625
|
+
const statement = typescript.factory.createFunctionDeclaration([typescript.factory.createModifier(typescript.SyntaxKind.ExportKeyword), typescript.factory.createModifier(typescript.SyntaxKind.AsyncKeyword)], void 0, reserveUnique(Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.mediaTypeToSuffix(req.type) : "")), void 0, [
|
|
1626
|
+
...parameters.length > 0 ? Generator.toDeclarationNodes(parameters) : [],
|
|
1627
|
+
...req?.schema ? [Generator.toRequestBodyTypeNode(req.schema)] : [],
|
|
1628
|
+
...authArgument && authTypeReference ? [typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier(authArgument.name), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), authTypeReference)] : [],
|
|
1629
|
+
typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier(requestControl.name), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier(optionsTypeName)))
|
|
1630
|
+
].filter(Boolean), void 0, Generator.bodyBlock(options.baseURL + uri, method, parameters, req, responses[0], adaptor, options.errorMode, authArgument, requestControl));
|
|
1631
|
+
const mergedDescription = [description, summary].filter(Boolean).map((part) => part?.trim()).join(". ");
|
|
1152
1632
|
Generator.addComments(statement, [
|
|
1153
1633
|
mergedDescription && { comment: mergedDescription },
|
|
1154
1634
|
deprecated && { tag: "deprecated" },
|
|
1155
|
-
...Generator.generateParamTags(parameters, req)
|
|
1635
|
+
...Generator.generateParamTags(parameters, req),
|
|
1636
|
+
...authArgument ? [{
|
|
1637
|
+
tag: "param",
|
|
1638
|
+
paramName: authArgument.name,
|
|
1639
|
+
type: "AuthOptions",
|
|
1640
|
+
comment: "Optional security credentials, keyed by scheme name"
|
|
1641
|
+
}] : [],
|
|
1642
|
+
{
|
|
1643
|
+
tag: "param",
|
|
1644
|
+
paramName: requestControl.name,
|
|
1645
|
+
type: optionsTypeName,
|
|
1646
|
+
comment: "Optional abort signal, extra headers and timeout"
|
|
1647
|
+
}
|
|
1156
1648
|
].filter(Boolean));
|
|
1157
1649
|
statements.push(statement);
|
|
1158
1650
|
}
|
|
@@ -1163,16 +1655,76 @@ var Generator = class Generator {
|
|
|
1163
1655
|
static async prettier(code) {
|
|
1164
1656
|
return await (0, prettier.format)(code, { parser: "typescript" });
|
|
1165
1657
|
}
|
|
1658
|
+
/**
|
|
1659
|
+
* Splits generated code into `types.ts`, one file per tag, and `index.ts`.
|
|
1660
|
+
* Shared type declarations live in `types.ts`; tag files import them and
|
|
1661
|
+
* export only their functions.
|
|
1662
|
+
*/
|
|
1663
|
+
static async genCodeMulti(schema, initOptions, adaptor) {
|
|
1664
|
+
const genOptions = {
|
|
1665
|
+
baseURL: initOptions.baseURL ?? "",
|
|
1666
|
+
errorMode: initOptions.errorMode === "throw" || initOptions.errorMode === "result" ? initOptions.errorMode : void 0
|
|
1667
|
+
};
|
|
1668
|
+
const isTypeDeclaration = (statement) => (0, typescript.isEnumDeclaration)(statement) || (0, typescript.isTypeAliasDeclaration)(statement) || (0, typescript.isInterfaceDeclaration)(statement);
|
|
1669
|
+
const typeStatements = Generator.schemaToStatemets(schema, adaptor, genOptions).filter(isTypeDeclaration);
|
|
1670
|
+
const typeNames = typeStatements.map((statement) => (0, typescript.isEnumDeclaration)(statement) || (0, typescript.isTypeAliasDeclaration)(statement) || (0, typescript.isInterfaceDeclaration)(statement) ? statement.name.text : void 0).filter((name) => Boolean(name));
|
|
1671
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1672
|
+
for (const [uri, operations] of Object.entries(schema.apis)) for (const operation of operations) {
|
|
1673
|
+
const tag = operation.tags?.[0] ?? "default";
|
|
1674
|
+
const apis = groups.get(tag) ?? {};
|
|
1675
|
+
apis[uri] ??= [];
|
|
1676
|
+
apis[uri].push(operation);
|
|
1677
|
+
groups.set(tag, apis);
|
|
1678
|
+
}
|
|
1679
|
+
const files = {};
|
|
1680
|
+
const used = /* @__PURE__ */ new Set(["index", "types"]);
|
|
1681
|
+
files["types.ts"] = await Generator.prettier(Generator.toCode(typeStatements));
|
|
1682
|
+
const exportLines = ["export * from './types.js';"];
|
|
1683
|
+
for (const [tag, apis] of groups) {
|
|
1684
|
+
const tagStatements = Generator.schemaToStatemets({
|
|
1685
|
+
...schema,
|
|
1686
|
+
apis
|
|
1687
|
+
}, adaptor, genOptions).filter((statement) => !isTypeDeclaration(statement));
|
|
1688
|
+
const nodes = [];
|
|
1689
|
+
if (typeNames.length > 0) nodes.push(typescript.factory.createImportDeclaration(void 0, typescript.factory.createImportClause(true, void 0, typescript.factory.createNamedImports(typeNames.map((name) => typescript.factory.createImportSpecifier(false, void 0, typescript.factory.createIdentifier(name))))), typescript.factory.createStringLiteral("./types.js")));
|
|
1690
|
+
nodes.push(...tagStatements);
|
|
1691
|
+
let code = Generator.toCode(nodes);
|
|
1692
|
+
if (initOptions.importClientSource) code = initOptions.importClientSource + "\n\n" + code;
|
|
1693
|
+
const fileName = Generator.uniqueFileName(tag, used);
|
|
1694
|
+
files[`${fileName}.ts`] = await Generator.prettier(code);
|
|
1695
|
+
exportLines.push(`export * from './${fileName}.js';`);
|
|
1696
|
+
}
|
|
1697
|
+
const index = await Generator.prettier(exportLines.join("\n"));
|
|
1698
|
+
files["index.ts"] = index;
|
|
1699
|
+
return {
|
|
1700
|
+
code: index,
|
|
1701
|
+
files
|
|
1702
|
+
};
|
|
1703
|
+
}
|
|
1704
|
+
/** Lower-case file stem that cannot collide with reserved or earlier names. */
|
|
1705
|
+
static uniqueFileName(tag, used) {
|
|
1706
|
+
const base = tag.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "default";
|
|
1707
|
+
let name = base;
|
|
1708
|
+
let suffix = 2;
|
|
1709
|
+
while (used.has(name)) {
|
|
1710
|
+
name = `${base}-${suffix}`;
|
|
1711
|
+
suffix++;
|
|
1712
|
+
}
|
|
1713
|
+
used.add(name);
|
|
1714
|
+
return name;
|
|
1715
|
+
}
|
|
1166
1716
|
static async genCode(schema, initOptions, adaptor) {
|
|
1167
|
-
const { importClientSource } = initOptions;
|
|
1168
|
-
const statements = Generator.schemaToStatemets(schema, adaptor, {
|
|
1717
|
+
const { importClientSource, errorMode } = initOptions;
|
|
1718
|
+
const statements = Generator.schemaToStatemets(schema, adaptor, {
|
|
1719
|
+
baseURL: initOptions.baseURL ?? "",
|
|
1720
|
+
errorMode: errorMode === "throw" || errorMode === "result" ? errorMode : void 0
|
|
1721
|
+
});
|
|
1169
1722
|
let code = Generator.toCode(statements);
|
|
1170
1723
|
if (importClientSource) code = importClientSource + "\n\n" + code;
|
|
1171
1724
|
return await Generator.prettier(code);
|
|
1172
1725
|
}
|
|
1173
1726
|
};
|
|
1174
|
-
|
|
1175
|
-
//#region src/core/client/axios.ts
|
|
1727
|
+
// src/core/client/axios.ts
|
|
1176
1728
|
/**
|
|
1177
1729
|
* Adapter class implementing support for generating code that makes use of the Axios HTTP client library.
|
|
1178
1730
|
* This adapter defines custom behavior and field mappings specific to the Axios client.
|
|
@@ -1203,16 +1755,19 @@ var AxiosAdapter = class extends Adapter {
|
|
|
1203
1755
|
*
|
|
1204
1756
|
* @returns {Statement[]} An array of TypeScript statements that define the client configuration.
|
|
1205
1757
|
*/
|
|
1206
|
-
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, _shouldUseJSONResponse) {
|
|
1758
|
+
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, _shouldUseJSONResponse, errorMode, auth, requestControl) {
|
|
1207
1759
|
const statements = [];
|
|
1208
1760
|
parameters.filter((p) => !p.in || p.in === "body");
|
|
1209
1761
|
const inHeader = parameters.filter((p) => p.in === "header");
|
|
1210
1762
|
const toLiterlExpression = () => {
|
|
1211
1763
|
const headerEntries = [];
|
|
1212
|
-
for (const p of inHeader) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral(p.name), typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createIdentifier(Base.
|
|
1764
|
+
for (const p of inHeader) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral(p.name), typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createIdentifier(Base.toIdentifier(p.name))])])));
|
|
1213
1765
|
if (bodyContentType !== void 0) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral("Content-Type"), typescript.factory.createStringLiteral(bodyContentType)));
|
|
1766
|
+
if (parameters.some((p) => p.in === "cookie") || auth?.injections.some((injection) => injection.location === "cookie")) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral("Cookie"), cookieHeaderExpression(parameters, auth)));
|
|
1767
|
+
if (auth) headerEntries.push(...authHeaderEntries(auth));
|
|
1214
1768
|
const properties = [typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.methodFieldName), typescript.factory.createStringLiteral(method.toUpperCase()))];
|
|
1215
|
-
if (headerEntries.length > 0) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.headersFieldName), typescript.factory.createObjectLiteralExpression(headerEntries)));
|
|
1769
|
+
if (headerEntries.length > 0 || requestControl) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.headersFieldName), typescript.factory.createObjectLiteralExpression(withRequestHeaders(headerEntries, requestControl))));
|
|
1770
|
+
if (requestControl) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("signal"), optionalAccess(requestControl, "signal")), typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("timeout"), optionalAccess(requestControl, "timeout")));
|
|
1216
1771
|
let bodyExpr;
|
|
1217
1772
|
switch (bodyKind) {
|
|
1218
1773
|
case "form-data":
|
|
@@ -1222,20 +1777,33 @@ var AxiosAdapter = class extends Adapter {
|
|
|
1222
1777
|
bodyExpr = typescript.factory.createIdentifier("sp");
|
|
1223
1778
|
break;
|
|
1224
1779
|
case "json":
|
|
1225
|
-
case "binary":
|
|
1226
|
-
bodyExpr = typescript.factory.createIdentifier("req");
|
|
1227
|
-
break;
|
|
1228
|
-
case "none": break;
|
|
1780
|
+
case "binary": bodyExpr = typescript.factory.createIdentifier("req");
|
|
1229
1781
|
}
|
|
1230
1782
|
if (bodyExpr) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
|
|
1231
1783
|
return typescript.factory.createObjectLiteralExpression(properties, true);
|
|
1232
1784
|
};
|
|
1233
|
-
|
|
1785
|
+
const axiosCall = typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), response?.schema ? [Generator.toTypeNode(response.schema)] : [typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("unknown"))], [Generator.toUrlTemplate(uri, parameters, "", auth), toLiterlExpression()]);
|
|
1786
|
+
if (errorMode !== "result") {
|
|
1787
|
+
statements.push(typescript.factory.createReturnStatement(axiosCall));
|
|
1788
|
+
return statements;
|
|
1789
|
+
}
|
|
1790
|
+
const prop = (name, value) => typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(name), value);
|
|
1791
|
+
const resProp = (name) => typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("res"), typescript.factory.createIdentifier(name));
|
|
1792
|
+
const errorProp = (name) => typescript.factory.createPropertyAccessExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("failure"), typescript.factory.createIdentifier("response")), typescript.factory.createIdentifier(name));
|
|
1793
|
+
const result = (ok, key, value) => typescript.factory.createObjectLiteralExpression([
|
|
1794
|
+
prop("ok", typescript.factory.createAsExpression(ok ? typescript.factory.createTrue() : typescript.factory.createFalse(), typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("const")))),
|
|
1795
|
+
prop("status", ok ? resProp("status") : errorProp("status")),
|
|
1796
|
+
prop(key, value)
|
|
1797
|
+
], true);
|
|
1798
|
+
statements.push(typescript.factory.createTryStatement(typescript.factory.createBlock([typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier("res"), void 0, void 0, typescript.factory.createAwaitExpression(axiosCall))], typescript.NodeFlags.Const)), typescript.factory.createReturnStatement(result(true, "data", resProp("data")))], true), typescript.factory.createCatchClause(typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier("err")), typescript.factory.createBlock([
|
|
1799
|
+
typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier("failure"), void 0, void 0, typescript.factory.createAsExpression(typescript.factory.createIdentifier("err"), typescript.factory.createTypeLiteralNode([typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("response"), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTypeLiteralNode([typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("status"), void 0, typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.NumberKeyword)), typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("data"), void 0, typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.UnknownKeyword))]))])))], typescript.NodeFlags.Const)),
|
|
1800
|
+
typescript.factory.createIfStatement(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("failure"), typescript.factory.createIdentifier("response")), typescript.factory.createBlock([typescript.factory.createReturnStatement(result(false, "error", errorProp("data")))], true)),
|
|
1801
|
+
typescript.factory.createThrowStatement(typescript.factory.createIdentifier("err"))
|
|
1802
|
+
], true)), void 0));
|
|
1234
1803
|
return statements;
|
|
1235
1804
|
}
|
|
1236
1805
|
};
|
|
1237
|
-
|
|
1238
|
-
//#region src/core/client/fetch.ts
|
|
1806
|
+
// src/core/client/fetch.ts
|
|
1239
1807
|
/**
|
|
1240
1808
|
* FetchAdapter is an adapter class that generates client-side fetch requests.
|
|
1241
1809
|
* It handles parameters, headers, and request bodies to construct proper fetch calls.
|
|
@@ -1259,7 +1827,7 @@ var FetchAdapter = class extends Adapter {
|
|
|
1259
1827
|
* @param shouldUseJSONResponse - Flag to use JSON parsing for the response
|
|
1260
1828
|
* @return - An array of generated TypeScript statements
|
|
1261
1829
|
*/
|
|
1262
|
-
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, shouldUseJSONResponse) {
|
|
1830
|
+
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, shouldUseJSONResponse, errorMode, auth, requestControl) {
|
|
1263
1831
|
const statements = [];
|
|
1264
1832
|
const inBody = parameters.filter((p) => !p.in || p.in === "body");
|
|
1265
1833
|
const inHeader = parameters.filter((p) => p.in === "header");
|
|
@@ -1270,10 +1838,13 @@ var FetchAdapter = class extends Adapter {
|
|
|
1270
1838
|
*/
|
|
1271
1839
|
const toLiterlExpression = () => {
|
|
1272
1840
|
const headerEntries = [];
|
|
1273
|
-
for (const p of inHeader) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral(p.name), typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createIdentifier(Base.
|
|
1841
|
+
for (const p of inHeader) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral(p.name), typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createIdentifier(Base.toIdentifier(p.name))])])));
|
|
1274
1842
|
if (bodyContentType !== void 0) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral("Content-Type"), typescript.factory.createStringLiteral(bodyContentType)));
|
|
1843
|
+
if (parameters.some((p) => p.in === "cookie") || auth?.injections.some((injection) => injection.location === "cookie")) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral("Cookie"), cookieHeaderExpression(parameters, auth)));
|
|
1844
|
+
if (auth) headerEntries.push(...authHeaderEntries(auth));
|
|
1275
1845
|
const properties = [typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.methodFieldName), typescript.factory.createStringLiteral(method.toUpperCase()))];
|
|
1276
|
-
if (headerEntries.length > 0) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.headersFieldName), typescript.factory.createObjectLiteralExpression(headerEntries)));
|
|
1846
|
+
if (headerEntries.length > 0 || requestControl) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.headersFieldName), typescript.factory.createObjectLiteralExpression(withRequestHeaders(headerEntries, requestControl))));
|
|
1847
|
+
if (requestControl) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("signal"), fetchSignalExpression(requestControl)));
|
|
1277
1848
|
let bodyExpr;
|
|
1278
1849
|
switch (bodyKind) {
|
|
1279
1850
|
case "form-data":
|
|
@@ -1287,24 +1858,40 @@ var FetchAdapter = class extends Adapter {
|
|
|
1287
1858
|
bodyExpr = typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("JSON"), typescript.factory.createIdentifier("stringify")), [], [arg]);
|
|
1288
1859
|
break;
|
|
1289
1860
|
}
|
|
1290
|
-
case "binary":
|
|
1291
|
-
bodyExpr = typescript.factory.createIdentifier("req");
|
|
1292
|
-
break;
|
|
1293
|
-
case "none": break;
|
|
1861
|
+
case "binary": bodyExpr = typescript.factory.createIdentifier("req");
|
|
1294
1862
|
}
|
|
1295
1863
|
if (bodyExpr) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
|
|
1296
1864
|
return typescript.factory.createObjectLiteralExpression(properties, true);
|
|
1297
1865
|
};
|
|
1298
|
-
|
|
1866
|
+
const fetchCall = typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters, "", auth), toLiterlExpression()]);
|
|
1867
|
+
const responseProp = (name) => typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("response"), typescript.factory.createIdentifier(name));
|
|
1868
|
+
const jsonExpression = typescript.factory.createAsExpression(typescript.factory.createParenthesizedExpression(typescript.factory.createAwaitExpression(typescript.factory.createCallExpression(responseProp("json"), void 0, []))), response?.schema ? Generator.toTypeNode(response.schema) : typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword));
|
|
1869
|
+
const successExpression = shouldUseJSONResponse ? jsonExpression : typescript.factory.createIdentifier("response");
|
|
1870
|
+
if (!errorMode) {
|
|
1871
|
+
statements.push(typescript.factory.createReturnStatement(shouldUseJSONResponse ? typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(fetchCall, typescript.factory.createIdentifier("then")), void 0, [typescript.factory.createArrowFunction([typescript.factory.createModifier(typescript.SyntaxKind.AsyncKeyword)], [], [typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier("response"))], void 0, typescript.factory.createToken(typescript.SyntaxKind.EqualsGreaterThanToken), jsonExpression)]) : fetchCall));
|
|
1872
|
+
return statements;
|
|
1873
|
+
}
|
|
1874
|
+
const notOk = typescript.factory.createPrefixUnaryExpression(typescript.SyntaxKind.ExclamationToken, responseProp("ok"));
|
|
1875
|
+
const responseText = typescript.factory.createAwaitExpression(typescript.factory.createCallExpression(responseProp("text"), void 0, []));
|
|
1876
|
+
const thenStatements = [];
|
|
1877
|
+
if (errorMode === "throw") thenStatements.push(typescript.factory.createIfStatement(notOk, typescript.factory.createBlock([typescript.factory.createThrowStatement(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("Object"), typescript.factory.createIdentifier("assign")), void 0, [typescript.factory.createNewExpression(typescript.factory.createIdentifier("Error"), void 0, [typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead("HTTP "), [typescript.factory.createTemplateSpan(responseProp("status"), typescript.factory.createTemplateTail(""))])]), typescript.factory.createObjectLiteralExpression([typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("status"), responseProp("status")), typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("body"), responseText)], true)]))], true)), typescript.factory.createReturnStatement(successExpression));
|
|
1878
|
+
else {
|
|
1879
|
+
const result = (ok, key, value) => typescript.factory.createObjectLiteralExpression([
|
|
1880
|
+
typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("ok"), typescript.factory.createAsExpression(ok ? typescript.factory.createTrue() : typescript.factory.createFalse(), typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("const")))),
|
|
1881
|
+
typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("status"), responseProp("status")),
|
|
1882
|
+
typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(key), value)
|
|
1883
|
+
], true);
|
|
1884
|
+
thenStatements.push(typescript.factory.createIfStatement(notOk, typescript.factory.createBlock([typescript.factory.createReturnStatement(result(false, "error", responseText))], true)), typescript.factory.createReturnStatement(result(true, "data", successExpression)));
|
|
1885
|
+
}
|
|
1886
|
+
statements.push(typescript.factory.createReturnStatement(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(fetchCall, typescript.factory.createIdentifier("then")), void 0, [typescript.factory.createArrowFunction([typescript.factory.createModifier(typescript.SyntaxKind.AsyncKeyword)], [], [typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier("response"))], void 0, typescript.factory.createToken(typescript.SyntaxKind.EqualsGreaterThanToken), typescript.factory.createBlock(thenStatements, true))])));
|
|
1299
1887
|
return statements;
|
|
1300
1888
|
}
|
|
1301
1889
|
};
|
|
1302
|
-
|
|
1303
|
-
//#region src/core/config.ts
|
|
1890
|
+
// src/core/config.ts
|
|
1304
1891
|
/**
|
|
1305
1892
|
* Strings considered truthy for boolean env vars (verbose/watch/typeCheck).
|
|
1306
1893
|
*/
|
|
1307
|
-
const TRUTHY_STRINGS = new Set([
|
|
1894
|
+
const TRUTHY_STRINGS = /* @__PURE__ */ new Set([
|
|
1308
1895
|
"true",
|
|
1309
1896
|
"1",
|
|
1310
1897
|
"yes",
|
|
@@ -1321,7 +1908,10 @@ const ENV_MAPPINGS = {
|
|
|
1321
1908
|
APICODEGEN_ADAPTOR: "adaptor",
|
|
1322
1909
|
APICODEGEN_VERBOSE: "verbose",
|
|
1323
1910
|
APICODEGEN_WATCH: "watch",
|
|
1324
|
-
APICODEGEN_TYPE_CHECK: "typeCheck"
|
|
1911
|
+
APICODEGEN_TYPE_CHECK: "typeCheck",
|
|
1912
|
+
APICODEGEN_CHECK: "check",
|
|
1913
|
+
APICODEGEN_ERROR_MODE: "errorMode",
|
|
1914
|
+
APICODEGEN_SPLIT_BY: "splitBy"
|
|
1325
1915
|
};
|
|
1326
1916
|
/**
|
|
1327
1917
|
* Load config from environment variables
|
|
@@ -1334,19 +1924,23 @@ function loadFromEnv() {
|
|
|
1334
1924
|
case "verbose":
|
|
1335
1925
|
case "watch":
|
|
1336
1926
|
case "typeCheck":
|
|
1927
|
+
case "check":
|
|
1337
1928
|
config[configKey] = TRUTHY_STRINGS.has(value.toLowerCase());
|
|
1338
1929
|
break;
|
|
1339
1930
|
case "adaptor":
|
|
1340
1931
|
if (Object.values(Adaptors).includes(value)) config[configKey] = value;
|
|
1341
1932
|
break;
|
|
1933
|
+
case "errorMode":
|
|
1934
|
+
if (value === "throw" || value === "result") config.errorMode = value;
|
|
1935
|
+
break;
|
|
1936
|
+
case "splitBy":
|
|
1937
|
+
if (value === "tag") config.splitBy = value;
|
|
1938
|
+
break;
|
|
1342
1939
|
default: config[configKey] = value;
|
|
1343
1940
|
}
|
|
1344
1941
|
}
|
|
1345
1942
|
return config;
|
|
1346
1943
|
}
|
|
1347
|
-
/**
|
|
1348
|
-
* Load config from a file
|
|
1349
|
-
*/
|
|
1350
1944
|
async function loadFromFile(filePath) {
|
|
1351
1945
|
const ext = node_path.default.extname(filePath).toLowerCase();
|
|
1352
1946
|
try {
|
|
@@ -1355,17 +1949,16 @@ async function loadFromFile(filePath) {
|
|
|
1355
1949
|
return JSON.parse(content);
|
|
1356
1950
|
}
|
|
1357
1951
|
if (ext === ".js" || ext === ".cjs" || ext === ".mjs") {
|
|
1358
|
-
const mod = await import(filePath);
|
|
1952
|
+
const mod = await import((0, node_url.pathToFileURL)(filePath).href);
|
|
1359
1953
|
return mod.default || mod;
|
|
1360
1954
|
}
|
|
1361
|
-
if (ext === ".ts") {
|
|
1955
|
+
if (ext === ".ts" || ext === ".mts" || ext === ".cts") {
|
|
1362
1956
|
const content = await fs_extra.default.readFile(filePath, "utf-8");
|
|
1363
1957
|
try {
|
|
1364
1958
|
return JSON.parse(content);
|
|
1365
|
-
} catch {
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
}
|
|
1959
|
+
} catch {}
|
|
1960
|
+
const mod = await import((0, node_url.pathToFileURL)(filePath).href);
|
|
1961
|
+
return mod.default || mod;
|
|
1369
1962
|
}
|
|
1370
1963
|
const content = await fs_extra.default.readFile(filePath, "utf-8");
|
|
1371
1964
|
return JSON.parse(content);
|
|
@@ -1381,10 +1974,13 @@ async function findConfigFile(cwd) {
|
|
|
1381
1974
|
"apicodegen.config.json",
|
|
1382
1975
|
"apicodegen.config.js",
|
|
1383
1976
|
"apicodegen.config.mjs",
|
|
1977
|
+
"apicodegen.config.ts",
|
|
1978
|
+
"apicodegen.config.mts",
|
|
1384
1979
|
".apicodegenrc",
|
|
1385
1980
|
".apicodegenrc.json",
|
|
1386
1981
|
".apicodegenrc.js",
|
|
1387
|
-
".apicodegenrc.mjs"
|
|
1982
|
+
".apicodegenrc.mjs",
|
|
1983
|
+
".apicodegenrc.ts"
|
|
1388
1984
|
]) {
|
|
1389
1985
|
const filePath = node_path.default.join(cwd, fileName);
|
|
1390
1986
|
if (await fs_extra.default.pathExists(filePath)) return filePath;
|
|
@@ -1409,6 +2005,35 @@ function mergeConfigs(base, ...sources) {
|
|
|
1409
2005
|
return result;
|
|
1410
2006
|
}
|
|
1411
2007
|
/**
|
|
2008
|
+
* Validate field types before the values reach the generator.
|
|
2009
|
+
*/
|
|
2010
|
+
function validateConfigShape(config) {
|
|
2011
|
+
const fail = (key, expected) => {
|
|
2012
|
+
throw new Error(`Invalid config field "${key}": expected ${expected}`);
|
|
2013
|
+
};
|
|
2014
|
+
if (config.spec !== void 0 && typeof config.spec !== "string") fail("spec", "a string");
|
|
2015
|
+
if (config.output !== void 0 && typeof config.output !== "string") fail("output", "a string");
|
|
2016
|
+
for (const key of [
|
|
2017
|
+
"verbose",
|
|
2018
|
+
"watch",
|
|
2019
|
+
"typeCheck",
|
|
2020
|
+
"check"
|
|
2021
|
+
]) if (config[key] !== void 0 && typeof config[key] !== "boolean") fail(key, "a boolean");
|
|
2022
|
+
if (config.adaptor !== void 0 && !Object.values(Adaptors).includes(config.adaptor)) fail("adaptor", Object.values(Adaptors).join(" or "));
|
|
2023
|
+
if (config.errorMode !== void 0 && config.errorMode !== "throw" && config.errorMode !== "result") fail("errorMode", "throw or result");
|
|
2024
|
+
if (config.splitBy !== void 0 && config.splitBy !== "tag") fail("splitBy", "tag");
|
|
2025
|
+
for (const key of [
|
|
2026
|
+
"includeTags",
|
|
2027
|
+
"excludeTags",
|
|
2028
|
+
"includePaths",
|
|
2029
|
+
"excludePaths"
|
|
2030
|
+
]) {
|
|
2031
|
+
const value = config[key];
|
|
2032
|
+
if (value !== void 0 && (!Array.isArray(value) || value.some((item) => typeof item !== "string"))) fail(key, "an array of strings");
|
|
2033
|
+
}
|
|
2034
|
+
if (config.requestOptions !== void 0 && (typeof config.requestOptions !== "object" || config.requestOptions === null || Array.isArray(config.requestOptions))) fail("requestOptions", "an object");
|
|
2035
|
+
}
|
|
2036
|
+
/**
|
|
1412
2037
|
* Validate config has required fields
|
|
1413
2038
|
*/
|
|
1414
2039
|
function validateConfig(config) {
|
|
@@ -1416,9 +2041,10 @@ function validateConfig(config) {
|
|
|
1416
2041
|
return true;
|
|
1417
2042
|
}
|
|
1418
2043
|
/**
|
|
1419
|
-
* Load and resolve config
|
|
2044
|
+
* Load and resolve every config entry. A config file may define a single
|
|
2045
|
+
* object or a `specs` array for multi-spec projects.
|
|
1420
2046
|
*/
|
|
1421
|
-
async function
|
|
2047
|
+
async function loadConfigs(options = {}) {
|
|
1422
2048
|
const cwd = options.cwd || process.cwd();
|
|
1423
2049
|
const cliOptions = options.cliOptions || {};
|
|
1424
2050
|
const envConfig = loadFromEnv();
|
|
@@ -1440,17 +2066,34 @@ async function loadConfig(options = {}) {
|
|
|
1440
2066
|
const pkg = JSON.parse(await fs_extra.default.readFile(packageJsonPath, "utf-8"));
|
|
1441
2067
|
if (pkg.apicodegen && typeof pkg.apicodegen === "object") inlineConfig = pkg.apicodegen;
|
|
1442
2068
|
} catch {}
|
|
1443
|
-
const
|
|
2069
|
+
const { specs, ...fileOptions } = fileConfig;
|
|
2070
|
+
const entries = Array.isArray(specs) && specs.length > 0 ? specs.map((entry) => mergeConfigs({
|
|
1444
2071
|
spec: "",
|
|
1445
2072
|
output: "./output.ts"
|
|
1446
|
-
},
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
2073
|
+
}, fileOptions, entry)) : [fileOptions];
|
|
2074
|
+
const sharedCliOptions = entries.length === 1 ? cliOptions : Object.fromEntries(Object.entries(cliOptions).filter(([key]) => key !== "spec" && key !== "output"));
|
|
2075
|
+
return entries.map((entry, index) => {
|
|
2076
|
+
const merged = mergeConfigs({
|
|
2077
|
+
spec: "",
|
|
2078
|
+
output: "./output.ts"
|
|
2079
|
+
}, envConfig, inlineConfig, entry, sharedCliOptions);
|
|
2080
|
+
validateConfigShape(merged);
|
|
2081
|
+
validateConfig(merged);
|
|
2082
|
+
const name = options.name || merged.name || merged.baseURL || merged.spec || `api-${index + 1}`;
|
|
2083
|
+
return {
|
|
2084
|
+
...merged,
|
|
2085
|
+
configFilePath,
|
|
2086
|
+
name
|
|
2087
|
+
};
|
|
2088
|
+
});
|
|
2089
|
+
}
|
|
2090
|
+
/**
|
|
2091
|
+
* Load a single config. Throws when the file defines no entries.
|
|
2092
|
+
*/
|
|
2093
|
+
async function loadConfig(options = {}) {
|
|
2094
|
+
const config = (await loadConfigs(options))[0];
|
|
2095
|
+
if (!config) throw new Error("No API configs found");
|
|
2096
|
+
return config;
|
|
1454
2097
|
}
|
|
1455
2098
|
/**
|
|
1456
2099
|
* Create CLI options from config for commander
|
|
@@ -1460,9 +2103,17 @@ function configToCLIOptions(config) {
|
|
|
1460
2103
|
if (config.spec) options.spec = config.spec;
|
|
1461
2104
|
if (config.output) options.output = config.output;
|
|
1462
2105
|
if (config.adaptor) options.adaptor = config.adaptor;
|
|
1463
|
-
if (config.
|
|
2106
|
+
if (config.errorMode) options.errorMode = config.errorMode;
|
|
2107
|
+
if (config.splitBy) options.splitBy = config.splitBy;
|
|
2108
|
+
if (config.includeTags) options.includeTags = config.includeTags;
|
|
2109
|
+
if (config.excludeTags) options.excludeTags = config.excludeTags;
|
|
2110
|
+
if (config.includePaths) options.includePaths = config.includePaths;
|
|
2111
|
+
if (config.excludePaths) options.excludePaths = config.excludePaths;
|
|
2112
|
+
if (config.baseURL !== void 0) options.baseURL = config.baseURL;
|
|
1464
2113
|
if (config.verbose) options.verbose = config.verbose;
|
|
2114
|
+
if (config.typeCheck) options.typeCheck = config.typeCheck;
|
|
1465
2115
|
if (config.watch) options.watch = config.watch;
|
|
2116
|
+
if (config.check) options.check = config.check;
|
|
1466
2117
|
if (config.importClientSource) options.importClientSource = config.importClientSource;
|
|
1467
2118
|
return options;
|
|
1468
2119
|
}
|
|
@@ -1477,11 +2128,203 @@ function toProviderOptions(config) {
|
|
|
1477
2128
|
baseURL: config.baseURL,
|
|
1478
2129
|
importClientSource: config.importClientSource,
|
|
1479
2130
|
verbose: config.verbose,
|
|
1480
|
-
requestOptions: config.requestOptions
|
|
2131
|
+
requestOptions: config.requestOptions,
|
|
2132
|
+
errorMode: config.errorMode,
|
|
2133
|
+
splitBy: config.splitBy,
|
|
2134
|
+
includeTags: config.includeTags,
|
|
2135
|
+
excludeTags: config.excludeTags,
|
|
2136
|
+
includePaths: config.includePaths,
|
|
2137
|
+
excludePaths: config.excludePaths
|
|
1481
2138
|
};
|
|
1482
2139
|
}
|
|
1483
|
-
|
|
1484
|
-
|
|
2140
|
+
// src/openapi/filter.ts
|
|
2141
|
+
function matchesPrefix(path, prefixes) {
|
|
2142
|
+
return !!prefixes?.length && prefixes.some((prefix) => path.startsWith(prefix));
|
|
2143
|
+
}
|
|
2144
|
+
/**
|
|
2145
|
+
* Keep only the operations selected by tag and path filters.
|
|
2146
|
+
*
|
|
2147
|
+
* Paths use prefix matching (`/admin` covers `/admin/users`). Operations with
|
|
2148
|
+
* no tags are kept only when no `includeTags` filter is active.
|
|
2149
|
+
*/
|
|
2150
|
+
function filterApis(apis, filters) {
|
|
2151
|
+
const keepTag = (op) => {
|
|
2152
|
+
const tags = op.tags ?? [];
|
|
2153
|
+
if (filters.includeTags?.length && !tags.some((tag) => filters.includeTags?.includes(tag))) return false;
|
|
2154
|
+
if (filters.excludeTags?.length && tags.some((tag) => filters.excludeTags?.includes(tag))) return false;
|
|
2155
|
+
return true;
|
|
2156
|
+
};
|
|
2157
|
+
const filtered = {};
|
|
2158
|
+
for (const [path, operations] of Object.entries(apis)) {
|
|
2159
|
+
if (filters.includePaths?.length && !matchesPrefix(path, filters.includePaths)) continue;
|
|
2160
|
+
if (matchesPrefix(path, filters.excludePaths)) continue;
|
|
2161
|
+
const kept = operations.filter(keepTag);
|
|
2162
|
+
if (kept.length > 0) filtered[path] = kept;
|
|
2163
|
+
}
|
|
2164
|
+
return filtered;
|
|
2165
|
+
}
|
|
2166
|
+
// src/openapi/read-write.ts
|
|
2167
|
+
function single(schema) {
|
|
2168
|
+
return schema;
|
|
2169
|
+
}
|
|
2170
|
+
/** True when a schema carries the flag anywhere except through a `$ref`. */
|
|
2171
|
+
function containsFlag(schema, flag) {
|
|
2172
|
+
if (!schema) return false;
|
|
2173
|
+
const value = single(schema);
|
|
2174
|
+
if (value[flag]) return true;
|
|
2175
|
+
if (value.properties) {
|
|
2176
|
+
for (const prop of Object.values(value.properties)) if (containsFlag(prop, flag)) return true;
|
|
2177
|
+
}
|
|
2178
|
+
if (schema.type === "array") return containsFlag(schema.items, flag);
|
|
2179
|
+
for (const key of [
|
|
2180
|
+
"allOf",
|
|
2181
|
+
"anyOf",
|
|
2182
|
+
"oneOf"
|
|
2183
|
+
]) if (value[key]?.some((member) => containsFlag(member, flag))) return true;
|
|
2184
|
+
const additional = value.additionalProperties;
|
|
2185
|
+
return !!additional && typeof additional === "object" && containsFlag(additional, flag);
|
|
2186
|
+
}
|
|
2187
|
+
/** The referenced emitted type name, when a schema is only a reference. */
|
|
2188
|
+
function refType(schema) {
|
|
2189
|
+
const value = single(schema);
|
|
2190
|
+
if (value.ref) return Base.upperCamelCase(Base.ref2name(value.ref));
|
|
2191
|
+
if (value.properties || value.oneOf || value.anyOf || value.allOf) return;
|
|
2192
|
+
if (schema.type === "array") return void 0;
|
|
2193
|
+
return typeof value.type === "string" ? Base.upperCamelCase(value.type) : void 0;
|
|
2194
|
+
}
|
|
2195
|
+
function dependsOn(schema, names) {
|
|
2196
|
+
const ref = refType(schema);
|
|
2197
|
+
if (ref && names.has(ref)) return true;
|
|
2198
|
+
const value = single(schema);
|
|
2199
|
+
if (value.properties) {
|
|
2200
|
+
for (const prop of Object.values(value.properties)) if (dependsOn(prop, names)) return true;
|
|
2201
|
+
}
|
|
2202
|
+
if (schema.type === "array") {
|
|
2203
|
+
const items = schema.items;
|
|
2204
|
+
return !!items && dependsOn(items, names);
|
|
2205
|
+
}
|
|
2206
|
+
for (const key of [
|
|
2207
|
+
"allOf",
|
|
2208
|
+
"anyOf",
|
|
2209
|
+
"oneOf"
|
|
2210
|
+
]) if (value[key]?.some((member) => dependsOn(member, names))) return true;
|
|
2211
|
+
const additional = value.additionalProperties;
|
|
2212
|
+
return !!additional && typeof additional === "object" && dependsOn(additional, names);
|
|
2213
|
+
}
|
|
2214
|
+
/**
|
|
2215
|
+
* Pick the schemas that need an Input/Output variant.
|
|
2216
|
+
*
|
|
2217
|
+
* A schema qualifies when it contains the flag directly, or references a
|
|
2218
|
+
* schema that does. The fixed point makes nested references follow.
|
|
2219
|
+
*/
|
|
2220
|
+
function buildVariant(schemas, flag, suffix) {
|
|
2221
|
+
const seeded = /* @__PURE__ */ new Set();
|
|
2222
|
+
const emitted = /* @__PURE__ */ new Map();
|
|
2223
|
+
for (const key of Object.keys(schemas)) {
|
|
2224
|
+
emitted.set(Base.upperCamelCase(key), key);
|
|
2225
|
+
if (containsFlag(schemas[key], flag)) seeded.add(key);
|
|
2226
|
+
}
|
|
2227
|
+
let changed = true;
|
|
2228
|
+
while (changed) {
|
|
2229
|
+
changed = false;
|
|
2230
|
+
const seededNames = new Set([...seeded].map((key) => Base.upperCamelCase(key)));
|
|
2231
|
+
for (const key of Object.keys(schemas)) if (!seeded.has(key) && dependsOn(schemas[key], seededNames)) {
|
|
2232
|
+
seeded.add(key);
|
|
2233
|
+
changed = true;
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
const names = /* @__PURE__ */ new Map();
|
|
2237
|
+
const keys = /* @__PURE__ */ new Map();
|
|
2238
|
+
const taken = new Set(emitted.keys());
|
|
2239
|
+
for (const key of seeded) {
|
|
2240
|
+
const variantKey = key + suffix;
|
|
2241
|
+
const variantName = Base.upperCamelCase(variantKey);
|
|
2242
|
+
if (taken.has(variantName)) continue;
|
|
2243
|
+
taken.add(variantName);
|
|
2244
|
+
names.set(Base.upperCamelCase(key), variantName);
|
|
2245
|
+
keys.set(key, variantKey);
|
|
2246
|
+
}
|
|
2247
|
+
return {
|
|
2248
|
+
names,
|
|
2249
|
+
keys
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2252
|
+
/** Clone a schema with flagged properties removed and variant refs remapped. */
|
|
2253
|
+
function transform(schema, flag, names) {
|
|
2254
|
+
const ref = refType(schema);
|
|
2255
|
+
if (ref && names.has(ref)) {
|
|
2256
|
+
const { ref: _ref, ...rest } = single(schema);
|
|
2257
|
+
return {
|
|
2258
|
+
...rest,
|
|
2259
|
+
type: names.get(ref)
|
|
2260
|
+
};
|
|
2261
|
+
}
|
|
2262
|
+
if (schema.type === "array") {
|
|
2263
|
+
const array = schema;
|
|
2264
|
+
return {
|
|
2265
|
+
...array,
|
|
2266
|
+
items: array.items ? transform(array.items, flag, names) : void 0
|
|
2267
|
+
};
|
|
2268
|
+
}
|
|
2269
|
+
const value = single(schema);
|
|
2270
|
+
const next = { ...value };
|
|
2271
|
+
if (value.properties) {
|
|
2272
|
+
const properties = {};
|
|
2273
|
+
for (const [key, prop] of Object.entries(value.properties)) {
|
|
2274
|
+
if (single(prop)[flag]) continue;
|
|
2275
|
+
properties[key] = transform(prop, flag, names);
|
|
2276
|
+
}
|
|
2277
|
+
next.properties = properties;
|
|
2278
|
+
if (Array.isArray(value.required)) next.required = value.required.filter((key) => key in properties);
|
|
2279
|
+
}
|
|
2280
|
+
for (const key of [
|
|
2281
|
+
"allOf",
|
|
2282
|
+
"anyOf",
|
|
2283
|
+
"oneOf"
|
|
2284
|
+
]) {
|
|
2285
|
+
const members = value[key];
|
|
2286
|
+
if (members) next[key] = members.map((m) => transform(m, flag, names));
|
|
2287
|
+
}
|
|
2288
|
+
const additional = value.additionalProperties;
|
|
2289
|
+
if (additional && typeof additional === "object") next.additionalProperties = transform(additional, flag, names);
|
|
2290
|
+
return next;
|
|
2291
|
+
}
|
|
2292
|
+
function transformMedia(media, flag, names) {
|
|
2293
|
+
return media.map((entry) => entry.schema ? {
|
|
2294
|
+
...entry,
|
|
2295
|
+
schema: transform(entry.schema, flag, names)
|
|
2296
|
+
} : entry);
|
|
2297
|
+
}
|
|
2298
|
+
function transformOperation(operation, input, output) {
|
|
2299
|
+
return {
|
|
2300
|
+
...operation,
|
|
2301
|
+
...operation.requestBody ? { requestBody: transformMedia(operation.requestBody, "readOnly", input) } : {},
|
|
2302
|
+
...operation.responses ? { responses: transformMedia(operation.responses, "writeOnly", output) } : {},
|
|
2303
|
+
...operation.responseTypes ? { responseTypes: Object.fromEntries(Object.entries(operation.responseTypes).map(([code, media]) => [code, transformMedia(media, "writeOnly", output)])) } : {}
|
|
2304
|
+
};
|
|
2305
|
+
}
|
|
2306
|
+
/**
|
|
2307
|
+
* Add `XxxInput` / `XxxOutput` schema aliases and point operations at them:
|
|
2308
|
+
* requests drop `readOnly` properties, responses drop `writeOnly` ones.
|
|
2309
|
+
*
|
|
2310
|
+
* Existing type names are untouched; variants are only created when the name
|
|
2311
|
+
* is free. With no `readOnly` / `writeOnly` in the document this is a no-op.
|
|
2312
|
+
*/
|
|
2313
|
+
function splitReadWrite(parsed) {
|
|
2314
|
+
const input = buildVariant(parsed.schemas, "readOnly", "Input");
|
|
2315
|
+
const output = buildVariant(parsed.schemas, "writeOnly", "Output");
|
|
2316
|
+
if (input.keys.size === 0 && output.keys.size === 0) return parsed;
|
|
2317
|
+
const schemas = { ...parsed.schemas };
|
|
2318
|
+
for (const [key, variantKey] of input.keys) schemas[variantKey] = transform(parsed.schemas[key], "readOnly", input.names);
|
|
2319
|
+
for (const [key, variantKey] of output.keys) schemas[variantKey] = transform(parsed.schemas[key], "writeOnly", output.names);
|
|
2320
|
+
const apis = Object.fromEntries(Object.entries(parsed.apis).map(([path, operations]) => [path, operations.map((operation) => transformOperation(operation, input.names, output.names))]));
|
|
2321
|
+
return {
|
|
2322
|
+
...parsed,
|
|
2323
|
+
schemas,
|
|
2324
|
+
apis
|
|
2325
|
+
};
|
|
2326
|
+
}
|
|
2327
|
+
// src/openapi/V2.ts
|
|
1485
2328
|
var V2 = class {
|
|
1486
2329
|
doc;
|
|
1487
2330
|
constructor(doc) {
|
|
@@ -1528,11 +2371,11 @@ var V2 = class {
|
|
|
1528
2371
|
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
1529
2372
|
};
|
|
1530
2373
|
} else {
|
|
1531
|
-
const { required = [], allOf, anyOf, description, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
2374
|
+
const { required = [], allOf, anyOf, description, discriminator, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
1532
2375
|
let { type } = schema;
|
|
1533
2376
|
if (enum_ && type !== "boolean") {
|
|
1534
2377
|
const enumObject = {
|
|
1535
|
-
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey))
|
|
2378
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
|
|
1536
2379
|
enum: [...new Set(enum_)]
|
|
1537
2380
|
};
|
|
1538
2381
|
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
@@ -1548,8 +2391,11 @@ var V2 = class {
|
|
|
1548
2391
|
type,
|
|
1549
2392
|
required,
|
|
1550
2393
|
description,
|
|
2394
|
+
discriminator: discriminator ? { propertyName: discriminator } : void 0,
|
|
1551
2395
|
enum: enum_,
|
|
1552
2396
|
format,
|
|
2397
|
+
readOnly: schema.readOnly,
|
|
2398
|
+
writeOnly: schema.writeOnly,
|
|
1553
2399
|
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
1554
2400
|
...s,
|
|
1555
2401
|
ref: s.$ref,
|
|
@@ -1586,6 +2432,9 @@ var V2 = class {
|
|
|
1586
2432
|
parameter = resolved;
|
|
1587
2433
|
}
|
|
1588
2434
|
const p = parameter;
|
|
2435
|
+
const collectionFormat = p.collectionFormat;
|
|
2436
|
+
const style = collectionFormat === "ssv" ? "spaceDelimited" : collectionFormat === "pipes" ? "pipeDelimited" : "form";
|
|
2437
|
+
const explode = collectionFormat === "multi";
|
|
1589
2438
|
const { name, required, description, type, items, enum: enum_, properties, schema } = p;
|
|
1590
2439
|
if (enum_) {
|
|
1591
2440
|
const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
|
|
@@ -1603,6 +2452,8 @@ var V2 = class {
|
|
|
1603
2452
|
required,
|
|
1604
2453
|
description,
|
|
1605
2454
|
in: p.in,
|
|
2455
|
+
style,
|
|
2456
|
+
explode,
|
|
1606
2457
|
schema: { type: sameEnum?.name ?? type }
|
|
1607
2458
|
};
|
|
1608
2459
|
}
|
|
@@ -1611,6 +2462,8 @@ var V2 = class {
|
|
|
1611
2462
|
required,
|
|
1612
2463
|
description,
|
|
1613
2464
|
in: p.in,
|
|
2465
|
+
style,
|
|
2466
|
+
explode,
|
|
1614
2467
|
schema: {
|
|
1615
2468
|
type,
|
|
1616
2469
|
items
|
|
@@ -1621,6 +2474,8 @@ var V2 = class {
|
|
|
1621
2474
|
required,
|
|
1622
2475
|
description,
|
|
1623
2476
|
in: p.in,
|
|
2477
|
+
style,
|
|
2478
|
+
explode,
|
|
1624
2479
|
schema: { type: Base.capitalize(Base.ref2name(schema.$ref)) }
|
|
1625
2480
|
};
|
|
1626
2481
|
return {
|
|
@@ -1628,6 +2483,8 @@ var V2 = class {
|
|
|
1628
2483
|
required,
|
|
1629
2484
|
description,
|
|
1630
2485
|
in: p.in,
|
|
2486
|
+
style,
|
|
2487
|
+
explode,
|
|
1631
2488
|
schema: {
|
|
1632
2489
|
type,
|
|
1633
2490
|
properties
|
|
@@ -1637,16 +2494,16 @@ var V2 = class {
|
|
|
1637
2494
|
/**
|
|
1638
2495
|
* OpenAPI schema to base response
|
|
1639
2496
|
*/
|
|
1640
|
-
getResponseByRef(schema) {
|
|
2497
|
+
getResponseByRef(schema, enums = []) {
|
|
1641
2498
|
if (Base.isRef(schema)) schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
|
|
1642
2499
|
const { schema: responseSchema } = schema;
|
|
1643
2500
|
return [{
|
|
1644
2501
|
type: "application/json",
|
|
1645
|
-
schema: responseSchema && this.getSchemaByRef(responseSchema, true)
|
|
2502
|
+
schema: responseSchema && this.getSchemaByRef(responseSchema, true, enums)
|
|
1646
2503
|
}];
|
|
1647
2504
|
}
|
|
1648
2505
|
init() {
|
|
1649
|
-
const { definitions = {}, responses = {}, paths = {} } = this.doc;
|
|
2506
|
+
const { definitions = {}, responses = {}, paths = {}, security = [], securityDefinitions = {} } = this.doc;
|
|
1650
2507
|
const enums = [];
|
|
1651
2508
|
const definitions_ = Object.keys(definitions).reduce((acc, key) => {
|
|
1652
2509
|
const schema = definitions[key];
|
|
@@ -1659,7 +2516,7 @@ var V2 = class {
|
|
|
1659
2516
|
const response = responses[key];
|
|
1660
2517
|
return {
|
|
1661
2518
|
...acc,
|
|
1662
|
-
[key]: this.getResponseByRef(response)
|
|
2519
|
+
[key]: this.getResponseByRef(response, enums)
|
|
1663
2520
|
};
|
|
1664
2521
|
}, {});
|
|
1665
2522
|
const apis = Object.keys(paths).reduce((acc, path) => {
|
|
@@ -1680,42 +2537,42 @@ var V2 = class {
|
|
|
1680
2537
|
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
1681
2538
|
const inBody = baseParameters.filter((p) => p.in === "body" || p.in === "formData");
|
|
1682
2539
|
const notInBody = baseParameters.filter((p) => p.in !== "body" && p.in !== "formData");
|
|
1683
|
-
const httpCodes = Object.keys(responses);
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
}
|
|
2540
|
+
const httpCodes = Object.keys(responses).filter((code) => code in responses);
|
|
2541
|
+
const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
|
|
2542
|
+
const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
|
|
2543
|
+
const inBodyOnlyHasBody = inBody && inBody.length === 1 && inBody[0].in === "body" && inBody[0].name === "body";
|
|
2544
|
+
methodApis.push({
|
|
2545
|
+
method,
|
|
2546
|
+
operationId,
|
|
2547
|
+
summary: summary_,
|
|
2548
|
+
deprecated,
|
|
2549
|
+
description: description_,
|
|
2550
|
+
parameters: uniqueParameterName.map((name) => notInBody.find((p) => p.name === name)).filter(Boolean),
|
|
2551
|
+
responses: responseTypes[successCode] ?? [],
|
|
2552
|
+
responseTypes,
|
|
2553
|
+
tags: methodObject.tags,
|
|
2554
|
+
security: methodObject.security ?? security,
|
|
2555
|
+
requestBody: inBody.length > 0 ? inBodyOnlyHasBody ? [{
|
|
2556
|
+
type: "application/json",
|
|
2557
|
+
schema: inBody[0].schema
|
|
2558
|
+
}] : [{
|
|
2559
|
+
type: "application/json",
|
|
2560
|
+
schema: {
|
|
2561
|
+
type: "object",
|
|
2562
|
+
properties: inBody.reduce((a, p) => {
|
|
2563
|
+
return {
|
|
2564
|
+
...a,
|
|
2565
|
+
[p.name]: {
|
|
2566
|
+
type: p.schema?.type ?? "unknown",
|
|
2567
|
+
required: p.schema?.required,
|
|
2568
|
+
items: p.schema?.items,
|
|
2569
|
+
description: p.schema?.description
|
|
2570
|
+
}
|
|
2571
|
+
};
|
|
2572
|
+
}, {})
|
|
2573
|
+
}
|
|
2574
|
+
}] : void 0
|
|
2575
|
+
});
|
|
1719
2576
|
}
|
|
1720
2577
|
});
|
|
1721
2578
|
return {
|
|
@@ -1729,12 +2586,12 @@ var V2 = class {
|
|
|
1729
2586
|
responses: responses_,
|
|
1730
2587
|
parameters: {},
|
|
1731
2588
|
requestBodies: {},
|
|
2589
|
+
securitySchemes: securityDefinitions,
|
|
1732
2590
|
apis
|
|
1733
2591
|
};
|
|
1734
2592
|
}
|
|
1735
2593
|
};
|
|
1736
|
-
|
|
1737
|
-
//#region src/openapi/V3.ts
|
|
2594
|
+
// src/openapi/V3.ts
|
|
1738
2595
|
var V3 = class {
|
|
1739
2596
|
doc;
|
|
1740
2597
|
constructor(doc) {
|
|
@@ -1794,7 +2651,9 @@ var V3 = class {
|
|
|
1794
2651
|
description,
|
|
1795
2652
|
deprecated,
|
|
1796
2653
|
in: schema.in,
|
|
1797
|
-
schema: { type: sameEnum?.name ?? type }
|
|
2654
|
+
schema: { type: sameEnum?.name ?? type },
|
|
2655
|
+
style: schema.style,
|
|
2656
|
+
explode: schema.explode
|
|
1798
2657
|
};
|
|
1799
2658
|
}
|
|
1800
2659
|
return {
|
|
@@ -1803,13 +2662,15 @@ var V3 = class {
|
|
|
1803
2662
|
description,
|
|
1804
2663
|
deprecated,
|
|
1805
2664
|
in: schema.in,
|
|
2665
|
+
style: schema.style,
|
|
2666
|
+
explode: schema.explode,
|
|
1806
2667
|
schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
|
|
1807
2668
|
};
|
|
1808
2669
|
}
|
|
1809
2670
|
/**
|
|
1810
2671
|
* OpenAPI schema to base response
|
|
1811
2672
|
*/
|
|
1812
|
-
getResponseByRef(schema) {
|
|
2673
|
+
getResponseByRef(schema, enums = []) {
|
|
1813
2674
|
if (Base.isRef(schema)) {
|
|
1814
2675
|
const resolvedSchema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1815
2676
|
if (!resolvedSchema) return [];
|
|
@@ -1818,7 +2679,7 @@ var V3 = class {
|
|
|
1818
2679
|
const { content = {} } = schema;
|
|
1819
2680
|
return Object.keys(content).map((c) => ({
|
|
1820
2681
|
type: c,
|
|
1821
|
-
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
|
|
2682
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
|
|
1822
2683
|
}));
|
|
1823
2684
|
}
|
|
1824
2685
|
/**
|
|
@@ -1843,25 +2704,27 @@ var V3 = class {
|
|
|
1843
2704
|
if (!schema) return { type: "unknown" };
|
|
1844
2705
|
if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
|
|
1845
2706
|
if (this.isOpenAPIArraySchema(schema)) {
|
|
1846
|
-
const { type, description, items, required } = schema;
|
|
2707
|
+
const { type, description, items, required, nullable } = schema;
|
|
1847
2708
|
return {
|
|
1848
2709
|
type,
|
|
2710
|
+
nullable,
|
|
1849
2711
|
required: !!required,
|
|
1850
2712
|
description,
|
|
1851
2713
|
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
1852
2714
|
};
|
|
1853
2715
|
} else {
|
|
1854
|
-
const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
2716
|
+
const { required = [], allOf, anyOf, description, deprecated, discriminator, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
1855
2717
|
let { type } = schema;
|
|
1856
2718
|
if (enum_ && type !== "boolean") {
|
|
1857
2719
|
const enumObject = {
|
|
1858
|
-
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey))
|
|
2720
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
|
|
1859
2721
|
enum: [...new Set(enum_)]
|
|
1860
2722
|
};
|
|
1861
2723
|
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
1862
2724
|
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
1863
2725
|
return {
|
|
1864
2726
|
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
2727
|
+
nullable: schema.nullable,
|
|
1865
2728
|
required,
|
|
1866
2729
|
description,
|
|
1867
2730
|
deprecated
|
|
@@ -1870,11 +2733,16 @@ var V3 = class {
|
|
|
1870
2733
|
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
1871
2734
|
return {
|
|
1872
2735
|
type,
|
|
2736
|
+
nullable: schema.nullable,
|
|
2737
|
+
additionalProperties: schema.additionalProperties && typeof schema.additionalProperties === "object" ? this.toBaseSchema(schema.additionalProperties, enums) : schema.additionalProperties,
|
|
1873
2738
|
required,
|
|
1874
2739
|
description,
|
|
1875
2740
|
deprecated,
|
|
2741
|
+
discriminator,
|
|
1876
2742
|
enum: enum_,
|
|
1877
2743
|
format,
|
|
2744
|
+
readOnly: schema.readOnly,
|
|
2745
|
+
writeOnly: schema.writeOnly,
|
|
1878
2746
|
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
1879
2747
|
...s,
|
|
1880
2748
|
ref: s.$ref,
|
|
@@ -1904,9 +2772,9 @@ var V3 = class {
|
|
|
1904
2772
|
}
|
|
1905
2773
|
}
|
|
1906
2774
|
init() {
|
|
1907
|
-
const { components = {}, paths = {} } = this.doc;
|
|
2775
|
+
const { components = {}, paths = {}, security = [] } = this.doc;
|
|
1908
2776
|
const enums = [];
|
|
1909
|
-
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {} } = components;
|
|
2777
|
+
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {}, securitySchemes = {} } = components;
|
|
1910
2778
|
const schemas_ = Object.keys(schemas).reduce((acc, key) => {
|
|
1911
2779
|
const schema = schemas[key];
|
|
1912
2780
|
return {
|
|
@@ -1925,7 +2793,7 @@ var V3 = class {
|
|
|
1925
2793
|
const response = responses[key];
|
|
1926
2794
|
return {
|
|
1927
2795
|
...acc,
|
|
1928
|
-
[key]: this.getResponseByRef(response)
|
|
2796
|
+
[key]: this.getResponseByRef(response, enums)
|
|
1929
2797
|
};
|
|
1930
2798
|
}, {});
|
|
1931
2799
|
const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
|
|
@@ -1952,22 +2820,22 @@ var V3 = class {
|
|
|
1952
2820
|
const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
|
|
1953
2821
|
const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
|
|
1954
2822
|
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
1955
|
-
const httpCodes = Object.keys(responses);
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
}
|
|
2823
|
+
const httpCodes = Object.keys(responses).filter((code) => code in responses);
|
|
2824
|
+
const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
|
|
2825
|
+
const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
|
|
2826
|
+
methodApis.push({
|
|
2827
|
+
method,
|
|
2828
|
+
operationId,
|
|
2829
|
+
summary: summary_ ?? summary,
|
|
2830
|
+
description: description_ ?? description,
|
|
2831
|
+
deprecated,
|
|
2832
|
+
parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
|
|
2833
|
+
responses: responseTypes[successCode] ?? [],
|
|
2834
|
+
responseTypes,
|
|
2835
|
+
tags: methodObject.tags,
|
|
2836
|
+
security: methodObject.security ?? security,
|
|
2837
|
+
requestBody: baseRequestBody
|
|
2838
|
+
});
|
|
1971
2839
|
}
|
|
1972
2840
|
});
|
|
1973
2841
|
return {
|
|
@@ -1981,12 +2849,12 @@ var V3 = class {
|
|
|
1981
2849
|
responses: responses_,
|
|
1982
2850
|
parameters: parameters_,
|
|
1983
2851
|
requestBodies: requestBodies_,
|
|
2852
|
+
securitySchemes,
|
|
1984
2853
|
apis
|
|
1985
2854
|
};
|
|
1986
2855
|
}
|
|
1987
2856
|
};
|
|
1988
|
-
|
|
1989
|
-
//#region src/openapi/V3_1.ts
|
|
2857
|
+
// src/openapi/V3_1.ts
|
|
1990
2858
|
var V3_1 = class {
|
|
1991
2859
|
doc;
|
|
1992
2860
|
constructor(doc) {
|
|
@@ -2003,7 +2871,8 @@ var V3_1 = class {
|
|
|
2003
2871
|
* Is array schema.
|
|
2004
2872
|
*/
|
|
2005
2873
|
isOpenAPIArraySchema(schema) {
|
|
2006
|
-
|
|
2874
|
+
if (typeof schema !== "object") return false;
|
|
2875
|
+
return schema.type === "array" || Array.isArray(schema.type) && schema.type.includes("array");
|
|
2007
2876
|
}
|
|
2008
2877
|
/**
|
|
2009
2878
|
* OpenAPI schema to base schema.
|
|
@@ -2040,7 +2909,9 @@ var V3_1 = class {
|
|
|
2040
2909
|
description,
|
|
2041
2910
|
deprecated,
|
|
2042
2911
|
in: schema.in,
|
|
2043
|
-
schema: { type: sameEnum?.name ?? type }
|
|
2912
|
+
schema: { type: sameEnum?.name ?? type },
|
|
2913
|
+
style: schema.style,
|
|
2914
|
+
explode: schema.explode
|
|
2044
2915
|
};
|
|
2045
2916
|
}
|
|
2046
2917
|
return {
|
|
@@ -2049,18 +2920,20 @@ var V3_1 = class {
|
|
|
2049
2920
|
description,
|
|
2050
2921
|
deprecated,
|
|
2051
2922
|
in: schema.in,
|
|
2923
|
+
style: schema.style,
|
|
2924
|
+
explode: schema.explode,
|
|
2052
2925
|
schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
|
|
2053
2926
|
};
|
|
2054
2927
|
}
|
|
2055
2928
|
/**
|
|
2056
2929
|
* OpenAPI schema to base response
|
|
2057
2930
|
*/
|
|
2058
|
-
getResponseByRef(schema) {
|
|
2931
|
+
getResponseByRef(schema, enums = []) {
|
|
2059
2932
|
if (Base.isRef(schema)) schema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2060
2933
|
const { content = {} } = schema;
|
|
2061
2934
|
return Object.keys(content).map((c) => ({
|
|
2062
2935
|
type: c,
|
|
2063
|
-
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
|
|
2936
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
|
|
2064
2937
|
}));
|
|
2065
2938
|
}
|
|
2066
2939
|
/**
|
|
@@ -2081,25 +2954,38 @@ var V3_1 = class {
|
|
|
2081
2954
|
if (!schema) return { type: "unknown" };
|
|
2082
2955
|
if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
|
|
2083
2956
|
if (this.isOpenAPIArraySchema(schema)) {
|
|
2084
|
-
const {
|
|
2957
|
+
const { description, items, required } = schema;
|
|
2958
|
+
const rawType = schema.type;
|
|
2085
2959
|
return {
|
|
2086
|
-
type,
|
|
2960
|
+
type: "array",
|
|
2961
|
+
nullable: Array.isArray(rawType) && rawType.includes("null"),
|
|
2087
2962
|
required: !!required,
|
|
2088
2963
|
description,
|
|
2089
2964
|
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
2090
2965
|
};
|
|
2091
2966
|
} else {
|
|
2092
|
-
const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
2093
|
-
|
|
2967
|
+
const { required = [], allOf, anyOf, description, deprecated, discriminator, enum: enum_, format, oneOf, properties = {}, const: constValue, additionalProperties } = schema;
|
|
2968
|
+
const rawType = schema.type;
|
|
2969
|
+
const typeArray = Array.isArray(rawType) ? rawType.filter((t) => t !== "null") : void 0;
|
|
2970
|
+
let type = Array.isArray(rawType) ? typeArray?.[0] : schema.type;
|
|
2971
|
+
const nullableByType = Array.isArray(rawType) && rawType.includes("null");
|
|
2972
|
+
if (constValue !== void 0) return {
|
|
2973
|
+
type: typeof constValue === "number" ? "number" : typeof constValue === "boolean" ? "boolean" : "string",
|
|
2974
|
+
const: constValue,
|
|
2975
|
+
required,
|
|
2976
|
+
description,
|
|
2977
|
+
deprecated
|
|
2978
|
+
};
|
|
2094
2979
|
if (enum_ && type !== "boolean") {
|
|
2095
2980
|
const enumObject = {
|
|
2096
|
-
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey))
|
|
2981
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
|
|
2097
2982
|
enum: [...new Set(enum_)]
|
|
2098
2983
|
};
|
|
2099
2984
|
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
2100
2985
|
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
2101
2986
|
return {
|
|
2102
2987
|
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
2988
|
+
nullable: nullableByType,
|
|
2103
2989
|
required,
|
|
2104
2990
|
description,
|
|
2105
2991
|
deprecated
|
|
@@ -2108,11 +2994,18 @@ var V3_1 = class {
|
|
|
2108
2994
|
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
2109
2995
|
return {
|
|
2110
2996
|
type,
|
|
2997
|
+
types: typeArray,
|
|
2998
|
+
nullable: nullableByType,
|
|
2999
|
+
const: constValue,
|
|
3000
|
+
additionalProperties: additionalProperties && typeof additionalProperties === "object" ? this.toBaseSchema(additionalProperties, enums) : additionalProperties,
|
|
2111
3001
|
required,
|
|
2112
3002
|
description,
|
|
2113
3003
|
deprecated,
|
|
3004
|
+
discriminator,
|
|
2114
3005
|
enum: enum_,
|
|
2115
3006
|
format,
|
|
3007
|
+
readOnly: schema.readOnly,
|
|
3008
|
+
writeOnly: schema.writeOnly,
|
|
2116
3009
|
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
2117
3010
|
...s,
|
|
2118
3011
|
ref: s.$ref,
|
|
@@ -2142,9 +3035,9 @@ var V3_1 = class {
|
|
|
2142
3035
|
}
|
|
2143
3036
|
}
|
|
2144
3037
|
init() {
|
|
2145
|
-
const { components = {}, paths = {} } = this.doc;
|
|
3038
|
+
const { components = {}, paths = {}, security = [] } = this.doc;
|
|
2146
3039
|
const enums = [];
|
|
2147
|
-
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {} } = components;
|
|
3040
|
+
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {}, securitySchemes = {} } = components;
|
|
2148
3041
|
const schemas_ = Object.keys(schemas).reduce((acc, key) => {
|
|
2149
3042
|
const schema = schemas[key];
|
|
2150
3043
|
return {
|
|
@@ -2163,7 +3056,7 @@ var V3_1 = class {
|
|
|
2163
3056
|
const response = responses[key];
|
|
2164
3057
|
return {
|
|
2165
3058
|
...acc,
|
|
2166
|
-
[key]: this.getResponseByRef(response)
|
|
3059
|
+
[key]: this.getResponseByRef(response, enums)
|
|
2167
3060
|
};
|
|
2168
3061
|
}, {});
|
|
2169
3062
|
const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
|
|
@@ -2190,22 +3083,22 @@ var V3_1 = class {
|
|
|
2190
3083
|
const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
|
|
2191
3084
|
const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
|
|
2192
3085
|
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
2193
|
-
const httpCodes = Object.keys(responses);
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
}
|
|
3086
|
+
const httpCodes = Object.keys(responses).filter((code) => code in responses);
|
|
3087
|
+
const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
|
|
3088
|
+
const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
|
|
3089
|
+
methodApis.push({
|
|
3090
|
+
method,
|
|
3091
|
+
operationId,
|
|
3092
|
+
summary: summary_ ?? summary,
|
|
3093
|
+
description: description_ ?? description,
|
|
3094
|
+
deprecated,
|
|
3095
|
+
parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
|
|
3096
|
+
responses: responseTypes[successCode] ?? [],
|
|
3097
|
+
responseTypes,
|
|
3098
|
+
tags: methodObject.tags,
|
|
3099
|
+
security: methodObject.security ?? security,
|
|
3100
|
+
requestBody: baseRequestBody
|
|
3101
|
+
});
|
|
2209
3102
|
}
|
|
2210
3103
|
});
|
|
2211
3104
|
return {
|
|
@@ -2219,12 +3112,12 @@ var V3_1 = class {
|
|
|
2219
3112
|
responses: responses_,
|
|
2220
3113
|
parameters: parameters_,
|
|
2221
3114
|
requestBodies: requestBodies_,
|
|
3115
|
+
securitySchemes,
|
|
2222
3116
|
apis
|
|
2223
3117
|
};
|
|
2224
3118
|
}
|
|
2225
3119
|
};
|
|
2226
|
-
|
|
2227
|
-
//#region src/openapi/index.ts
|
|
3120
|
+
// src/openapi/index.ts
|
|
2228
3121
|
const logger$1 = (0, _moccona_logger.createScopedLogger)("OpenAPI");
|
|
2229
3122
|
let OpenAPIVersion = /* @__PURE__ */ function(OpenAPIVersion) {
|
|
2230
3123
|
OpenAPIVersion["v2"] = "v2";
|
|
@@ -2261,6 +3154,18 @@ function getAdaptor(type) {
|
|
|
2261
3154
|
default: return new FetchAdapter();
|
|
2262
3155
|
}
|
|
2263
3156
|
}
|
|
3157
|
+
/**
|
|
3158
|
+
* Use the document's first server when the caller did not configure a base URL.
|
|
3159
|
+
* Server variables fall back to their declared defaults.
|
|
3160
|
+
*/
|
|
3161
|
+
function inferBaseURL(doc) {
|
|
3162
|
+
const server = doc.servers?.[0];
|
|
3163
|
+
if (server?.url) return server.url.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
3164
|
+
return server.variables?.[name]?.default ?? `{${name}}`;
|
|
3165
|
+
}).replace(/\/+$/, "");
|
|
3166
|
+
const v2 = doc;
|
|
3167
|
+
if (v2.host) return `${v2.schemes?.[0] ?? "https"}://${v2.host}${(v2.basePath ?? "").replace(/\/+$/, "")}`;
|
|
3168
|
+
}
|
|
2264
3169
|
async function codeGen(initOptions) {
|
|
2265
3170
|
const startTime = Date.now();
|
|
2266
3171
|
const { verbose } = initOptions;
|
|
@@ -2268,7 +3173,7 @@ async function codeGen(initOptions) {
|
|
|
2268
3173
|
else logger$1.setLevel("info");
|
|
2269
3174
|
logger$1.info(`Fetch document from ${initOptions.docURL}`);
|
|
2270
3175
|
const { transport, source } = Base.resolveSpecURL(initOptions.docURL);
|
|
2271
|
-
const
|
|
3176
|
+
const rawDoc = transport === "file" ? await (async () => {
|
|
2272
3177
|
let raw;
|
|
2273
3178
|
try {
|
|
2274
3179
|
raw = await (0, node_fs_promises.readFile)(source, "utf8");
|
|
@@ -2276,34 +3181,65 @@ async function codeGen(initOptions) {
|
|
|
2276
3181
|
if (error?.code === "ENOENT") throw createErrors.specNotFound(source, error);
|
|
2277
3182
|
throw new Error(`Failed to read OpenAPI spec from ${source}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2278
3183
|
}
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
2283
|
-
|
|
2284
|
-
|
|
3184
|
+
return Base.parseDoc(raw, source);
|
|
3185
|
+
})() : await Base.fetchDoc(source, initOptions.requestOptions);
|
|
3186
|
+
const doc = await Base.bundleExternalRefs(rawDoc, source, initOptions.requestOptions);
|
|
3187
|
+
const options = {
|
|
3188
|
+
...initOptions,
|
|
3189
|
+
baseURL: initOptions.baseURL ?? inferBaseURL(doc)
|
|
3190
|
+
};
|
|
3191
|
+
const { enums, schemas, parameters, responses, requestBodies, securitySchemes, apis } = new OpenAPIProvider(options, doc);
|
|
2285
3192
|
const adaptor = getAdaptor(initOptions.adaptor ?? "fetch");
|
|
2286
|
-
const
|
|
3193
|
+
const split = splitReadWrite({
|
|
2287
3194
|
enums,
|
|
2288
3195
|
schemas,
|
|
2289
3196
|
parameters,
|
|
2290
3197
|
responses,
|
|
2291
3198
|
requestBodies,
|
|
3199
|
+
securitySchemes,
|
|
2292
3200
|
apis
|
|
2293
|
-
}
|
|
2294
|
-
|
|
3201
|
+
});
|
|
3202
|
+
const parsed = {
|
|
3203
|
+
...split,
|
|
3204
|
+
apis: filterApis(split.apis, options)
|
|
3205
|
+
};
|
|
3206
|
+
const multi = initOptions.splitBy === "tag" ? await Generator.genCodeMulti(parsed, options, adaptor) : void 0;
|
|
3207
|
+
const code = multi?.code ?? await Generator.genCode(parsed, options, adaptor);
|
|
3208
|
+
if (initOptions.output) {
|
|
3209
|
+
if (multi) for (const [name, content] of Object.entries(multi.files)) await Generator.write(content, (0, node_path.join)(initOptions.output, name));
|
|
3210
|
+
else await Generator.write(code, initOptions.output);
|
|
3211
|
+
}
|
|
2295
3212
|
const duration = Date.now() - startTime;
|
|
3213
|
+
const endpoints = Object.keys(apis).length;
|
|
3214
|
+
const schemasCount = Object.keys(schemas).length;
|
|
2296
3215
|
return {
|
|
2297
3216
|
code,
|
|
3217
|
+
...multi ? { files: multi.files } : {},
|
|
2298
3218
|
stats: {
|
|
2299
|
-
endpoints
|
|
2300
|
-
schemas:
|
|
3219
|
+
endpoints,
|
|
3220
|
+
schemas: schemasCount,
|
|
2301
3221
|
duration
|
|
2302
3222
|
}
|
|
2303
3223
|
};
|
|
2304
3224
|
}
|
|
2305
|
-
|
|
2306
|
-
|
|
3225
|
+
// src/core/typecheck.ts
|
|
3226
|
+
/**
|
|
3227
|
+
* Type-check a generated file with the project's TypeScript.
|
|
3228
|
+
*
|
|
3229
|
+
* @param filePath - Path to the generated file.
|
|
3230
|
+
* @returns Collected error messages; an empty array means success.
|
|
3231
|
+
*/
|
|
3232
|
+
async function runTypeCheck(filePath) {
|
|
3233
|
+
try {
|
|
3234
|
+
await (0, execa.execaCommand)(`npx tsc ${filePath} --noEmit`, { shell: true });
|
|
3235
|
+
return [];
|
|
3236
|
+
} catch (error) {
|
|
3237
|
+
return [error instanceof Error ? error.message : String(error)];
|
|
3238
|
+
}
|
|
3239
|
+
}
|
|
3240
|
+
// package.json
|
|
3241
|
+
var version = "1.0.0";
|
|
3242
|
+
// src/vite-plugin/cache.ts
|
|
2307
3243
|
/**
|
|
2308
3244
|
* Cache for a single vite-plugin codegen run. Lives only for the duration
|
|
2309
3245
|
* of one plugin invocation — there is no module-level state.
|
|
@@ -2322,7 +3258,8 @@ var CodegenCache = class CodegenCache {
|
|
|
2322
3258
|
}
|
|
2323
3259
|
/** Hash the options that affect generated output (excluding the spec). */
|
|
2324
3260
|
static hashOptions(options) {
|
|
2325
|
-
const
|
|
3261
|
+
const keys = Object.keys(options).sort();
|
|
3262
|
+
const payload = [`generatorVersion=${version}`, ...keys.filter((k) => k !== "verbose" && k !== "typeCheck" && k !== "cache").map((k) => `${k}=${JSON.stringify(options[k])}`)].join("|");
|
|
2326
3263
|
return (0, node_crypto.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
2327
3264
|
}
|
|
2328
3265
|
/** Hash the raw spec content so unrelated edits are detected. */
|
|
@@ -2378,24 +3315,10 @@ var CodegenCache = class CodegenCache {
|
|
|
2378
3315
|
await (0, node_fs_promises.writeFile)(cachePath, JSON.stringify(entry));
|
|
2379
3316
|
}
|
|
2380
3317
|
};
|
|
2381
|
-
|
|
2382
|
-
//#region src/vite-plugin/index.ts
|
|
3318
|
+
// src/vite-plugin/index.ts
|
|
2383
3319
|
const PLUGIN_NAME = "api-code-gen";
|
|
2384
3320
|
const logger = (0, _moccona_logger.createScopedLogger)("api-code-gen");
|
|
2385
3321
|
/**
|
|
2386
|
-
* Run TypeScript type checking on generated file
|
|
2387
|
-
*/
|
|
2388
|
-
async function runTypeCheck(filePath) {
|
|
2389
|
-
const { execaCommand } = await import("execa");
|
|
2390
|
-
const errors = [];
|
|
2391
|
-
try {
|
|
2392
|
-
await execaCommand(`npx tsc ${filePath} --noEmit`, { shell: true });
|
|
2393
|
-
} catch (error) {
|
|
2394
|
-
if (error instanceof Error) errors.push(error.message);
|
|
2395
|
-
}
|
|
2396
|
-
return errors;
|
|
2397
|
-
}
|
|
2398
|
-
/**
|
|
2399
3322
|
* Validate spec path exists
|
|
2400
3323
|
*/
|
|
2401
3324
|
async function validateSpecPath(specPath) {
|
|
@@ -2404,6 +3327,12 @@ async function validateSpecPath(specPath) {
|
|
|
2404
3327
|
const absolutePath = node_path.default.isAbsolute(filePath) ? filePath : node_path.default.resolve(process.cwd(), filePath);
|
|
2405
3328
|
if (!await fs_extra.default.pathExists(absolutePath)) throw createErrors.specNotFound(absolutePath);
|
|
2406
3329
|
}
|
|
3330
|
+
/** Resolve a local spec to an absolute path; remote specs return null. */
|
|
3331
|
+
function toWatchPath(spec) {
|
|
3332
|
+
if (!spec || spec.startsWith("http://") || spec.startsWith("https://")) return null;
|
|
3333
|
+
const filePath = spec.replace(/^file:\/\//, "");
|
|
3334
|
+
return node_path.default.isAbsolute(filePath) ? filePath : node_path.default.resolve(process.cwd(), filePath);
|
|
3335
|
+
}
|
|
2407
3336
|
/**
|
|
2408
3337
|
* Generate code for a single API configuration
|
|
2409
3338
|
*/
|
|
@@ -2419,19 +3348,21 @@ async function generateForOption(option) {
|
|
|
2419
3348
|
}
|
|
2420
3349
|
});
|
|
2421
3350
|
await validateSpecPath(config.spec);
|
|
2422
|
-
if (config.output) {
|
|
2423
|
-
const outputDir = node_path.default.dirname(config.output);
|
|
2424
|
-
await fs_extra.default.ensureDir(outputDir);
|
|
2425
|
-
}
|
|
2426
3351
|
let docURL = config.spec;
|
|
2427
3352
|
if (!docURL.startsWith("http://") && !docURL.startsWith("https://") && !docURL.startsWith("file://") && !docURL.startsWith("/") && !/^[A-Za-z]:[\\/]/.test(docURL)) docURL = node_path.default.resolve(process.cwd(), docURL);
|
|
2428
3353
|
const resolvedCacheDir = cacheDir ?? node_path.default.join(process.cwd(), "node_modules", ".cache", "apicodegen");
|
|
2429
|
-
const codegenCache = cache ? new CodegenCache(resolvedCacheDir) : null;
|
|
3354
|
+
const codegenCache = cache && !config.splitBy ? new CodegenCache(resolvedCacheDir) : null;
|
|
2430
3355
|
const optionsHash = CodegenCache.hashOptions({
|
|
2431
3356
|
name,
|
|
2432
3357
|
spec: docURL,
|
|
2433
3358
|
output: config.output,
|
|
2434
3359
|
adaptor: config.adaptor,
|
|
3360
|
+
errorMode: config.errorMode,
|
|
3361
|
+
splitBy: config.splitBy,
|
|
3362
|
+
includeTags: config.includeTags,
|
|
3363
|
+
excludeTags: config.excludeTags,
|
|
3364
|
+
includePaths: config.includePaths,
|
|
3365
|
+
excludePaths: config.excludePaths,
|
|
2435
3366
|
baseURL: config.baseURL,
|
|
2436
3367
|
importClientSource: config.importClientSource
|
|
2437
3368
|
});
|
|
@@ -2473,7 +3404,13 @@ async function generateForOption(option) {
|
|
|
2473
3404
|
if (verbose) logger.warn(`Cache write failed for ${name}: ${cacheError.message}`);
|
|
2474
3405
|
}
|
|
2475
3406
|
}
|
|
2476
|
-
if (config.output)
|
|
3407
|
+
if (config.output) {
|
|
3408
|
+
if (result.files) {
|
|
3409
|
+
const dir = node_path.default.dirname(config.output);
|
|
3410
|
+
for (const [name, content] of Object.entries(result.files)) if (name !== "index.ts") await fs_extra.default.outputFile(node_path.default.join(dir, name), content);
|
|
3411
|
+
}
|
|
3412
|
+
await fs_extra.default.outputFile(config.output, result.code);
|
|
3413
|
+
}
|
|
2477
3414
|
if (typeCheck && config.output) {
|
|
2478
3415
|
const typeErrors = await runTypeCheck(config.output);
|
|
2479
3416
|
if (typeErrors.length > 0) {
|
|
@@ -2523,49 +3460,72 @@ function apiCodeGenPlugin(options) {
|
|
|
2523
3460
|
logger.warn("No API configurations provided to apiCodeGenPlugin");
|
|
2524
3461
|
return { name: PLUGIN_NAME };
|
|
2525
3462
|
}
|
|
3463
|
+
let mode = "unknown";
|
|
3464
|
+
const watched = /* @__PURE__ */ new Set();
|
|
3465
|
+
const printResults = (results) => {
|
|
3466
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3467
|
+
console.log(`\x1b[1m\x1b[36mAPI Code Gen\x1b[0m`);
|
|
3468
|
+
console.log(`\x1b[90mMode:\x1b[0m ${mode}`);
|
|
3469
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3470
|
+
const successCount = results.filter((r) => r.success).length;
|
|
3471
|
+
const failCount = results.length - successCount;
|
|
3472
|
+
for (const result of results) if (result.success) {
|
|
3473
|
+
const { name, output, stats, cached } = result;
|
|
3474
|
+
if (stats) {
|
|
3475
|
+
const cachedTag = cached ? " \x1B[90m[cached]\x1B[0m" : "";
|
|
3476
|
+
console.log(`\x1b[32m✓\x1b[0m ${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms${cachedTag}`);
|
|
3477
|
+
} else console.log(`\x1b[32m✓\x1b[0m ${name} → ${output || "N/A"}`);
|
|
3478
|
+
} else {
|
|
3479
|
+
const { name, error } = result;
|
|
3480
|
+
const wrapped = isApicodegenError(error) ? error : wrapError(error, {
|
|
3481
|
+
code: "E_GENERATION_FAILED",
|
|
3482
|
+
message: `Failed to generate API "${name}"`
|
|
3483
|
+
});
|
|
3484
|
+
console.log(`\x1b[31m✗\x1b[0m ${name}`);
|
|
3485
|
+
console.log(`\x1b[90m${formatError(wrapped, true)}\x1b[0m`);
|
|
3486
|
+
}
|
|
3487
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3488
|
+
const totalDuration = results.reduce((sum, r) => sum + (r.stats?.duration || 0), 0);
|
|
3489
|
+
const totalEndpoints = results.reduce((sum, r) => sum + (r.stats?.endpoints || 0), 0);
|
|
3490
|
+
const totalSchemas = results.reduce((sum, r) => sum + (r.stats?.schemas || 0), 0);
|
|
3491
|
+
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)`);
|
|
3492
|
+
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)`);
|
|
3493
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3494
|
+
};
|
|
3495
|
+
const regenerate = async (option) => {
|
|
3496
|
+
const result = await generateForOption(option);
|
|
3497
|
+
printResults([result]);
|
|
3498
|
+
};
|
|
2526
3499
|
return {
|
|
2527
3500
|
name: PLUGIN_NAME,
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
console.log(`\x1b[1m\x1b[36mAPI Code Gen\x1b[0m`);
|
|
2531
|
-
console.log(`\x1b[90mMode:\x1b[0m ${env?.command || "unknown"}`);
|
|
2532
|
-
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
2533
|
-
const results = await Promise.all(options.map(generateForOption));
|
|
2534
|
-
const successCount = results.filter((r) => r.success).length;
|
|
2535
|
-
const failCount = options.length - successCount;
|
|
2536
|
-
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
2537
|
-
for (const result of results) if (result.success) {
|
|
2538
|
-
const { name, output, stats, cached } = result;
|
|
2539
|
-
if (stats) {
|
|
2540
|
-
const cachedTag = cached ? " \x1B[90m[cached]\x1B[0m" : "";
|
|
2541
|
-
console.log(`\x1b[32m✓\x1b[0m ${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms${cachedTag}`);
|
|
2542
|
-
} else console.log(`\x1b[32m✓\x1b[0m ${name} → ${output || "N/A"}`);
|
|
2543
|
-
} else {
|
|
2544
|
-
const { name, error } = result;
|
|
2545
|
-
if (isApicodegenError(error)) {
|
|
2546
|
-
console.log(`\x1b[31m✗\x1b[0m ${name}`);
|
|
2547
|
-
console.log(`\x1b[90m${formatError(error, true)}\x1b[0m`);
|
|
2548
|
-
} else {
|
|
2549
|
-
const wrapped = wrapError(error, {
|
|
2550
|
-
code: "E_GENERATION_FAILED",
|
|
2551
|
-
message: `Failed to generate API "${name}"`
|
|
2552
|
-
});
|
|
2553
|
-
console.log(`\x1b[31m✗\x1b[0m ${name}`);
|
|
2554
|
-
console.log(`\x1b[90m${formatError(wrapped, true)}\x1b[0m`);
|
|
2555
|
-
}
|
|
2556
|
-
}
|
|
2557
|
-
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
2558
|
-
const totalDuration = results.reduce((sum, r) => sum + (r.stats?.duration || 0), 0);
|
|
2559
|
-
const totalEndpoints = results.reduce((sum, r) => sum + (r.stats?.endpoints || 0), 0);
|
|
2560
|
-
const totalSchemas = results.reduce((sum, r) => sum + (r.stats?.schemas || 0), 0);
|
|
2561
|
-
if (failCount === 0) console.log(`\x1b[32m✓\x1b[0m API Code Gen - Complete (\x1b[90m${successCount}/${options.length} succeeded\x1b[0m, ${totalEndpoints} endpoints, ${totalSchemas} schemas, ${totalDuration}ms\x1b[0m)`);
|
|
2562
|
-
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)`);
|
|
2563
|
-
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3501
|
+
config(_config, env) {
|
|
3502
|
+
mode = env?.command || "unknown";
|
|
2564
3503
|
return {};
|
|
3504
|
+
},
|
|
3505
|
+
async buildStart() {
|
|
3506
|
+
for (const option of options) {
|
|
3507
|
+
const specPath = toWatchPath(option.spec);
|
|
3508
|
+
if (specPath) this.addWatchFile(specPath);
|
|
3509
|
+
}
|
|
3510
|
+
printResults(await Promise.all(options.map(generateForOption)));
|
|
3511
|
+
},
|
|
3512
|
+
configureServer(server) {
|
|
3513
|
+
for (const option of options) {
|
|
3514
|
+
const specPath = toWatchPath(option.spec);
|
|
3515
|
+
if (!specPath || watched.has(specPath)) continue;
|
|
3516
|
+
watched.add(specPath);
|
|
3517
|
+
server.watcher.add(specPath);
|
|
3518
|
+
const onChange = async (changed) => {
|
|
3519
|
+
if (node_path.default.resolve(changed) !== node_path.default.resolve(specPath)) return;
|
|
3520
|
+
await regenerate(option);
|
|
3521
|
+
server.ws.send({ type: "full-reload" });
|
|
3522
|
+
};
|
|
3523
|
+
server.watcher.on("change", onChange);
|
|
3524
|
+
server.watcher.on("add", onChange);
|
|
3525
|
+
}
|
|
2565
3526
|
}
|
|
2566
3527
|
};
|
|
2567
3528
|
}
|
|
2568
|
-
//#endregion
|
|
2569
3529
|
exports.Adapter = Adapter;
|
|
2570
3530
|
exports.Adaptors = Adaptors;
|
|
2571
3531
|
exports.ApicodegenError = ApicodegenError;
|
|
@@ -2587,16 +3547,24 @@ exports.SchemaFormatType = SchemaFormatType;
|
|
|
2587
3547
|
exports.SchemaType = SchemaType;
|
|
2588
3548
|
exports.SuccessHttpStatusCode = SuccessHttpStatusCode;
|
|
2589
3549
|
exports.apiCodeGenPlugin = apiCodeGenPlugin;
|
|
3550
|
+
exports.authAccess = authAccess;
|
|
3551
|
+
exports.authHeaderEntries = authHeaderEntries;
|
|
2590
3552
|
exports.codeGen = codeGen;
|
|
2591
3553
|
exports.configToCLIOptions = configToCLIOptions;
|
|
3554
|
+
exports.cookieHeaderExpression = cookieHeaderExpression;
|
|
2592
3555
|
exports.createErrors = createErrors;
|
|
3556
|
+
exports.fetchSignalExpression = fetchSignalExpression;
|
|
2593
3557
|
exports.formatError = formatError;
|
|
2594
3558
|
exports.isApicodegenError = isApicodegenError;
|
|
2595
3559
|
exports.loadConfig = loadConfig;
|
|
3560
|
+
exports.loadConfigs = loadConfigs;
|
|
2596
3561
|
exports.mergeConfigs = mergeConfigs;
|
|
3562
|
+
exports.optionalAccess = optionalAccess;
|
|
2597
3563
|
exports.printError = printError;
|
|
2598
3564
|
exports.toProviderOptions = toProviderOptions;
|
|
2599
3565
|
exports.validateConfig = validateConfig;
|
|
3566
|
+
exports.validateConfigShape = validateConfigShape;
|
|
3567
|
+
exports.withRequestHeaders = withRequestHeaders;
|
|
2600
3568
|
exports.wrapError = wrapError;
|
|
2601
3569
|
|
|
2602
3570
|
//# sourceMappingURL=index.cjs.map
|