@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/npm/index.mjs CHANGED
@@ -1,20 +1,16 @@
1
- import { readFile, stat, writeFile } from "node:fs/promises";
1
+ import { NodeFlags, SyntaxKind, addSyntheticLeadingComment, createPrinter, factory, isEnumDeclaration, isInterfaceDeclaration, isTypeAliasDeclaration } from "typescript";
2
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
3
+ import { pathToFileURL } from "node:url";
2
4
  import { Agent, request } from "undici";
3
- import { NodeFlags, SyntaxKind, addSyntheticLeadingComment, createPrinter, factory } from "typescript";
5
+ import { parse } from "yaml";
6
+ import path, { dirname, join } from "node:path";
4
7
  import { format } from "prettier";
5
- import path from "node:path";
6
8
  import fs from "fs-extra";
7
9
  import { createScopedLogger } from "@moccona/logger";
10
+ import { execaCommand } from "execa";
8
11
  import { createHash } from "node:crypto";
9
- //#region src/core/base/Adaptor.ts
10
- /**
11
- * Base adapter for tool
12
- * This abstract class serves as the foundation for implementing adapters for different code generation tools
13
- */
14
- var Adapter = class {};
15
- //#endregion
16
- //#region src/core/constants/keywords.ts
17
- const typescriptKeywords = new Set([
12
+ // src/core/constants/keywords.ts
13
+ const typescriptKeywords = /* @__PURE__ */ new Set([
18
14
  "break",
19
15
  "case",
20
16
  "catch",
@@ -90,8 +86,7 @@ const typescriptKeywords = new Set([
90
86
  "undefined",
91
87
  "bigint"
92
88
  ]);
93
- //#endregion
94
- //#region src/core/errors.ts
89
+ // src/core/errors.ts
95
90
  /**
96
91
  * Error handling utilities for api-codegen
97
92
  */
@@ -288,6 +283,15 @@ const createErrors = {
288
283
  cause
289
284
  });
290
285
  },
286
+ writeFailed(path, cause) {
287
+ return new ApicodegenError({
288
+ code: ErrorCodes.GENERATION_FAILED,
289
+ message: "Failed to write generated code",
290
+ location: path,
291
+ suggestions: ["Check that the output path is writable", "Ensure the output directory can be created"],
292
+ cause
293
+ });
294
+ },
291
295
  typeCheckFailed(path, _errors, cause) {
292
296
  return new ApicodegenError({
293
297
  code: ErrorCodes.TYPE_CHECK_FAILED,
@@ -335,8 +339,7 @@ function wrapError(error, context) {
335
339
  function isApicodegenError(error) {
336
340
  return error instanceof ApicodegenError;
337
341
  }
338
- //#endregion
339
- //#region src/core/interface.ts
342
+ // src/core/interface.ts
340
343
  let SchemaType = /* @__PURE__ */ function(SchemaType) {
341
344
  SchemaType["schemas"] = "schemas";
342
345
  SchemaType["parameters"] = "parameters";
@@ -400,8 +403,7 @@ let Adaptors = /* @__PURE__ */ function(Adaptors) {
400
403
  Adaptors["axios"] = "axios";
401
404
  return Adaptors;
402
405
  }({});
403
- //#endregion
404
- //#region src/core/base/Base.ts
406
+ // src/core/base/Base.ts
405
407
  /**
406
408
  * @file Base class implementation
407
409
  * @author wp.l
@@ -472,6 +474,17 @@ var Base = class Base {
472
474
  return name + suffix;
473
475
  }
474
476
  /**
477
+ * Converts arbitrary text into a legal TypeScript variable identifier.
478
+ * Keywords keep the `_` suffix that `normalize` adds, since `camelCase`
479
+ * would otherwise strip it and emit a reserved word.
480
+ * @param text - Input text.
481
+ * @returns - A legal identifier.
482
+ */
483
+ static toIdentifier(text) {
484
+ const name = Base.camelCase(Base.normalize(text));
485
+ return typescriptKeywords.has(name) ? `${name}_` : name;
486
+ }
487
+ /**
475
488
  * Normalizes a string by replacing special characters and avoiding TypeScript keywords.
476
489
  * @param text - Input text to normalize.
477
490
  * @returns - The normalized string.
@@ -585,18 +598,39 @@ var Base = class Base {
585
598
  if (error?.code === "ENOENT") throw createErrors.specNotFound(filePath, error);
586
599
  throw new Error(`Failed to read OpenAPI spec from ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
587
600
  }
601
+ return Base.parseDoc(raw, filePath);
602
+ }
603
+ /**
604
+ * Parses an OpenAPI document from JSON or YAML text.
605
+ *
606
+ * JSON is attempted first for a clearer syntax error on JSON files; YAML
607
+ * then handles `.yaml` / `.yml` specs. Any failure is reported as
608
+ * `E_SPEC_PARSE_FAILED` with the source path attached.
609
+ *
610
+ * @param raw - Raw spec content.
611
+ * @param source - Path or URL used in error messages.
612
+ * @returns - The parsed document.
613
+ */
614
+ static parseDoc(raw, source) {
615
+ let parsed;
588
616
  try {
589
- return JSON.parse(raw);
590
- } catch (error) {
591
- throw createErrors.specParseFailed(filePath, void 0, void 0, error);
617
+ parsed = JSON.parse(raw);
618
+ } catch {
619
+ try {
620
+ parsed = parse(raw);
621
+ } catch (error) {
622
+ throw createErrors.specParseFailed(source, void 0, void 0, error);
623
+ }
592
624
  }
625
+ if (parsed === null || typeof parsed !== "object") throw createErrors.specParseFailed(source, void 0, void 0, /* @__PURE__ */ new Error("Spec must be a JSON or YAML object"));
626
+ return parsed;
593
627
  }
594
628
  /**
595
629
  * Fetches documentation from a given URL.
596
630
  *
597
631
  * Supports three transport modes:
598
- * - `file://...` URLs → read from filesystem (parsed as JSON)
599
- * - absolute filesystem paths → read from filesystem (parsed as JSON)
632
+ * - `file://...` URLs → read from filesystem (JSON or YAML)
633
+ * - absolute filesystem paths → read from filesystem (JSON or YAML)
600
634
  * - `http(s)://...` URLs (and unrecognised inputs like relative paths)
601
635
  * → fetched via undici (existing behavior)
602
636
  *
@@ -606,22 +640,139 @@ var Base = class Base {
606
640
  *
607
641
  * @param url - The URL or filesystem path to fetch the documentation from.
608
642
  * @param requestInit - Additional request parameters (only used for http(s)).
643
+ * TLS certificates are verified by default; set `insecure: true` to opt out.
609
644
  * @returns - A promise resolving to the fetched documentation data.
610
645
  */
611
646
  static async fetchDoc(url, requestInit = {}) {
612
647
  const { transport, source } = Base.resolveSpecURL(url);
613
648
  if (transport === "file") return Base.readLocalDoc(source);
649
+ const { insecure = false, ...init } = requestInit;
614
650
  const { body, statusCode } = await request(source, {
615
651
  method: "GET",
616
- dispatcher: new Agent({ connect: { rejectUnauthorized: false } }),
617
- ...requestInit
652
+ ...insecure ? { dispatcher: new Agent({ connect: { rejectUnauthorized: false } }) } : {},
653
+ ...init
618
654
  });
619
655
  if (statusCode >= 400) throw new Error(`Failed to fetch OpenAPI documentation from ${source}: HTTP ${statusCode}`);
620
- try {
621
- return body.json();
622
- } catch (error) {
623
- throw new Error(`Failed to parse JSON response from ${source}: ${error instanceof Error ? error.message : String(error)}`);
656
+ return Base.parseDoc(await body.text(), source);
657
+ }
658
+ /**
659
+ * Copies external `$ref` targets (other files or remote URLs) into the root
660
+ * document and rewrites the refs to local ones. Objects are registered
661
+ * before their children are walked, so cycles keep working.
662
+ *
663
+ * External refs are placed in the component section implied by their
664
+ * fragment (`schemas` by default); a generated local `$ref` points at the
665
+ * copy.
666
+ *
667
+ * @param doc - Parsed root document (mutated in place).
668
+ * @param source - Absolute path or URL of the root document.
669
+ * @param requestInit - Request options for remote refs.
670
+ * @returns - The same document with external refs resolved.
671
+ */
672
+ static async bundleExternalRefs(doc, source, requestInit = {}) {
673
+ const root = doc;
674
+ const isV2 = typeof root.swagger === "string";
675
+ const rootURL = Base.resolveSpecURL(source).transport === "file" ? pathToFileURL(source).href : source;
676
+ const docs = /* @__PURE__ */ new Map([[rootURL, root]]);
677
+ const registered = /* @__PURE__ */ new Map();
678
+ const loadDoc = async (url) => {
679
+ const cached = docs.get(url);
680
+ if (cached !== void 0) return cached;
681
+ const loaded = await Base.fetchDoc(url, requestInit);
682
+ docs.set(url, loaded);
683
+ return loaded;
684
+ };
685
+ const containerFor = (ref) => {
686
+ const section = Base.externalRefSection(ref, isV2);
687
+ if (isV2) {
688
+ root[section] ??= {};
689
+ return {
690
+ record: root[section],
691
+ prefix: `#/${section}/`
692
+ };
693
+ }
694
+ root.components ??= {};
695
+ root.components[section] ??= {};
696
+ return {
697
+ record: root.components[section],
698
+ prefix: `#/components/${section}/`
699
+ };
700
+ };
701
+ const register = async (absolute) => {
702
+ const existing = registered.get(absolute);
703
+ if (existing) return existing;
704
+ const hashIndex = absolute.indexOf("#");
705
+ const docURL = hashIndex === -1 ? absolute : absolute.slice(0, hashIndex);
706
+ const fragment = hashIndex === -1 ? "" : absolute.slice(hashIndex);
707
+ const externalDoc = await loadDoc(docURL);
708
+ const { record, prefix } = containerFor(fragment);
709
+ const target = Base.resolveJSONPointer(externalDoc, fragment);
710
+ if (target === void 0) return `${prefix}unknown`;
711
+ const baseName = Base.externalRefName(fragment, docURL);
712
+ let name = baseName;
713
+ let suffix = 2;
714
+ while (name in record) {
715
+ name = `${baseName}${suffix}`;
716
+ suffix++;
717
+ }
718
+ registered.set(absolute, prefix + name);
719
+ record[name] = target;
720
+ await walk(target, docURL);
721
+ return prefix + name;
722
+ };
723
+ const walk = async (value, docURL) => {
724
+ if (Array.isArray(value)) {
725
+ for (const item of value) await walk(item, docURL);
726
+ return;
727
+ }
728
+ if (value === null || typeof value !== "object") return;
729
+ const object = value;
730
+ if (typeof object.$ref === "string") {
731
+ const ref = object.$ref;
732
+ if (ref.startsWith("#") && docURL === rootURL) return;
733
+ const absolute = ref.startsWith("#") ? docURL + ref : new URL(ref, docURL).href;
734
+ if ((docURL.startsWith("http://") || docURL.startsWith("https://")) && !absolute.startsWith("http://") && !absolute.startsWith("https://")) throw new Error(`Refusing to resolve external $ref from a remote document: ${absolute}`);
735
+ object.$ref = await register(absolute);
736
+ return;
737
+ }
738
+ for (const key of Object.keys(object)) await walk(object[key], docURL);
739
+ };
740
+ await walk(root, rootURL);
741
+ return doc;
742
+ }
743
+ /** Component section an external ref belongs to. */
744
+ static externalRefSection(ref, isV2) {
745
+ if (isV2) {
746
+ if (ref.includes("/parameters/")) return "parameters";
747
+ if (ref.includes("/responses/")) return "responses";
748
+ return "definitions";
624
749
  }
750
+ if (ref.includes("/parameters/")) return "parameters";
751
+ if (ref.includes("/responses/")) return "responses";
752
+ if (ref.includes("/requestBodies/")) return "requestBodies";
753
+ return "schemas";
754
+ }
755
+ /** Local component name derived from the ref fragment or file name. */
756
+ static externalRefName(fragment, docURL) {
757
+ let name = fragment.replace(/^#/, "").split("/").filter(Boolean).map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")).at(-1) ?? "";
758
+ if (!name) try {
759
+ name = new URL(docURL).pathname.split("/").pop() ?? "";
760
+ } catch {
761
+ name = "";
762
+ }
763
+ name = name.replace(/\.(json|ya?ml)$/i, "").replace(/[^A-Za-z0-9_.-]/g, "_");
764
+ return name || "External";
765
+ }
766
+ /** Resolves a `#/a/b` JSON pointer inside a parsed document. */
767
+ static resolveJSONPointer(doc, fragment) {
768
+ if (!fragment) return doc;
769
+ const parts = fragment.replace(/^#\/?/, "").split("/").filter(Boolean).map((part) => decodeURIComponent(part).replaceAll("~1", "/").replaceAll("~0", "~"));
770
+ let current = doc;
771
+ for (const part of parts) {
772
+ if (current === null || typeof current !== "object") return void 0;
773
+ current = current[part];
774
+ }
775
+ return current;
625
776
  }
626
777
  /**
627
778
  * Determines the media type from a given media type string.
@@ -691,8 +842,72 @@ var Base = class Base {
691
842
  return typeof schema === "object" && schema !== null && "$ref" in schema && typeof schema.$ref === "string";
692
843
  }
693
844
  };
694
- //#endregion
695
- //#region src/core/base/Provider.ts
845
+ // src/core/base/Adaptor.ts
846
+ /** `options?.name` */
847
+ function optionalAccess(control, name) {
848
+ return factory.createPropertyAccessChain(factory.createIdentifier(control.name), factory.createToken(SyntaxKind.QuestionDotToken), factory.createIdentifier(name));
849
+ }
850
+ /**
851
+ * `options?.signal && options?.timeout ? AbortSignal.any([...]) : ...`,
852
+ * combining a caller signal with a timeout when both are present.
853
+ */
854
+ function fetchSignalExpression(control) {
855
+ const signal = optionalAccess(control, "signal");
856
+ const timeout = optionalAccess(control, "timeout");
857
+ const timeoutSignal = () => factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("AbortSignal"), factory.createIdentifier("timeout")), void 0, [timeout]);
858
+ const both = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("AbortSignal"), factory.createIdentifier("any")), void 0, [factory.createArrayLiteralExpression([signal, timeoutSignal()])]);
859
+ return factory.createConditionalExpression(signal, factory.createToken(SyntaxKind.QuestionToken), factory.createConditionalExpression(timeout, factory.createToken(SyntaxKind.QuestionToken), both, factory.createToken(SyntaxKind.ColonToken), signal), factory.createToken(SyntaxKind.ColonToken), factory.createConditionalExpression(timeout, factory.createToken(SyntaxKind.QuestionToken), timeoutSignal(), factory.createToken(SyntaxKind.ColonToken), factory.createIdentifier("undefined")));
860
+ }
861
+ /**
862
+ * Header entries plus a spread of caller-supplied headers.
863
+ */
864
+ function withRequestHeaders(entries, control) {
865
+ if (!control) return entries;
866
+ return [...entries, factory.createSpreadAssignment(optionalAccess(control, "headers"))];
867
+ }
868
+ /** `auth?.["scheme"]` */
869
+ function authAccess(auth, scheme) {
870
+ return factory.createElementAccessChain(factory.createIdentifier(auth.name), factory.createToken(SyntaxKind.QuestionDotToken), factory.createStringLiteral(scheme));
871
+ }
872
+ /**
873
+ * Header entries (conditional spreads) for auth schemes sent as headers.
874
+ */
875
+ function authHeaderEntries(auth) {
876
+ return auth.injections.filter((injection) => injection.location === "header").map((injection) => {
877
+ const access = authAccess(auth, injection.scheme);
878
+ const hasValue = factory.createBinaryExpression(access, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword));
879
+ let value;
880
+ let condition = hasValue;
881
+ if (injection.kind === "basic") {
882
+ condition = factory.createBinaryExpression(access, factory.createToken(SyntaxKind.AmpersandAmpersandToken), factory.createBinaryExpression(factory.createTypeOfExpression(access), factory.createToken(SyntaxKind.EqualsEqualsEqualsToken), factory.createStringLiteral("object")));
883
+ const credentials = factory.createTemplateExpression(factory.createTemplateHead(""), [factory.createTemplateSpan(factory.createPropertyAccessExpression(access, "username"), factory.createTemplateMiddle(":")), factory.createTemplateSpan(factory.createPropertyAccessExpression(access, "password"), factory.createTemplateTail(""))]);
884
+ value = factory.createTemplateExpression(factory.createTemplateHead("Basic "), [factory.createTemplateSpan(factory.createCallExpression(factory.createIdentifier("btoa"), void 0, [credentials]), factory.createTemplateTail(""))]);
885
+ } else if (injection.kind === "bearer") value = factory.createTemplateExpression(factory.createTemplateHead("Bearer "), [factory.createTemplateSpan(factory.createCallExpression(factory.createIdentifier("String"), void 0, [access]), factory.createTemplateTail(""))]);
886
+ else value = factory.createCallExpression(factory.createIdentifier("String"), void 0, [access]);
887
+ return factory.createSpreadAssignment(factory.createConditionalExpression(condition, factory.createToken(SyntaxKind.QuestionToken), factory.createObjectLiteralExpression([factory.createPropertyAssignment(factory.createStringLiteral(injection.name), value)], false), factory.createToken(SyntaxKind.ColonToken), factory.createObjectLiteralExpression([], false)));
888
+ });
889
+ }
890
+ /**
891
+ * Builds a `Cookie` header value from OpenAPI cookie parameters.
892
+ * Undefined/null values are filtered out at runtime.
893
+ */
894
+ function cookieHeaderExpression(parameters, auth) {
895
+ const entries = parameters.filter((p) => p.in === "cookie").map((parameter) => {
896
+ const id = factory.createIdentifier(Base.toIdentifier(parameter.name));
897
+ return factory.createConditionalExpression(factory.createBinaryExpression(id, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createToken(SyntaxKind.QuestionToken), factory.createTemplateExpression(factory.createTemplateHead(`${parameter.name}=`), [factory.createTemplateSpan(factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [id])]), factory.createTemplateTail(""))]), factory.createToken(SyntaxKind.ColonToken), factory.createStringLiteral(""));
898
+ });
899
+ const authEntries = auth ? auth.injections.filter((injection) => injection.location === "cookie").map((injection) => {
900
+ const access = authAccess(auth, injection.scheme);
901
+ return factory.createConditionalExpression(factory.createBinaryExpression(access, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createToken(SyntaxKind.QuestionToken), factory.createTemplateExpression(factory.createTemplateHead(`${injection.name}=`), [factory.createTemplateSpan(factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [access])]), factory.createTemplateTail(""))]), factory.createToken(SyntaxKind.ColonToken), factory.createStringLiteral(""));
902
+ }) : [];
903
+ return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createArrayLiteralExpression([...entries, ...authEntries], true), factory.createIdentifier("filter")), void 0, [factory.createIdentifier("Boolean")]), factory.createIdentifier("join")), void 0, [factory.createStringLiteral("; ")]);
904
+ }
905
+ /**
906
+ * Base adapter for tool
907
+ * This abstract class serves as the foundation for implementing adapters for different code generation tools
908
+ */
909
+ var Adapter = class {};
910
+ // src/core/base/Provider.ts
696
911
  /**
697
912
  * Abstract Provider Class.
698
913
  *
@@ -736,6 +951,8 @@ var Provider = class {
736
951
  responses = {};
737
952
  /** collection of request bodies indexed by name */
738
953
  requestBodies = {};
954
+ /** security schemes declared by the document */
955
+ securitySchemes = {};
739
956
  /** collection of API endpoints (operations) indexed by path */
740
957
  apis = {};
741
958
  /** URL for fetching API documentation */
@@ -759,17 +976,17 @@ var Provider = class {
759
976
  this.output = initOptions.output ?? ".";
760
977
  this.requestOptions = initOptions.requestOptions ?? {};
761
978
  this.importClientSource = initOptions.importClientSource ?? "";
762
- const { enums, schemas, requestBodies, responses, parameters, apis } = this.parse(doc);
979
+ const { enums, schemas, requestBodies, responses, parameters, securitySchemes, apis } = this.parse(doc);
763
980
  this.enums = enums;
764
981
  this.schemas = schemas;
765
982
  this.responses = responses;
766
983
  this.parameters = parameters;
767
984
  this.requestBodies = requestBodies;
985
+ this.securitySchemes = securitySchemes;
768
986
  this.apis = apis;
769
987
  }
770
988
  };
771
- //#endregion
772
- //#region src/core/generator/naming.ts
989
+ // src/core/generator/naming.ts
773
990
  /**
774
991
  * Create a per-generation unique-name resolver.
775
992
  *
@@ -792,8 +1009,7 @@ const createUniqueNameResolver = () => {
792
1009
  return next === 1 ? name : `${name}${next}`;
793
1010
  };
794
1011
  };
795
- //#endregion
796
- //#region src/core/generator/index.ts
1012
+ // src/core/generator/index.ts
797
1013
  var Generator = class Generator {
798
1014
  /**
799
1015
  * Converts an array of TypeScript statements into a formatted string of code.
@@ -809,9 +1025,10 @@ var Generator = class Generator {
809
1025
  }
810
1026
  static async write(code, filepath) {
811
1027
  try {
1028
+ await mkdir(dirname(filepath), { recursive: true });
812
1029
  await writeFile(filepath, code);
813
1030
  } catch (error) {
814
- console.error(error);
1031
+ throw createErrors.writeFailed(filepath, error instanceof Error ? error : new Error(String(error)));
815
1032
  }
816
1033
  }
817
1034
  /**
@@ -823,22 +1040,84 @@ var Generator = class Generator {
823
1040
  * @param basePath - Optional base path to prepend (default: "").
824
1041
  * @returns A TypeScript template expressi
825
1042
  */
826
- static toUrlTemplate(path, parameters, basePath = "") {
1043
+ static toUrlTemplate(path, parameters, basePath = "", auth) {
1044
+ const pathExpression = Generator.toPathTemplate(path, basePath);
827
1045
  const queryParameters = parameters.filter((p) => p.in === "query");
828
- if (queryParameters.length > 0) {
829
- const queryString = queryParameters.map((qp, index) => `${index === 0 ? "?" : "&"}${encodeURIComponent(qp.name)}={${Base.camelCase(Base.normalize(qp.name))}}`).join("");
830
- path += queryString;
831
- }
1046
+ const hasAuthQuery = auth?.injections.some((injection) => injection.location === "query");
1047
+ if (queryParameters.length === 0 && !hasAuthQuery) return pathExpression;
1048
+ return factory.createBinaryExpression(pathExpression, factory.createToken(SyntaxKind.PlusToken), Generator.toQueryStringExpression(queryParameters, auth));
1049
+ }
1050
+ /**
1051
+ * Builds the path part of a URL, encoding every `{param}` interpolation.
1052
+ */
1053
+ static toPathTemplate(path, basePath) {
832
1054
  const pathSegments = path.replaceAll("{", "${").split("$").filter(Boolean);
833
1055
  if (pathSegments.length === 1) return factory.createNoSubstitutionTemplateLiteral(basePath + path);
834
1056
  return factory.createTemplateExpression(factory.createTemplateHead(basePath + pathSegments[0]), pathSegments.slice(1).map((segment, index) => {
835
1057
  const match = /^{(.+)}(.+)?/gm.exec(segment);
836
1058
  const isLastSegment = index === pathSegments.length - 2;
837
1059
  if (!match) throw new Error(`Invalid path segment: ${segment}`);
838
- return factory.createTemplateSpan(factory.createIdentifier(match[1]), !isLastSegment ? factory.createTemplateMiddle(match[2]) : factory.createTemplateTail(match[2] || ""));
1060
+ return factory.createTemplateSpan(factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.toIdentifier(match[1]))])]), !isLastSegment ? factory.createTemplateMiddle(match[2]) : factory.createTemplateTail(match[2] || ""));
839
1061
  }));
840
1062
  }
841
1063
  /**
1064
+ * Emits an IIFE that builds a query string, omitting undefined/null
1065
+ * values and honouring array `explode` / delimiter styles.
1066
+ */
1067
+ static toQueryStringExpression(parameters, auth) {
1068
+ const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
1069
+ const unique = (base) => {
1070
+ let name = base;
1071
+ let suffix = 2;
1072
+ while (taken.has(name)) name = `${base}${suffix++}`;
1073
+ taken.add(name);
1074
+ return name;
1075
+ };
1076
+ const qName = unique("q");
1077
+ const vName = unique("v");
1078
+ const sName = unique("s");
1079
+ const statements = [factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier(qName), void 0, void 0, factory.createNewExpression(factory.createIdentifier("URLSearchParams"), void 0, []))], NodeFlags.Const))];
1080
+ const append = (name, value) => factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier(qName), factory.createIdentifier("append")), void 0, [typeof name === "string" ? factory.createStringLiteral(name) : name, value]));
1081
+ const stringify = (value) => factory.createCallExpression(factory.createIdentifier("String"), void 0, [value]);
1082
+ const isNotNull = (value) => factory.createBinaryExpression(value, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword));
1083
+ for (const parameter of parameters) {
1084
+ const id = factory.createIdentifier(Base.toIdentifier(parameter.name));
1085
+ const isArray = parameter.schema?.type === "array";
1086
+ if (parameter.style === "deepObject" && !isArray) {
1087
+ const addName = unique("addDeepObject");
1088
+ const prefix = factory.createIdentifier("prefix");
1089
+ const value = factory.createIdentifier("value");
1090
+ const key = factory.createIdentifier("k");
1091
+ const entry = factory.createIdentifier("v");
1092
+ const path = factory.createTemplateExpression(factory.createTemplateHead(""), [factory.createTemplateSpan(prefix, factory.createTemplateMiddle("[")), factory.createTemplateSpan(key, factory.createTemplateTail("]"))]);
1093
+ const recurse = factory.createCallExpression(factory.createIdentifier(addName), void 0, [path, factory.createAsExpression(entry, factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), factory.createToken(SyntaxKind.UnknownKeyword)]))]);
1094
+ const forOf = factory.createForOfStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createArrayBindingPattern([factory.createBindingElement(void 0, void 0, key), factory.createBindingElement(void 0, void 0, entry)]))], NodeFlags.Const), factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), factory.createIdentifier("entries")), void 0, [value]), factory.createBlock([factory.createIfStatement(factory.createBinaryExpression(entry, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([factory.createIfStatement(factory.createBinaryExpression(factory.createTypeOfExpression(entry), factory.createToken(SyntaxKind.EqualsEqualsEqualsToken), factory.createStringLiteral("object")), factory.createExpressionStatement(recurse), append(path, stringify(entry)))], true))], true));
1095
+ const declaration = factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier(addName), void 0, void 0, factory.createArrowFunction(void 0, void 0, [factory.createParameterDeclaration(void 0, void 0, prefix, void 0, factory.createKeywordTypeNode(SyntaxKind.StringKeyword)), factory.createParameterDeclaration(void 0, void 0, value, void 0, factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), factory.createToken(SyntaxKind.UnknownKeyword)]))], void 0, factory.createToken(SyntaxKind.EqualsGreaterThanToken), factory.createBlock([forOf], true)))], NodeFlags.Const));
1096
+ const invoke = factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier(addName), void 0, [factory.createStringLiteral(parameter.name), factory.createAsExpression(id, factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), factory.createToken(SyntaxKind.UnknownKeyword)]))]));
1097
+ statements.push(parameter.required ? factory.createBlock([declaration, invoke], true) : factory.createIfStatement(isNotNull(id), factory.createBlock([declaration, invoke], true)));
1098
+ continue;
1099
+ }
1100
+ if (isArray) {
1101
+ if (parameter.explode ?? (parameter.style === void 0 || parameter.style === "form")) {
1102
+ statements.push(factory.createForOfStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier(vName), void 0, void 0, void 0)], NodeFlags.Const), factory.createBinaryExpression(id, factory.createToken(SyntaxKind.QuestionQuestionToken), factory.createArrayLiteralExpression([])), factory.createBlock([append(parameter.name, stringify(factory.createIdentifier(vName)))], true)));
1103
+ continue;
1104
+ }
1105
+ const separator = parameter.style === "spaceDelimited" ? " " : parameter.style === "pipeDelimited" ? "|" : ",";
1106
+ const join = factory.createCallExpression(factory.createPropertyAccessExpression(id, factory.createIdentifier("join")), void 0, [factory.createStringLiteral(separator)]);
1107
+ statements.push(factory.createIfStatement(isNotNull(id), factory.createBlock([append(parameter.name, join)], true)));
1108
+ continue;
1109
+ }
1110
+ const statement = append(parameter.name, stringify(id));
1111
+ statements.push(parameter.required ? statement : factory.createIfStatement(isNotNull(id), factory.createBlock([statement], true)));
1112
+ }
1113
+ if (auth) for (const injection of auth.injections.filter((item) => item.location === "query")) {
1114
+ const access = authAccess(auth, injection.scheme);
1115
+ statements.push(factory.createIfStatement(factory.createBinaryExpression(access, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([append(injection.name, stringify(access))], true)));
1116
+ }
1117
+ statements.push(factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier(sName), void 0, void 0, factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier(qName), factory.createIdentifier("toString")), void 0, []))], NodeFlags.Const)), factory.createReturnStatement(factory.createConditionalExpression(factory.createIdentifier(sName), factory.createToken(SyntaxKind.QuestionToken), factory.createTemplateExpression(factory.createTemplateHead("?"), [factory.createTemplateSpan(factory.createIdentifier(sName), factory.createTemplateTail(""))]), factory.createToken(SyntaxKind.ColonToken), factory.createStringLiteral(""))));
1118
+ return factory.createCallExpression(factory.createParenthesizedExpression(factory.createArrowFunction(void 0, void 0, [], void 0, factory.createToken(SyntaxKind.EqualsGreaterThanToken), factory.createBlock(statements, true))), void 0, []);
1119
+ }
1120
+ /**
842
1121
  * Adds synthetic comments to a TypeScript AST node.
843
1122
  *
844
1123
  * @param node - The target AST node.
@@ -855,7 +1134,7 @@ var Generator = class Generator {
855
1134
  if (comment.tag) return `* @${comment.tag} ${comment.comment ?? ""}`;
856
1135
  return `* ${comment.comment}`;
857
1136
  };
858
- const formattedComments = comments.map(formatComment).join("\n").trim() + "\n";
1137
+ const formattedComments = comments.map(formatComment).join("\n").replaceAll("*/", "*\\/").trim() + "\n";
859
1138
  addSyntheticLeadingComment(node, SyntaxKind.MultiLineCommentTrivia, formattedComments, true);
860
1139
  }
861
1140
  /**
@@ -872,6 +1151,16 @@ var Generator = class Generator {
872
1151
  const nonArraySchema = schema;
873
1152
  return nonArraySchema.format === "blob" || nonArraySchema.format === "binary" || nonArraySchema.type === "file";
874
1153
  }
1154
+ /** Whether a schema is a primitive text part (not binary, ref, or object). */
1155
+ static isTextSchema(schema) {
1156
+ if (!schema || schema.isRef) return false;
1157
+ if (Generator.isBinarySchema(schema)) return false;
1158
+ if (schema.type === "array") {
1159
+ const items = schema.items;
1160
+ return items ? Generator.isTextSchema(items) : false;
1161
+ }
1162
+ return schema.type === "string" || schema.type === "integer" || schema.type === "number" || schema.type === "boolean";
1163
+ }
875
1164
  static schemaToTypeString(schema) {
876
1165
  if (schema.type === "array") {
877
1166
  const arraySchema = schema;
@@ -890,7 +1179,7 @@ var Generator = class Generator {
890
1179
  static generateParamTags(parameters, requestBody) {
891
1180
  const tags = [];
892
1181
  for (const p of parameters) {
893
- const paramName = Base.camelCase(Base.normalize(p.name));
1182
+ const paramName = Base.toIdentifier(p.name);
894
1183
  let paramType = "unknown";
895
1184
  if (p.schema) paramType = Generator.schemaToTypeString(p.schema);
896
1185
  const isOptional = p.required === false;
@@ -899,7 +1188,7 @@ var Generator = class Generator {
899
1188
  tag: "param",
900
1189
  paramName,
901
1190
  type: `${paramType}${isOptional ? " | undefined" : ""}`,
902
- comment: `${inPrefix}${p.description ?? ""}`
1191
+ comment: `${inPrefix}${p.description?.trim() ?? ""}`
903
1192
  });
904
1193
  }
905
1194
  if (requestBody?.schema && "properties" in requestBody.schema) {
@@ -914,7 +1203,7 @@ var Generator = class Generator {
914
1203
  tag: "param",
915
1204
  paramName,
916
1205
  type: `${paramType}${isOptional ? " | undefined" : ""}`,
917
- comment: schema.description ?? ""
1206
+ comment: schema.description?.trim() ?? ""
918
1207
  });
919
1208
  }
920
1209
  }
@@ -923,8 +1212,47 @@ var Generator = class Generator {
923
1212
  static toRequestBodyTypeNode(schema) {
924
1213
  return factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("req"), void 0, Generator.toTypeNode(schema));
925
1214
  }
1215
+ /**
1216
+ * Narrows a `oneOf` member with its discriminator mapping value:
1217
+ * `Cat & { petType: 'cat' }`.
1218
+ */
1219
+ static discriminatedMember(schema, discriminator) {
1220
+ const node = Generator.toTypeNode(schema);
1221
+ const ref = schema.ref;
1222
+ if (!ref) return node;
1223
+ const name = Base.ref2name(ref);
1224
+ const value = Object.entries(discriminator.mapping ?? {}).find(([, target]) => Base.ref2name(target) === name)?.[0];
1225
+ if (value === void 0) return node;
1226
+ return factory.createIntersectionTypeNode([node, factory.createTypeLiteralNode([factory.createPropertySignature(void 0, factory.createStringLiteral(discriminator.propertyName), void 0, factory.createLiteralTypeNode(factory.createStringLiteral(value)))])]);
1227
+ }
926
1228
  static toTypeNode(schema) {
1229
+ if ("const" in schema && schema.const !== void 0) return Generator.toLiteralTypeNode(schema.const);
1230
+ const base = Generator.toTypeNodeInner(schema);
1231
+ if (schema.nullable) return factory.createUnionTypeNode([base, factory.createLiteralTypeNode(factory.createNull())]);
1232
+ return base;
1233
+ }
1234
+ static toLiteralTypeNode(value) {
1235
+ if (typeof value === "string") return factory.createLiteralTypeNode(factory.createStringLiteral(value));
1236
+ if (typeof value === "number") return factory.createLiteralTypeNode(factory.createNumericLiteral(value));
1237
+ return factory.createLiteralTypeNode(value ? factory.createTrue() : factory.createFalse());
1238
+ }
1239
+ static primitiveTypeNode(type) {
1240
+ switch (type) {
1241
+ case "string": return factory.createToken(SyntaxKind.StringKeyword);
1242
+ case "integer":
1243
+ case "number": return factory.createToken(SyntaxKind.NumberKeyword);
1244
+ case "boolean": return factory.createToken(SyntaxKind.BooleanKeyword);
1245
+ case "object": return factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), factory.createToken(SyntaxKind.UnknownKeyword)]);
1246
+ default: return factory.createTypeReferenceNode(factory.createIdentifier(Base.upperCamelCase(type)));
1247
+ }
1248
+ }
1249
+ static toTypeNodeInner(schema) {
927
1250
  const { type, ref } = schema;
1251
+ const unionTypes = schema.types;
1252
+ if (unionTypes && unionTypes.length > 0) {
1253
+ const nodes = Generator.deduplicateTypes(unionTypes.map((name) => Generator.primitiveTypeNode(name)));
1254
+ return nodes.length === 1 ? nodes[0] : factory.createUnionTypeNode(nodes);
1255
+ }
928
1256
  if (ref) {
929
1257
  const identify = Base.ref2name(ref);
930
1258
  return factory.createTypeReferenceNode(factory.createIdentifier(identify === "unknown" ? identify : Base.upperCamelCase(identify)));
@@ -936,20 +1264,28 @@ var Generator = class Generator {
936
1264
  }
937
1265
  case "object": {
938
1266
  const propsCount = Object.keys(schema.properties ?? {}).length;
939
- if (!schema.properties || propsCount === 0) return factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), factory.createToken(SyntaxKind.UnknownKeyword)]);
1267
+ const additional = schema.additionalProperties;
1268
+ const additionalValue = additional && additional !== true ? Generator.toTypeNode(additional) : factory.createToken(SyntaxKind.UnknownKeyword);
1269
+ if (!schema.properties || propsCount === 0) return factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), additionalValue]);
940
1270
  const props = Object.keys(schema.properties);
941
1271
  const required = Array.isArray(schema.required) ? schema.required : [];
942
- return factory.createTypeLiteralNode(props.map((propKey) => {
1272
+ const literal = factory.createTypeLiteralNode(props.map((propKey) => {
943
1273
  const propSchema = schema.properties[propKey];
944
1274
  return factory.createPropertySignature(void 0, factory.createStringLiteral(propKey), required.includes(propKey) ? void 0 : factory.createToken(SyntaxKind.QuestionToken), Generator.toTypeNode(propSchema));
945
1275
  }));
1276
+ const additionalProps = schema.additionalProperties;
1277
+ if (additionalProps === void 0 || additionalProps === false) return literal;
1278
+ return factory.createIntersectionTypeNode([literal, factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), additionalProps === true ? factory.createToken(SyntaxKind.UnknownKeyword) : Generator.toTypeNode(additionalProps)])]);
946
1279
  }
947
1280
  case "integer":
948
1281
  case "number":
949
- if (schema.enum) return factory.createUnionTypeNode(schema.enum.map((e) => factory.createLiteralTypeNode(factory.createNumericLiteral(e))));
1282
+ if (schema.enum) {
1283
+ const values = schema.enum.filter((value) => typeof value === "number");
1284
+ if (values.length > 0) return factory.createUnionTypeNode(values.map((value) => factory.createLiteralTypeNode(factory.createNumericLiteral(value))));
1285
+ }
950
1286
  return factory.createToken(SyntaxKind.NumberKeyword);
951
1287
  case "boolean": return factory.createToken(SyntaxKind.BooleanKeyword);
952
- case "file": return factory.createTypeReferenceNode(factory.createIdentifier("Blob"));
1288
+ case "file": return factory.createTypeReferenceNode(factory.createQualifiedName(factory.createIdentifier("globalThis"), factory.createIdentifier("Blob")));
953
1289
  default: {
954
1290
  const { format, oneOf, allOf, anyOf, type, enum: enum_ } = schema;
955
1291
  switch (format) {
@@ -957,12 +1293,16 @@ var Generator = class Generator {
957
1293
  case "string": return factory.createToken(SyntaxKind.StringKeyword);
958
1294
  case "boolean": return factory.createToken(SyntaxKind.BooleanKeyword);
959
1295
  case "blob":
960
- case "binary": return factory.createTypeReferenceNode(factory.createIdentifier("Blob"));
961
- default:
1296
+ case "binary": return factory.createTypeReferenceNode(factory.createQualifiedName(factory.createIdentifier("globalThis"), factory.createIdentifier("Blob")));
1297
+ }
1298
+ if (enum_) {
1299
+ const values = enum_.filter((value) => typeof value === "string");
1300
+ if (values.length > 0) return factory.createUnionTypeNode(values.map((value) => factory.createLiteralTypeNode(factory.createStringLiteral(value))));
962
1301
  }
963
- if (enum_) return factory.createUnionTypeNode(enum_.map((e) => factory.createLiteralTypeNode(factory.createStringLiteral(e))));
964
1302
  if (type === "string") return factory.createToken(SyntaxKind.StringKeyword);
965
1303
  if (oneOf) {
1304
+ const discriminator = schema.discriminator;
1305
+ if (discriminator?.mapping) return factory.createUnionTypeNode(Generator.deduplicateTypes(oneOf.map((member) => Generator.discriminatedMember(member, discriminator))));
966
1306
  const uniqueTypes = Generator.deduplicateTypes(oneOf.map((s) => Generator.toTypeNode(s)));
967
1307
  return factory.createUnionTypeNode(uniqueTypes);
968
1308
  }
@@ -976,6 +1316,12 @@ var Generator = class Generator {
976
1316
  }
977
1317
  return factory.createToken(SyntaxKind.UnknownKeyword);
978
1318
  }
1319
+ static toResponsesTypeNode(responses) {
1320
+ return factory.createTypeLiteralNode(Object.entries(responses).map(([code, mediaTypes]) => {
1321
+ const schema = mediaTypes[0]?.schema;
1322
+ return factory.createPropertySignature(void 0, factory.createStringLiteral(code), void 0, schema ? Generator.toTypeNode(schema) : factory.createToken(SyntaxKind.UnknownKeyword));
1323
+ }));
1324
+ }
979
1325
  static deduplicateTypes(types) {
980
1326
  const seen = /* @__PURE__ */ new Set();
981
1327
  const unique = [];
@@ -997,30 +1343,41 @@ var Generator = class Generator {
997
1343
  const refParameters = [];
998
1344
  for (const parameter of parameters) if (parameter.ref) {
999
1345
  const refName = Base.ref2name(parameter.ref);
1000
- refParameters.push(factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(Base.camelCase(Base.normalize(refName))), void 0, factory.createTypeReferenceNode(factory.createIdentifier(Base.upperCamelCase(Base.normalize(refName)))), void 0));
1346
+ refParameters.push(factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(Base.toIdentifier(refName)), void 0, factory.createTypeReferenceNode(factory.createIdentifier(Base.upperCamelCase(Base.normalize(refName)))), void 0));
1001
1347
  } else {
1002
1348
  const { name, schema, required } = parameter;
1003
- objectElements.push(factory.createBindingElement(void 0, void 0, factory.createIdentifier(Base.camelCase(Base.normalize(name)))));
1004
- typeObjectElements.push(factory.createPropertySignature([], factory.createIdentifier(Base.camelCase(Base.normalize(name))), required ? void 0 : factory.createToken(SyntaxKind.QuestionToken), !schema ? factory.createToken(SyntaxKind.UnknownKeyword) : Generator.toTypeNode(schema)));
1349
+ const key = Base.camelCase(Base.normalize(name));
1350
+ const id = Base.toIdentifier(name);
1351
+ objectElements.push(factory.createBindingElement(void 0, key === id ? void 0 : factory.createIdentifier(key), factory.createIdentifier(id)));
1352
+ typeObjectElements.push(factory.createPropertySignature([], factory.createIdentifier(key), required ? void 0 : factory.createToken(SyntaxKind.QuestionToken), !schema ? factory.createToken(SyntaxKind.UnknownKeyword) : Generator.toTypeNode(schema)));
1005
1353
  }
1006
1354
  if (objectElements.length > 0) return [factory.createParameterDeclaration(void 0, void 0, factory.createObjectBindingPattern(objectElements), void 0, factory.createTypeLiteralNode(typeObjectElements), void 0), ...refParameters];
1007
1355
  return refParameters;
1008
1356
  }
1357
+ /** Property keys listed in a parent schema's `required` array. */
1358
+ static requiredPropertyKeys(schema) {
1359
+ return schema && Array.isArray(schema.required) ? schema.required : [];
1360
+ }
1009
1361
  static toFormDataStatement(parameters, requestBody) {
1010
1362
  const statements = [];
1363
+ const requiredKeys = Generator.requiredPropertyKeys(requestBody);
1011
1364
  const fdDeclaration = factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier("fd"), void 0, void 0, factory.createNewExpression(factory.createIdentifier("FormData"), void 0, []))], NodeFlags.Const));
1012
1365
  statements.push(fdDeclaration);
1013
1366
  parameters.forEach((parameter) => {
1014
- statements.push(factory.createExpressionStatement(factory.createBinaryExpression(factory.createIdentifier(parameter.name), factory.createToken(SyntaxKind.AmpersandAmpersandToken), factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("fd"), factory.createIdentifier("append")), void 0, [factory.createStringLiteral(parameter.name), factory.createIdentifier(parameter.name)]))));
1367
+ const id = factory.createIdentifier(Base.toIdentifier(parameter.name));
1368
+ statements.push(factory.createExpressionStatement(factory.createBinaryExpression(id, factory.createToken(SyntaxKind.AmpersandAmpersandToken), factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("fd"), factory.createIdentifier("append")), void 0, [factory.createStringLiteral(parameter.name), id]))));
1015
1369
  });
1016
1370
  if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) Object.keys(requestBody.properties).forEach((key) => {
1017
1371
  const schemaByKey = requestBody.properties[key];
1018
- if (schemaByKey.type === "array" && Generator.isBinarySchema(schemaByKey)) statements.push(factory.createForOfStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration("file")], NodeFlags.Const), factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key)), factory.createBlock([factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("fd"), factory.createIdentifier("append")), [], [
1019
- factory.createStringLiteral(key),
1020
- factory.createIdentifier("file"),
1021
- factory.createPropertyAccessExpression(factory.createAsExpression(factory.createIdentifier("file"), factory.createTypeReferenceNode(factory.createIdentifier("File"), void 0)), factory.createIdentifier("name"))
1022
- ]))])));
1023
- else if (schemaByKey.required) statements.push(factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("fd"), factory.createIdentifier("append")), void 0, [factory.createStringLiteral(key), schemaByKey.type === "string" || Generator.isBinarySchema(schemaByKey) || schemaByKey.isRef ? factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key)) : schemaByKey.type === "array" || schemaByKey.type === "object" ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), void 0, [factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key))]) : factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key))])])));
1372
+ const accessor = factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key));
1373
+ if (schemaByKey.type === "array" && Generator.isBinarySchema(schemaByKey)) {
1374
+ const loop = factory.createForOfStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration("file")], NodeFlags.Const), accessor, factory.createBlock([factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("fd"), factory.createIdentifier("append")), [], [
1375
+ factory.createStringLiteral(key),
1376
+ factory.createIdentifier("file"),
1377
+ factory.createPropertyAccessExpression(factory.createAsExpression(factory.createIdentifier("file"), factory.createTypeReferenceNode(factory.createIdentifier("File"), void 0)), factory.createIdentifier("name"))
1378
+ ]))]));
1379
+ statements.push(requiredKeys.includes(key) ? loop : factory.createIfStatement(factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([loop], true)));
1380
+ } else if (requiredKeys.includes(key)) statements.push(factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("fd"), factory.createIdentifier("append")), void 0, [factory.createStringLiteral(key), schemaByKey.type === "string" || Generator.isBinarySchema(schemaByKey) || schemaByKey.isRef ? factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key)) : schemaByKey.type === "array" || schemaByKey.type === "object" ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), void 0, [factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key))]) : factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key))])])));
1024
1381
  else statements.push(factory.createExpressionStatement(factory.createBinaryExpression(factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key)), factory.createToken(SyntaxKind.AmpersandAmpersandToken), factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("fd"), factory.createIdentifier("append")), void 0, [factory.createStringLiteral(key), schemaByKey.type === "string" || Generator.isBinarySchema(schemaByKey) || schemaByKey.isRef ? factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key)) : schemaByKey.type === "array" || schemaByKey.type === "object" ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), void 0, [factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key))]) : factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key))])]))));
1025
1382
  });
1026
1383
  return statements;
@@ -1040,17 +1397,26 @@ var Generator = class Generator {
1040
1397
  const spDeclaration = factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier("sp"), void 0, void 0, factory.createNewExpression(factory.createIdentifier("URLSearchParams"), void 0, []))], NodeFlags.Const));
1041
1398
  statements.push(spDeclaration);
1042
1399
  const appendValue = (key, valueExpr) => factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("sp"), factory.createIdentifier("append")), void 0, [factory.createStringLiteral(key), valueExpr]));
1043
- if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) for (const key of Object.keys(requestBody.properties)) {
1044
- const fieldSchema = requestBody.properties[key];
1045
- const required = !!fieldSchema.required;
1046
- const accessor = factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key));
1047
- const append = appendValue(key, Generator.toFormDataCompatibleString(accessor, fieldSchema));
1048
- if (required) statements.push(append);
1049
- else statements.push(factory.createIfStatement(factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([append], true)));
1400
+ if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) {
1401
+ const requiredKeys = Generator.requiredPropertyKeys(requestBody);
1402
+ for (const key of Object.keys(requestBody.properties)) {
1403
+ const fieldSchema = requestBody.properties[key];
1404
+ const required = requiredKeys.includes(key);
1405
+ const accessor = factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key));
1406
+ const nonNull = factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword));
1407
+ if (fieldSchema.type === "array") {
1408
+ const item = factory.createIdentifier("item");
1409
+ const loop = factory.createForOfStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(item)], NodeFlags.Const), accessor, factory.createBlock([appendValue(key, Generator.toFormDataCompatibleString(item, fieldSchema.items))], true));
1410
+ statements.push(required ? loop : factory.createIfStatement(nonNull, factory.createBlock([loop], true)));
1411
+ continue;
1412
+ }
1413
+ const append = appendValue(key, Generator.toFormDataCompatibleString(accessor, fieldSchema));
1414
+ statements.push(required ? append : factory.createIfStatement(nonNull, factory.createBlock([append], true)));
1415
+ }
1050
1416
  }
1051
1417
  for (const parameter of parameters) {
1052
1418
  if (parameter.in === "header" || parameter.in === "cookie" || parameter.in === "path") continue;
1053
- const accessor = factory.createIdentifier(Base.camelCase(Base.normalize(parameter.name)));
1419
+ const accessor = factory.createIdentifier(Base.toIdentifier(parameter.name));
1054
1420
  statements.push(factory.createIfStatement(factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([appendValue(parameter.name, Generator.toFormDataCompatibleString(accessor))], true)));
1055
1421
  }
1056
1422
  return statements;
@@ -1064,7 +1430,7 @@ var Generator = class Generator {
1064
1430
  if (schema && (schema.type === "object" || schema.type === "array")) return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), void 0, [expr]);
1065
1431
  return factory.createCallExpression(factory.createIdentifier("String"), void 0, [expr]);
1066
1432
  }
1067
- static bodyBlock(uri, method, parameters, requestBody, response, adapter) {
1433
+ static bodyBlock(uri, method, parameters, requestBody, response, adapter, errorMode, auth, requestControl) {
1068
1434
  const shouldParseResponseToJSON = "application/json" === response?.type;
1069
1435
  const parametersShouldPutInFormData = parameters.filter((p) => p.in === "formData" || p.schema && Generator.isBinarySchema(p.schema));
1070
1436
  const parametersShouldNotPutInFormData = parameters.filter((p) => !parametersShouldPutInFormData.includes(p));
@@ -1073,10 +1439,12 @@ var Generator = class Generator {
1073
1439
  const hasBinaryInParameters = parameters.some((p) => p?.schema && Generator.isBinarySchema(p.schema));
1074
1440
  const mediaType = (requestBody?.type ?? "").toLowerCase().split(";")[0]?.trim();
1075
1441
  const requestSchemaIsBinary = requestBody?.schema && Generator.isBinarySchema(requestBody.schema);
1442
+ const multipartParts = requestBody?.schema && "properties" in requestBody.schema && requestBody.schema.properties ? Object.values(requestBody.schema.properties) : [];
1443
+ const hasOnlyTextParts = multipartParts.length > 0 && multipartParts.every((part) => Generator.isTextSchema(part));
1076
1444
  let bodyKind = "none";
1077
1445
  let bodyContentType;
1078
1446
  if (mediaType === "multipart/form-data") {
1079
- if (hasBinaryInParameters || isRequestBodyContainsBinary || parametersShouldPutInFormData.length > 0) bodyKind = "form-data";
1447
+ if (hasBinaryInParameters || isRequestBodyContainsBinary || hasOnlyTextParts || parametersShouldPutInFormData.length > 0) bodyKind = "form-data";
1080
1448
  } else if (mediaType === "application/x-www-form-urlencoded") {
1081
1449
  bodyKind = "urlencoded";
1082
1450
  bodyContentType = "application/x-www-form-urlencoded";
@@ -1095,39 +1463,164 @@ var Generator = class Generator {
1095
1463
  const preStatements = [];
1096
1464
  if (bodyKind === "form-data") preStatements.push(...Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema));
1097
1465
  else if (bodyKind === "urlencoded") preStatements.push(...Generator.toURLSearchParamsStatement(parametersShouldNotPutInFormData, requestBody?.schema));
1098
- return factory.createBlock([...preStatements, ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, bodyKind, bodyContentType, shouldParseResponseToJSON)]);
1466
+ return factory.createBlock([...preStatements, ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, bodyKind, bodyContentType, shouldParseResponseToJSON, errorMode, auth, requestControl)]);
1467
+ }
1468
+ /**
1469
+ * Resolves effective security requirements into concrete injections.
1470
+ * Requirements are OR-ed by the spec; we inject every credential the
1471
+ * caller provides, so either branch of an OR works.
1472
+ */
1473
+ static toAuthInjections(security, schemes) {
1474
+ const injections = [];
1475
+ const seen = /* @__PURE__ */ new Set();
1476
+ for (const requirement of security ?? []) for (const schemeName of Object.keys(requirement)) {
1477
+ const scheme = schemes[schemeName];
1478
+ if (!scheme) continue;
1479
+ let injection;
1480
+ if (scheme.type === "apiKey" && scheme.in && scheme.name) injection = {
1481
+ scheme: schemeName,
1482
+ location: scheme.in,
1483
+ name: scheme.name,
1484
+ kind: "raw"
1485
+ };
1486
+ else if (scheme.type === "http") injection = {
1487
+ scheme: schemeName,
1488
+ location: "header",
1489
+ name: "Authorization",
1490
+ kind: scheme.scheme === "basic" ? "basic" : "bearer"
1491
+ };
1492
+ else if (scheme.type === "basic" || scheme.type === "oauth2" || scheme.type === "openIdConnect") injection = {
1493
+ scheme: schemeName,
1494
+ location: "header",
1495
+ name: "Authorization",
1496
+ kind: scheme.type === "basic" ? "basic" : "bearer"
1497
+ };
1498
+ if (!injection) continue;
1499
+ const key = `${injection.location}:${injection.name}`;
1500
+ if (seen.has(key)) continue;
1501
+ seen.add(key);
1502
+ injections.push(injection);
1503
+ }
1504
+ return injections;
1505
+ }
1506
+ /** `{ [scheme: string]: string | { username: string; password: string } }` */
1507
+ static authOptionsTypeNode() {
1508
+ return factory.createTypeLiteralNode([factory.createIndexSignature(void 0, [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("scheme"), void 0, factory.createKeywordTypeNode(SyntaxKind.StringKeyword))], factory.createUnionTypeNode([factory.createKeywordTypeNode(SyntaxKind.StringKeyword), factory.createTypeLiteralNode([factory.createPropertySignature(void 0, factory.createIdentifier("username"), void 0, factory.createKeywordTypeNode(SyntaxKind.StringKeyword)), factory.createPropertySignature(void 0, factory.createIdentifier("password"), void 0, factory.createKeywordTypeNode(SyntaxKind.StringKeyword))])]))]);
1509
+ }
1510
+ /** `{ signal?: AbortSignal; headers?: Record<string, string>; timeout?: number }` */
1511
+ static requestOptionsTypeNode() {
1512
+ const stringType = factory.createKeywordTypeNode(SyntaxKind.StringKeyword);
1513
+ return factory.createTypeLiteralNode([
1514
+ factory.createPropertySignature(void 0, factory.createIdentifier("signal"), factory.createToken(SyntaxKind.QuestionToken), factory.createTypeReferenceNode(factory.createIdentifier("AbortSignal"))),
1515
+ factory.createPropertySignature(void 0, factory.createIdentifier("headers"), factory.createToken(SyntaxKind.QuestionToken), factory.createTypeReferenceNode(factory.createIdentifier("Record"), [stringType, stringType])),
1516
+ factory.createPropertySignature(void 0, factory.createIdentifier("timeout"), factory.createToken(SyntaxKind.QuestionToken), factory.createKeywordTypeNode(SyntaxKind.NumberKeyword))
1517
+ ]);
1099
1518
  }
1100
1519
  static schemaToStatemets(parsedDoc, adaptor, options) {
1101
1520
  const statements = [];
1102
- const { apis, schemas = {}, enums } = parsedDoc;
1521
+ const { apis, schemas = {}, enums, securitySchemes = {} } = parsedDoc;
1103
1522
  const enumNames = [];
1104
1523
  for (const enumObject of enums) {
1105
1524
  enumNames.push(Base.upperCamelCase(enumObject.name));
1106
- statements.push(factory.createEnumDeclaration([factory.createToken(SyntaxKind.ExportKeyword)], factory.createIdentifier(Base.upperCamelCase(enumObject.name)), enumObject.enum.map((member, index) => {
1107
- const key = typeof member === "string" ? member : `Value${member}`;
1525
+ const usedKeys = /* @__PURE__ */ new Set();
1526
+ const members = enumObject.enum.filter((member) => typeof member === "string" || typeof member === "number").map((member, index) => {
1527
+ let key = typeof member === "string" && !/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(member) ? member : `Value_${String(member).replace(/[^A-Za-z0-9]/g, "_")}`;
1528
+ if (usedKeys.has(key)) key = `${key}_${index}`;
1529
+ usedKeys.add(key);
1108
1530
  return factory.createEnumMember(factory.createStringLiteral(key), typeof member === "string" ? factory.createStringLiteral(member) : factory.createNumericLiteral(member));
1109
- })));
1531
+ });
1532
+ statements.push(factory.createEnumDeclaration([factory.createToken(SyntaxKind.ExportKeyword)], factory.createIdentifier(Base.upperCamelCase(enumObject.name)), members));
1110
1533
  }
1111
1534
  for (const schemaKey in schemas) if (Object.hasOwn(schemas, schemaKey) && !enumNames.includes(Base.upperCamelCase(schemaKey))) {
1112
1535
  const schema = schemas[schemaKey];
1113
1536
  statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(Base.upperCamelCase(schemaKey)), void 0, Generator.toTypeNode(schema)));
1114
1537
  }
1115
1538
  const reserveUnique = createUniqueNameResolver();
1539
+ let authTypeName;
1540
+ let requestOptionsTypeName;
1116
1541
  for (const uri in apis) {
1117
1542
  const operations = apis[uri];
1118
1543
  for (const operation of operations) {
1119
1544
  const { method, operationId, requestBody = [], responses = [], summary, deprecated, description } = operation;
1120
- let { parameters = [] } = operation;
1121
- parameters = parameters.filter((p) => p.in !== "cookie");
1545
+ const { parameters = [] } = operation;
1546
+ const authInjections = Generator.toAuthInjections(operation.security, securitySchemes);
1547
+ let authArgument;
1548
+ let authTypeReference;
1549
+ if (authInjections.length > 0) {
1550
+ const typeName = authTypeName ?? (() => {
1551
+ let candidate = "AuthOptions";
1552
+ while (Object.keys(schemas).some((key) => Base.upperCamelCase(key) === candidate) || enumNames.includes(candidate)) candidate += "2";
1553
+ return candidate;
1554
+ })();
1555
+ if (!authTypeName) {
1556
+ authTypeName = typeName;
1557
+ statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, Generator.authOptionsTypeNode()));
1558
+ }
1559
+ const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
1560
+ taken.add("req");
1561
+ let name = "auth";
1562
+ let suffix = 2;
1563
+ while (taken.has(name)) {
1564
+ name = `auth${suffix}`;
1565
+ suffix++;
1566
+ }
1567
+ authArgument = {
1568
+ name,
1569
+ injections: authInjections
1570
+ };
1571
+ authTypeReference = factory.createTypeReferenceNode(factory.createIdentifier(typeName));
1572
+ }
1573
+ const optionsTypeName = requestOptionsTypeName ?? (() => {
1574
+ let candidate = "RequestOptions";
1575
+ while (Object.keys(schemas).some((key) => Base.upperCamelCase(key) === candidate) || enumNames.includes(candidate)) candidate += "2";
1576
+ return candidate;
1577
+ })();
1578
+ if (!requestOptionsTypeName) {
1579
+ requestOptionsTypeName = optionsTypeName;
1580
+ statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(optionsTypeName), void 0, Generator.requestOptionsTypeNode()));
1581
+ }
1582
+ const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
1583
+ taken.add("req");
1584
+ if (authArgument) taken.add(authArgument.name);
1585
+ let requestControlName = "options";
1586
+ let requestControlSuffix = 2;
1587
+ while (taken.has(requestControlName)) {
1588
+ requestControlName = `options${requestControlSuffix}`;
1589
+ requestControlSuffix++;
1590
+ }
1591
+ const requestControl = { name: requestControlName };
1122
1592
  if (requestBody.length === 0) requestBody.push({ type: "application/json" });
1593
+ const { responseTypes } = operation;
1594
+ const responseCodes = Object.keys(responseTypes ?? {});
1595
+ if (responseTypes && (responseCodes.length > 1 || !/^2\d\d$/.test(responseCodes[0] ?? ""))) {
1596
+ const responsesName = reserveUnique(`${Base.pathToFnName(uri, method, operationId)}Responses`);
1597
+ statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(responsesName), void 0, Generator.toResponsesTypeNode(responseTypes)));
1598
+ }
1123
1599
  const shouldAddExtraMethodNameSuffix = requestBody.length > 1;
1124
1600
  for (const req of requestBody) {
1125
- const statement = factory.createFunctionDeclaration([factory.createModifier(SyntaxKind.ExportKeyword), factory.createModifier(SyntaxKind.AsyncKeyword)], void 0, reserveUnique(Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.mediaTypeToSuffix(req.type) : "")), void 0, [...parameters.length > 0 ? Generator.toDeclarationNodes(parameters) : [], ...req?.schema ? [Generator.toRequestBodyTypeNode(req.schema)] : []].filter(Boolean), void 0, Generator.bodyBlock(options.baseURL + uri, method, parameters, req, responses[0], adaptor));
1126
- const mergedDescription = [description, summary].filter(Boolean).join(". ");
1601
+ const statement = factory.createFunctionDeclaration([factory.createModifier(SyntaxKind.ExportKeyword), factory.createModifier(SyntaxKind.AsyncKeyword)], void 0, reserveUnique(Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.mediaTypeToSuffix(req.type) : "")), void 0, [
1602
+ ...parameters.length > 0 ? Generator.toDeclarationNodes(parameters) : [],
1603
+ ...req?.schema ? [Generator.toRequestBodyTypeNode(req.schema)] : [],
1604
+ ...authArgument && authTypeReference ? [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(authArgument.name), factory.createToken(SyntaxKind.QuestionToken), authTypeReference)] : [],
1605
+ factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(requestControl.name), factory.createToken(SyntaxKind.QuestionToken), factory.createTypeReferenceNode(factory.createIdentifier(optionsTypeName)))
1606
+ ].filter(Boolean), void 0, Generator.bodyBlock(options.baseURL + uri, method, parameters, req, responses[0], adaptor, options.errorMode, authArgument, requestControl));
1607
+ const mergedDescription = [description, summary].filter(Boolean).map((part) => part?.trim()).join(". ");
1127
1608
  Generator.addComments(statement, [
1128
1609
  mergedDescription && { comment: mergedDescription },
1129
1610
  deprecated && { tag: "deprecated" },
1130
- ...Generator.generateParamTags(parameters, req)
1611
+ ...Generator.generateParamTags(parameters, req),
1612
+ ...authArgument ? [{
1613
+ tag: "param",
1614
+ paramName: authArgument.name,
1615
+ type: "AuthOptions",
1616
+ comment: "Optional security credentials, keyed by scheme name"
1617
+ }] : [],
1618
+ {
1619
+ tag: "param",
1620
+ paramName: requestControl.name,
1621
+ type: optionsTypeName,
1622
+ comment: "Optional abort signal, extra headers and timeout"
1623
+ }
1131
1624
  ].filter(Boolean));
1132
1625
  statements.push(statement);
1133
1626
  }
@@ -1138,16 +1631,76 @@ var Generator = class Generator {
1138
1631
  static async prettier(code) {
1139
1632
  return await format(code, { parser: "typescript" });
1140
1633
  }
1634
+ /**
1635
+ * Splits generated code into `types.ts`, one file per tag, and `index.ts`.
1636
+ * Shared type declarations live in `types.ts`; tag files import them and
1637
+ * export only their functions.
1638
+ */
1639
+ static async genCodeMulti(schema, initOptions, adaptor) {
1640
+ const genOptions = {
1641
+ baseURL: initOptions.baseURL ?? "",
1642
+ errorMode: initOptions.errorMode === "throw" || initOptions.errorMode === "result" ? initOptions.errorMode : void 0
1643
+ };
1644
+ const isTypeDeclaration = (statement) => isEnumDeclaration(statement) || isTypeAliasDeclaration(statement) || isInterfaceDeclaration(statement);
1645
+ const typeStatements = Generator.schemaToStatemets(schema, adaptor, genOptions).filter(isTypeDeclaration);
1646
+ const typeNames = typeStatements.map((statement) => isEnumDeclaration(statement) || isTypeAliasDeclaration(statement) || isInterfaceDeclaration(statement) ? statement.name.text : void 0).filter((name) => Boolean(name));
1647
+ const groups = /* @__PURE__ */ new Map();
1648
+ for (const [uri, operations] of Object.entries(schema.apis)) for (const operation of operations) {
1649
+ const tag = operation.tags?.[0] ?? "default";
1650
+ const apis = groups.get(tag) ?? {};
1651
+ apis[uri] ??= [];
1652
+ apis[uri].push(operation);
1653
+ groups.set(tag, apis);
1654
+ }
1655
+ const files = {};
1656
+ const used = /* @__PURE__ */ new Set(["index", "types"]);
1657
+ files["types.ts"] = await Generator.prettier(Generator.toCode(typeStatements));
1658
+ const exportLines = ["export * from './types.js';"];
1659
+ for (const [tag, apis] of groups) {
1660
+ const tagStatements = Generator.schemaToStatemets({
1661
+ ...schema,
1662
+ apis
1663
+ }, adaptor, genOptions).filter((statement) => !isTypeDeclaration(statement));
1664
+ const nodes = [];
1665
+ if (typeNames.length > 0) nodes.push(factory.createImportDeclaration(void 0, factory.createImportClause(true, void 0, factory.createNamedImports(typeNames.map((name) => factory.createImportSpecifier(false, void 0, factory.createIdentifier(name))))), factory.createStringLiteral("./types.js")));
1666
+ nodes.push(...tagStatements);
1667
+ let code = Generator.toCode(nodes);
1668
+ if (initOptions.importClientSource) code = initOptions.importClientSource + "\n\n" + code;
1669
+ const fileName = Generator.uniqueFileName(tag, used);
1670
+ files[`${fileName}.ts`] = await Generator.prettier(code);
1671
+ exportLines.push(`export * from './${fileName}.js';`);
1672
+ }
1673
+ const index = await Generator.prettier(exportLines.join("\n"));
1674
+ files["index.ts"] = index;
1675
+ return {
1676
+ code: index,
1677
+ files
1678
+ };
1679
+ }
1680
+ /** Lower-case file stem that cannot collide with reserved or earlier names. */
1681
+ static uniqueFileName(tag, used) {
1682
+ const base = tag.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "default";
1683
+ let name = base;
1684
+ let suffix = 2;
1685
+ while (used.has(name)) {
1686
+ name = `${base}-${suffix}`;
1687
+ suffix++;
1688
+ }
1689
+ used.add(name);
1690
+ return name;
1691
+ }
1141
1692
  static async genCode(schema, initOptions, adaptor) {
1142
- const { importClientSource } = initOptions;
1143
- const statements = Generator.schemaToStatemets(schema, adaptor, { baseURL: initOptions.baseURL ?? "" });
1693
+ const { importClientSource, errorMode } = initOptions;
1694
+ const statements = Generator.schemaToStatemets(schema, adaptor, {
1695
+ baseURL: initOptions.baseURL ?? "",
1696
+ errorMode: errorMode === "throw" || errorMode === "result" ? errorMode : void 0
1697
+ });
1144
1698
  let code = Generator.toCode(statements);
1145
1699
  if (importClientSource) code = importClientSource + "\n\n" + code;
1146
1700
  return await Generator.prettier(code);
1147
1701
  }
1148
1702
  };
1149
- //#endregion
1150
- //#region src/core/client/axios.ts
1703
+ // src/core/client/axios.ts
1151
1704
  /**
1152
1705
  * Adapter class implementing support for generating code that makes use of the Axios HTTP client library.
1153
1706
  * This adapter defines custom behavior and field mappings specific to the Axios client.
@@ -1178,16 +1731,19 @@ var AxiosAdapter = class extends Adapter {
1178
1731
  *
1179
1732
  * @returns {Statement[]} An array of TypeScript statements that define the client configuration.
1180
1733
  */
1181
- client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, _shouldUseJSONResponse) {
1734
+ client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, _shouldUseJSONResponse, errorMode, auth, requestControl) {
1182
1735
  const statements = [];
1183
1736
  parameters.filter((p) => !p.in || p.in === "body");
1184
1737
  const inHeader = parameters.filter((p) => p.in === "header");
1185
1738
  const toLiterlExpression = () => {
1186
1739
  const headerEntries = [];
1187
- for (const p of inHeader) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.camelCase(Base.normalize(p.name)))])])));
1740
+ for (const p of inHeader) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.toIdentifier(p.name))])])));
1188
1741
  if (bodyContentType !== void 0) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Content-Type"), factory.createStringLiteral(bodyContentType)));
1742
+ if (parameters.some((p) => p.in === "cookie") || auth?.injections.some((injection) => injection.location === "cookie")) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Cookie"), cookieHeaderExpression(parameters, auth)));
1743
+ if (auth) headerEntries.push(...authHeaderEntries(auth));
1189
1744
  const properties = [factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))];
1190
- if (headerEntries.length > 0) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(headerEntries)));
1745
+ if (headerEntries.length > 0 || requestControl) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(withRequestHeaders(headerEntries, requestControl))));
1746
+ if (requestControl) properties.push(factory.createPropertyAssignment(factory.createIdentifier("signal"), optionalAccess(requestControl, "signal")), factory.createPropertyAssignment(factory.createIdentifier("timeout"), optionalAccess(requestControl, "timeout")));
1191
1747
  let bodyExpr;
1192
1748
  switch (bodyKind) {
1193
1749
  case "form-data":
@@ -1197,20 +1753,33 @@ var AxiosAdapter = class extends Adapter {
1197
1753
  bodyExpr = factory.createIdentifier("sp");
1198
1754
  break;
1199
1755
  case "json":
1200
- case "binary":
1201
- bodyExpr = factory.createIdentifier("req");
1202
- break;
1203
- case "none": break;
1756
+ case "binary": bodyExpr = factory.createIdentifier("req");
1204
1757
  }
1205
1758
  if (bodyExpr) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
1206
1759
  return factory.createObjectLiteralExpression(properties, true);
1207
1760
  };
1208
- statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createIdentifier(adapter.name), response?.schema ? [Generator.toTypeNode(response.schema)] : [factory.createTypeReferenceNode(factory.createIdentifier("unknown"))], [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1761
+ const axiosCall = factory.createCallExpression(factory.createIdentifier(adapter.name), response?.schema ? [Generator.toTypeNode(response.schema)] : [factory.createTypeReferenceNode(factory.createIdentifier("unknown"))], [Generator.toUrlTemplate(uri, parameters, "", auth), toLiterlExpression()]);
1762
+ if (errorMode !== "result") {
1763
+ statements.push(factory.createReturnStatement(axiosCall));
1764
+ return statements;
1765
+ }
1766
+ const prop = (name, value) => factory.createPropertyAssignment(factory.createIdentifier(name), value);
1767
+ const resProp = (name) => factory.createPropertyAccessExpression(factory.createIdentifier("res"), factory.createIdentifier(name));
1768
+ const errorProp = (name) => factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(factory.createIdentifier("failure"), factory.createIdentifier("response")), factory.createIdentifier(name));
1769
+ const result = (ok, key, value) => factory.createObjectLiteralExpression([
1770
+ prop("ok", factory.createAsExpression(ok ? factory.createTrue() : factory.createFalse(), factory.createTypeReferenceNode(factory.createIdentifier("const")))),
1771
+ prop("status", ok ? resProp("status") : errorProp("status")),
1772
+ prop(key, value)
1773
+ ], true);
1774
+ statements.push(factory.createTryStatement(factory.createBlock([factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier("res"), void 0, void 0, factory.createAwaitExpression(axiosCall))], NodeFlags.Const)), factory.createReturnStatement(result(true, "data", resProp("data")))], true), factory.createCatchClause(factory.createVariableDeclaration(factory.createIdentifier("err")), factory.createBlock([
1775
+ factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier("failure"), void 0, void 0, factory.createAsExpression(factory.createIdentifier("err"), factory.createTypeLiteralNode([factory.createPropertySignature(void 0, factory.createIdentifier("response"), factory.createToken(SyntaxKind.QuestionToken), factory.createTypeLiteralNode([factory.createPropertySignature(void 0, factory.createIdentifier("status"), void 0, factory.createKeywordTypeNode(SyntaxKind.NumberKeyword)), factory.createPropertySignature(void 0, factory.createIdentifier("data"), void 0, factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword))]))])))], NodeFlags.Const)),
1776
+ factory.createIfStatement(factory.createPropertyAccessExpression(factory.createIdentifier("failure"), factory.createIdentifier("response")), factory.createBlock([factory.createReturnStatement(result(false, "error", errorProp("data")))], true)),
1777
+ factory.createThrowStatement(factory.createIdentifier("err"))
1778
+ ], true)), void 0));
1209
1779
  return statements;
1210
1780
  }
1211
1781
  };
1212
- //#endregion
1213
- //#region src/core/client/fetch.ts
1782
+ // src/core/client/fetch.ts
1214
1783
  /**
1215
1784
  * FetchAdapter is an adapter class that generates client-side fetch requests.
1216
1785
  * It handles parameters, headers, and request bodies to construct proper fetch calls.
@@ -1234,7 +1803,7 @@ var FetchAdapter = class extends Adapter {
1234
1803
  * @param shouldUseJSONResponse - Flag to use JSON parsing for the response
1235
1804
  * @return - An array of generated TypeScript statements
1236
1805
  */
1237
- client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, shouldUseJSONResponse) {
1806
+ client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, shouldUseJSONResponse, errorMode, auth, requestControl) {
1238
1807
  const statements = [];
1239
1808
  const inBody = parameters.filter((p) => !p.in || p.in === "body");
1240
1809
  const inHeader = parameters.filter((p) => p.in === "header");
@@ -1245,10 +1814,13 @@ var FetchAdapter = class extends Adapter {
1245
1814
  */
1246
1815
  const toLiterlExpression = () => {
1247
1816
  const headerEntries = [];
1248
- for (const p of inHeader) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.camelCase(Base.normalize(p.name)))])])));
1817
+ for (const p of inHeader) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.toIdentifier(p.name))])])));
1249
1818
  if (bodyContentType !== void 0) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Content-Type"), factory.createStringLiteral(bodyContentType)));
1819
+ if (parameters.some((p) => p.in === "cookie") || auth?.injections.some((injection) => injection.location === "cookie")) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Cookie"), cookieHeaderExpression(parameters, auth)));
1820
+ if (auth) headerEntries.push(...authHeaderEntries(auth));
1250
1821
  const properties = [factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))];
1251
- if (headerEntries.length > 0) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(headerEntries)));
1822
+ if (headerEntries.length > 0 || requestControl) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(withRequestHeaders(headerEntries, requestControl))));
1823
+ if (requestControl) properties.push(factory.createPropertyAssignment(factory.createIdentifier("signal"), fetchSignalExpression(requestControl)));
1252
1824
  let bodyExpr;
1253
1825
  switch (bodyKind) {
1254
1826
  case "form-data":
@@ -1262,24 +1834,40 @@ var FetchAdapter = class extends Adapter {
1262
1834
  bodyExpr = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), [], [arg]);
1263
1835
  break;
1264
1836
  }
1265
- case "binary":
1266
- bodyExpr = factory.createIdentifier("req");
1267
- break;
1268
- case "none": break;
1837
+ case "binary": bodyExpr = factory.createIdentifier("req");
1269
1838
  }
1270
1839
  if (bodyExpr) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
1271
1840
  return factory.createObjectLiteralExpression(properties, true);
1272
1841
  };
1273
- statements.push(factory.createReturnStatement(shouldUseJSONResponse ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()]), factory.createIdentifier("then")), void 0, [factory.createArrowFunction([factory.createModifier(SyntaxKind.AsyncKeyword)], [], [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("response"))], void 0, factory.createToken(SyntaxKind.EqualsGreaterThanToken), response?.schema ? factory.createAsExpression(factory.createParenthesizedExpression(factory.createAwaitExpression(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("response"), factory.createIdentifier("json")), void 0, []))), Generator.toTypeNode(response.schema)) : factory.createAsExpression(factory.createParenthesizedExpression(factory.createAwaitExpression(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("response"), factory.createIdentifier("json")), void 0, []))), factory.createToken(SyntaxKind.UnknownKeyword)))]) : factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1842
+ const fetchCall = factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters, "", auth), toLiterlExpression()]);
1843
+ const responseProp = (name) => factory.createPropertyAccessExpression(factory.createIdentifier("response"), factory.createIdentifier(name));
1844
+ const jsonExpression = factory.createAsExpression(factory.createParenthesizedExpression(factory.createAwaitExpression(factory.createCallExpression(responseProp("json"), void 0, []))), response?.schema ? Generator.toTypeNode(response.schema) : factory.createToken(SyntaxKind.UnknownKeyword));
1845
+ const successExpression = shouldUseJSONResponse ? jsonExpression : factory.createIdentifier("response");
1846
+ if (!errorMode) {
1847
+ statements.push(factory.createReturnStatement(shouldUseJSONResponse ? factory.createCallExpression(factory.createPropertyAccessExpression(fetchCall, factory.createIdentifier("then")), void 0, [factory.createArrowFunction([factory.createModifier(SyntaxKind.AsyncKeyword)], [], [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("response"))], void 0, factory.createToken(SyntaxKind.EqualsGreaterThanToken), jsonExpression)]) : fetchCall));
1848
+ return statements;
1849
+ }
1850
+ const notOk = factory.createPrefixUnaryExpression(SyntaxKind.ExclamationToken, responseProp("ok"));
1851
+ const responseText = factory.createAwaitExpression(factory.createCallExpression(responseProp("text"), void 0, []));
1852
+ const thenStatements = [];
1853
+ if (errorMode === "throw") thenStatements.push(factory.createIfStatement(notOk, factory.createBlock([factory.createThrowStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), factory.createIdentifier("assign")), void 0, [factory.createNewExpression(factory.createIdentifier("Error"), void 0, [factory.createTemplateExpression(factory.createTemplateHead("HTTP "), [factory.createTemplateSpan(responseProp("status"), factory.createTemplateTail(""))])]), factory.createObjectLiteralExpression([factory.createPropertyAssignment(factory.createIdentifier("status"), responseProp("status")), factory.createPropertyAssignment(factory.createIdentifier("body"), responseText)], true)]))], true)), factory.createReturnStatement(successExpression));
1854
+ else {
1855
+ const result = (ok, key, value) => factory.createObjectLiteralExpression([
1856
+ factory.createPropertyAssignment(factory.createIdentifier("ok"), factory.createAsExpression(ok ? factory.createTrue() : factory.createFalse(), factory.createTypeReferenceNode(factory.createIdentifier("const")))),
1857
+ factory.createPropertyAssignment(factory.createIdentifier("status"), responseProp("status")),
1858
+ factory.createPropertyAssignment(factory.createIdentifier(key), value)
1859
+ ], true);
1860
+ thenStatements.push(factory.createIfStatement(notOk, factory.createBlock([factory.createReturnStatement(result(false, "error", responseText))], true)), factory.createReturnStatement(result(true, "data", successExpression)));
1861
+ }
1862
+ statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createPropertyAccessExpression(fetchCall, factory.createIdentifier("then")), void 0, [factory.createArrowFunction([factory.createModifier(SyntaxKind.AsyncKeyword)], [], [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("response"))], void 0, factory.createToken(SyntaxKind.EqualsGreaterThanToken), factory.createBlock(thenStatements, true))])));
1274
1863
  return statements;
1275
1864
  }
1276
1865
  };
1277
- //#endregion
1278
- //#region src/core/config.ts
1866
+ // src/core/config.ts
1279
1867
  /**
1280
1868
  * Strings considered truthy for boolean env vars (verbose/watch/typeCheck).
1281
1869
  */
1282
- const TRUTHY_STRINGS = new Set([
1870
+ const TRUTHY_STRINGS = /* @__PURE__ */ new Set([
1283
1871
  "true",
1284
1872
  "1",
1285
1873
  "yes",
@@ -1296,7 +1884,10 @@ const ENV_MAPPINGS = {
1296
1884
  APICODEGEN_ADAPTOR: "adaptor",
1297
1885
  APICODEGEN_VERBOSE: "verbose",
1298
1886
  APICODEGEN_WATCH: "watch",
1299
- APICODEGEN_TYPE_CHECK: "typeCheck"
1887
+ APICODEGEN_TYPE_CHECK: "typeCheck",
1888
+ APICODEGEN_CHECK: "check",
1889
+ APICODEGEN_ERROR_MODE: "errorMode",
1890
+ APICODEGEN_SPLIT_BY: "splitBy"
1300
1891
  };
1301
1892
  /**
1302
1893
  * Load config from environment variables
@@ -1309,19 +1900,23 @@ function loadFromEnv() {
1309
1900
  case "verbose":
1310
1901
  case "watch":
1311
1902
  case "typeCheck":
1903
+ case "check":
1312
1904
  config[configKey] = TRUTHY_STRINGS.has(value.toLowerCase());
1313
1905
  break;
1314
1906
  case "adaptor":
1315
1907
  if (Object.values(Adaptors).includes(value)) config[configKey] = value;
1316
1908
  break;
1909
+ case "errorMode":
1910
+ if (value === "throw" || value === "result") config.errorMode = value;
1911
+ break;
1912
+ case "splitBy":
1913
+ if (value === "tag") config.splitBy = value;
1914
+ break;
1317
1915
  default: config[configKey] = value;
1318
1916
  }
1319
1917
  }
1320
1918
  return config;
1321
1919
  }
1322
- /**
1323
- * Load config from a file
1324
- */
1325
1920
  async function loadFromFile(filePath) {
1326
1921
  const ext = path.extname(filePath).toLowerCase();
1327
1922
  try {
@@ -1330,17 +1925,16 @@ async function loadFromFile(filePath) {
1330
1925
  return JSON.parse(content);
1331
1926
  }
1332
1927
  if (ext === ".js" || ext === ".cjs" || ext === ".mjs") {
1333
- const mod = await import(filePath);
1928
+ const mod = await import(pathToFileURL(filePath).href);
1334
1929
  return mod.default || mod;
1335
1930
  }
1336
- if (ext === ".ts") {
1931
+ if (ext === ".ts" || ext === ".mts" || ext === ".cts") {
1337
1932
  const content = await fs.readFile(filePath, "utf-8");
1338
1933
  try {
1339
1934
  return JSON.parse(content);
1340
- } catch {
1341
- const jsonMatch = content.match(/export\s+default\s+(\{.+\})/s);
1342
- if (jsonMatch) return JSON.parse(jsonMatch[1]);
1343
- }
1935
+ } catch {}
1936
+ const mod = await import(pathToFileURL(filePath).href);
1937
+ return mod.default || mod;
1344
1938
  }
1345
1939
  const content = await fs.readFile(filePath, "utf-8");
1346
1940
  return JSON.parse(content);
@@ -1356,10 +1950,13 @@ async function findConfigFile(cwd) {
1356
1950
  "apicodegen.config.json",
1357
1951
  "apicodegen.config.js",
1358
1952
  "apicodegen.config.mjs",
1953
+ "apicodegen.config.ts",
1954
+ "apicodegen.config.mts",
1359
1955
  ".apicodegenrc",
1360
1956
  ".apicodegenrc.json",
1361
1957
  ".apicodegenrc.js",
1362
- ".apicodegenrc.mjs"
1958
+ ".apicodegenrc.mjs",
1959
+ ".apicodegenrc.ts"
1363
1960
  ]) {
1364
1961
  const filePath = path.join(cwd, fileName);
1365
1962
  if (await fs.pathExists(filePath)) return filePath;
@@ -1384,6 +1981,35 @@ function mergeConfigs(base, ...sources) {
1384
1981
  return result;
1385
1982
  }
1386
1983
  /**
1984
+ * Validate field types before the values reach the generator.
1985
+ */
1986
+ function validateConfigShape(config) {
1987
+ const fail = (key, expected) => {
1988
+ throw new Error(`Invalid config field "${key}": expected ${expected}`);
1989
+ };
1990
+ if (config.spec !== void 0 && typeof config.spec !== "string") fail("spec", "a string");
1991
+ if (config.output !== void 0 && typeof config.output !== "string") fail("output", "a string");
1992
+ for (const key of [
1993
+ "verbose",
1994
+ "watch",
1995
+ "typeCheck",
1996
+ "check"
1997
+ ]) if (config[key] !== void 0 && typeof config[key] !== "boolean") fail(key, "a boolean");
1998
+ if (config.adaptor !== void 0 && !Object.values(Adaptors).includes(config.adaptor)) fail("adaptor", Object.values(Adaptors).join(" or "));
1999
+ if (config.errorMode !== void 0 && config.errorMode !== "throw" && config.errorMode !== "result") fail("errorMode", "throw or result");
2000
+ if (config.splitBy !== void 0 && config.splitBy !== "tag") fail("splitBy", "tag");
2001
+ for (const key of [
2002
+ "includeTags",
2003
+ "excludeTags",
2004
+ "includePaths",
2005
+ "excludePaths"
2006
+ ]) {
2007
+ const value = config[key];
2008
+ if (value !== void 0 && (!Array.isArray(value) || value.some((item) => typeof item !== "string"))) fail(key, "an array of strings");
2009
+ }
2010
+ if (config.requestOptions !== void 0 && (typeof config.requestOptions !== "object" || config.requestOptions === null || Array.isArray(config.requestOptions))) fail("requestOptions", "an object");
2011
+ }
2012
+ /**
1387
2013
  * Validate config has required fields
1388
2014
  */
1389
2015
  function validateConfig(config) {
@@ -1391,9 +2017,10 @@ function validateConfig(config) {
1391
2017
  return true;
1392
2018
  }
1393
2019
  /**
1394
- * Load and resolve config from multiple sources
2020
+ * Load and resolve every config entry. A config file may define a single
2021
+ * object or a `specs` array for multi-spec projects.
1395
2022
  */
1396
- async function loadConfig(options = {}) {
2023
+ async function loadConfigs(options = {}) {
1397
2024
  const cwd = options.cwd || process.cwd();
1398
2025
  const cliOptions = options.cliOptions || {};
1399
2026
  const envConfig = loadFromEnv();
@@ -1415,17 +2042,34 @@ async function loadConfig(options = {}) {
1415
2042
  const pkg = JSON.parse(await fs.readFile(packageJsonPath, "utf-8"));
1416
2043
  if (pkg.apicodegen && typeof pkg.apicodegen === "object") inlineConfig = pkg.apicodegen;
1417
2044
  } catch {}
1418
- const merged = mergeConfigs({
2045
+ const { specs, ...fileOptions } = fileConfig;
2046
+ const entries = Array.isArray(specs) && specs.length > 0 ? specs.map((entry) => mergeConfigs({
1419
2047
  spec: "",
1420
2048
  output: "./output.ts"
1421
- }, envConfig, inlineConfig, fileConfig, cliOptions);
1422
- validateConfig(merged);
1423
- const name = options.name || merged.baseURL || merged.spec;
1424
- return {
1425
- ...merged,
1426
- configFilePath,
1427
- name
1428
- };
2049
+ }, fileOptions, entry)) : [fileOptions];
2050
+ const sharedCliOptions = entries.length === 1 ? cliOptions : Object.fromEntries(Object.entries(cliOptions).filter(([key]) => key !== "spec" && key !== "output"));
2051
+ return entries.map((entry, index) => {
2052
+ const merged = mergeConfigs({
2053
+ spec: "",
2054
+ output: "./output.ts"
2055
+ }, envConfig, inlineConfig, entry, sharedCliOptions);
2056
+ validateConfigShape(merged);
2057
+ validateConfig(merged);
2058
+ const name = options.name || merged.name || merged.baseURL || merged.spec || `api-${index + 1}`;
2059
+ return {
2060
+ ...merged,
2061
+ configFilePath,
2062
+ name
2063
+ };
2064
+ });
2065
+ }
2066
+ /**
2067
+ * Load a single config. Throws when the file defines no entries.
2068
+ */
2069
+ async function loadConfig(options = {}) {
2070
+ const config = (await loadConfigs(options))[0];
2071
+ if (!config) throw new Error("No API configs found");
2072
+ return config;
1429
2073
  }
1430
2074
  /**
1431
2075
  * Create CLI options from config for commander
@@ -1435,9 +2079,17 @@ function configToCLIOptions(config) {
1435
2079
  if (config.spec) options.spec = config.spec;
1436
2080
  if (config.output) options.output = config.output;
1437
2081
  if (config.adaptor) options.adaptor = config.adaptor;
1438
- if (config.baseURL) options.baseURL = config.baseURL;
2082
+ if (config.errorMode) options.errorMode = config.errorMode;
2083
+ if (config.splitBy) options.splitBy = config.splitBy;
2084
+ if (config.includeTags) options.includeTags = config.includeTags;
2085
+ if (config.excludeTags) options.excludeTags = config.excludeTags;
2086
+ if (config.includePaths) options.includePaths = config.includePaths;
2087
+ if (config.excludePaths) options.excludePaths = config.excludePaths;
2088
+ if (config.baseURL !== void 0) options.baseURL = config.baseURL;
1439
2089
  if (config.verbose) options.verbose = config.verbose;
2090
+ if (config.typeCheck) options.typeCheck = config.typeCheck;
1440
2091
  if (config.watch) options.watch = config.watch;
2092
+ if (config.check) options.check = config.check;
1441
2093
  if (config.importClientSource) options.importClientSource = config.importClientSource;
1442
2094
  return options;
1443
2095
  }
@@ -1452,11 +2104,203 @@ function toProviderOptions(config) {
1452
2104
  baseURL: config.baseURL,
1453
2105
  importClientSource: config.importClientSource,
1454
2106
  verbose: config.verbose,
1455
- requestOptions: config.requestOptions
2107
+ requestOptions: config.requestOptions,
2108
+ errorMode: config.errorMode,
2109
+ splitBy: config.splitBy,
2110
+ includeTags: config.includeTags,
2111
+ excludeTags: config.excludeTags,
2112
+ includePaths: config.includePaths,
2113
+ excludePaths: config.excludePaths
2114
+ };
2115
+ }
2116
+ // src/openapi/filter.ts
2117
+ function matchesPrefix(path, prefixes) {
2118
+ return !!prefixes?.length && prefixes.some((prefix) => path.startsWith(prefix));
2119
+ }
2120
+ /**
2121
+ * Keep only the operations selected by tag and path filters.
2122
+ *
2123
+ * Paths use prefix matching (`/admin` covers `/admin/users`). Operations with
2124
+ * no tags are kept only when no `includeTags` filter is active.
2125
+ */
2126
+ function filterApis(apis, filters) {
2127
+ const keepTag = (op) => {
2128
+ const tags = op.tags ?? [];
2129
+ if (filters.includeTags?.length && !tags.some((tag) => filters.includeTags?.includes(tag))) return false;
2130
+ if (filters.excludeTags?.length && tags.some((tag) => filters.excludeTags?.includes(tag))) return false;
2131
+ return true;
2132
+ };
2133
+ const filtered = {};
2134
+ for (const [path, operations] of Object.entries(apis)) {
2135
+ if (filters.includePaths?.length && !matchesPrefix(path, filters.includePaths)) continue;
2136
+ if (matchesPrefix(path, filters.excludePaths)) continue;
2137
+ const kept = operations.filter(keepTag);
2138
+ if (kept.length > 0) filtered[path] = kept;
2139
+ }
2140
+ return filtered;
2141
+ }
2142
+ // src/openapi/read-write.ts
2143
+ function single(schema) {
2144
+ return schema;
2145
+ }
2146
+ /** True when a schema carries the flag anywhere except through a `$ref`. */
2147
+ function containsFlag(schema, flag) {
2148
+ if (!schema) return false;
2149
+ const value = single(schema);
2150
+ if (value[flag]) return true;
2151
+ if (value.properties) {
2152
+ for (const prop of Object.values(value.properties)) if (containsFlag(prop, flag)) return true;
2153
+ }
2154
+ if (schema.type === "array") return containsFlag(schema.items, flag);
2155
+ for (const key of [
2156
+ "allOf",
2157
+ "anyOf",
2158
+ "oneOf"
2159
+ ]) if (value[key]?.some((member) => containsFlag(member, flag))) return true;
2160
+ const additional = value.additionalProperties;
2161
+ return !!additional && typeof additional === "object" && containsFlag(additional, flag);
2162
+ }
2163
+ /** The referenced emitted type name, when a schema is only a reference. */
2164
+ function refType(schema) {
2165
+ const value = single(schema);
2166
+ if (value.ref) return Base.upperCamelCase(Base.ref2name(value.ref));
2167
+ if (value.properties || value.oneOf || value.anyOf || value.allOf) return;
2168
+ if (schema.type === "array") return void 0;
2169
+ return typeof value.type === "string" ? Base.upperCamelCase(value.type) : void 0;
2170
+ }
2171
+ function dependsOn(schema, names) {
2172
+ const ref = refType(schema);
2173
+ if (ref && names.has(ref)) return true;
2174
+ const value = single(schema);
2175
+ if (value.properties) {
2176
+ for (const prop of Object.values(value.properties)) if (dependsOn(prop, names)) return true;
2177
+ }
2178
+ if (schema.type === "array") {
2179
+ const items = schema.items;
2180
+ return !!items && dependsOn(items, names);
2181
+ }
2182
+ for (const key of [
2183
+ "allOf",
2184
+ "anyOf",
2185
+ "oneOf"
2186
+ ]) if (value[key]?.some((member) => dependsOn(member, names))) return true;
2187
+ const additional = value.additionalProperties;
2188
+ return !!additional && typeof additional === "object" && dependsOn(additional, names);
2189
+ }
2190
+ /**
2191
+ * Pick the schemas that need an Input/Output variant.
2192
+ *
2193
+ * A schema qualifies when it contains the flag directly, or references a
2194
+ * schema that does. The fixed point makes nested references follow.
2195
+ */
2196
+ function buildVariant(schemas, flag, suffix) {
2197
+ const seeded = /* @__PURE__ */ new Set();
2198
+ const emitted = /* @__PURE__ */ new Map();
2199
+ for (const key of Object.keys(schemas)) {
2200
+ emitted.set(Base.upperCamelCase(key), key);
2201
+ if (containsFlag(schemas[key], flag)) seeded.add(key);
2202
+ }
2203
+ let changed = true;
2204
+ while (changed) {
2205
+ changed = false;
2206
+ const seededNames = new Set([...seeded].map((key) => Base.upperCamelCase(key)));
2207
+ for (const key of Object.keys(schemas)) if (!seeded.has(key) && dependsOn(schemas[key], seededNames)) {
2208
+ seeded.add(key);
2209
+ changed = true;
2210
+ }
2211
+ }
2212
+ const names = /* @__PURE__ */ new Map();
2213
+ const keys = /* @__PURE__ */ new Map();
2214
+ const taken = new Set(emitted.keys());
2215
+ for (const key of seeded) {
2216
+ const variantKey = key + suffix;
2217
+ const variantName = Base.upperCamelCase(variantKey);
2218
+ if (taken.has(variantName)) continue;
2219
+ taken.add(variantName);
2220
+ names.set(Base.upperCamelCase(key), variantName);
2221
+ keys.set(key, variantKey);
2222
+ }
2223
+ return {
2224
+ names,
2225
+ keys
2226
+ };
2227
+ }
2228
+ /** Clone a schema with flagged properties removed and variant refs remapped. */
2229
+ function transform(schema, flag, names) {
2230
+ const ref = refType(schema);
2231
+ if (ref && names.has(ref)) {
2232
+ const { ref: _ref, ...rest } = single(schema);
2233
+ return {
2234
+ ...rest,
2235
+ type: names.get(ref)
2236
+ };
2237
+ }
2238
+ if (schema.type === "array") {
2239
+ const array = schema;
2240
+ return {
2241
+ ...array,
2242
+ items: array.items ? transform(array.items, flag, names) : void 0
2243
+ };
2244
+ }
2245
+ const value = single(schema);
2246
+ const next = { ...value };
2247
+ if (value.properties) {
2248
+ const properties = {};
2249
+ for (const [key, prop] of Object.entries(value.properties)) {
2250
+ if (single(prop)[flag]) continue;
2251
+ properties[key] = transform(prop, flag, names);
2252
+ }
2253
+ next.properties = properties;
2254
+ if (Array.isArray(value.required)) next.required = value.required.filter((key) => key in properties);
2255
+ }
2256
+ for (const key of [
2257
+ "allOf",
2258
+ "anyOf",
2259
+ "oneOf"
2260
+ ]) {
2261
+ const members = value[key];
2262
+ if (members) next[key] = members.map((m) => transform(m, flag, names));
2263
+ }
2264
+ const additional = value.additionalProperties;
2265
+ if (additional && typeof additional === "object") next.additionalProperties = transform(additional, flag, names);
2266
+ return next;
2267
+ }
2268
+ function transformMedia(media, flag, names) {
2269
+ return media.map((entry) => entry.schema ? {
2270
+ ...entry,
2271
+ schema: transform(entry.schema, flag, names)
2272
+ } : entry);
2273
+ }
2274
+ function transformOperation(operation, input, output) {
2275
+ return {
2276
+ ...operation,
2277
+ ...operation.requestBody ? { requestBody: transformMedia(operation.requestBody, "readOnly", input) } : {},
2278
+ ...operation.responses ? { responses: transformMedia(operation.responses, "writeOnly", output) } : {},
2279
+ ...operation.responseTypes ? { responseTypes: Object.fromEntries(Object.entries(operation.responseTypes).map(([code, media]) => [code, transformMedia(media, "writeOnly", output)])) } : {}
2280
+ };
2281
+ }
2282
+ /**
2283
+ * Add `XxxInput` / `XxxOutput` schema aliases and point operations at them:
2284
+ * requests drop `readOnly` properties, responses drop `writeOnly` ones.
2285
+ *
2286
+ * Existing type names are untouched; variants are only created when the name
2287
+ * is free. With no `readOnly` / `writeOnly` in the document this is a no-op.
2288
+ */
2289
+ function splitReadWrite(parsed) {
2290
+ const input = buildVariant(parsed.schemas, "readOnly", "Input");
2291
+ const output = buildVariant(parsed.schemas, "writeOnly", "Output");
2292
+ if (input.keys.size === 0 && output.keys.size === 0) return parsed;
2293
+ const schemas = { ...parsed.schemas };
2294
+ for (const [key, variantKey] of input.keys) schemas[variantKey] = transform(parsed.schemas[key], "readOnly", input.names);
2295
+ for (const [key, variantKey] of output.keys) schemas[variantKey] = transform(parsed.schemas[key], "writeOnly", output.names);
2296
+ const apis = Object.fromEntries(Object.entries(parsed.apis).map(([path, operations]) => [path, operations.map((operation) => transformOperation(operation, input.names, output.names))]));
2297
+ return {
2298
+ ...parsed,
2299
+ schemas,
2300
+ apis
1456
2301
  };
1457
2302
  }
1458
- //#endregion
1459
- //#region src/openapi/V2.ts
2303
+ // src/openapi/V2.ts
1460
2304
  var V2 = class {
1461
2305
  doc;
1462
2306
  constructor(doc) {
@@ -1503,11 +2347,11 @@ var V2 = class {
1503
2347
  items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
1504
2348
  };
1505
2349
  } else {
1506
- const { required = [], allOf, anyOf, description, enum: enum_, format, oneOf, properties = {} } = schema;
2350
+ const { required = [], allOf, anyOf, description, discriminator, enum: enum_, format, oneOf, properties = {} } = schema;
1507
2351
  let { type } = schema;
1508
2352
  if (enum_ && type !== "boolean") {
1509
2353
  const enumObject = {
1510
- name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
2354
+ name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
1511
2355
  enum: [...new Set(enum_)]
1512
2356
  };
1513
2357
  const sameObject = Base.findSameSchema(enumObject, enums);
@@ -1523,8 +2367,11 @@ var V2 = class {
1523
2367
  type,
1524
2368
  required,
1525
2369
  description,
2370
+ discriminator: discriminator ? { propertyName: discriminator } : void 0,
1526
2371
  enum: enum_,
1527
2372
  format,
2373
+ readOnly: schema.readOnly,
2374
+ writeOnly: schema.writeOnly,
1528
2375
  allOf: allOf?.map((s) => Base.isRef(s) ? {
1529
2376
  ...s,
1530
2377
  ref: s.$ref,
@@ -1561,6 +2408,9 @@ var V2 = class {
1561
2408
  parameter = resolved;
1562
2409
  }
1563
2410
  const p = parameter;
2411
+ const collectionFormat = p.collectionFormat;
2412
+ const style = collectionFormat === "ssv" ? "spaceDelimited" : collectionFormat === "pipes" ? "pipeDelimited" : "form";
2413
+ const explode = collectionFormat === "multi";
1564
2414
  const { name, required, description, type, items, enum: enum_, properties, schema } = p;
1565
2415
  if (enum_) {
1566
2416
  const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
@@ -1578,6 +2428,8 @@ var V2 = class {
1578
2428
  required,
1579
2429
  description,
1580
2430
  in: p.in,
2431
+ style,
2432
+ explode,
1581
2433
  schema: { type: sameEnum?.name ?? type }
1582
2434
  };
1583
2435
  }
@@ -1586,6 +2438,8 @@ var V2 = class {
1586
2438
  required,
1587
2439
  description,
1588
2440
  in: p.in,
2441
+ style,
2442
+ explode,
1589
2443
  schema: {
1590
2444
  type,
1591
2445
  items
@@ -1596,6 +2450,8 @@ var V2 = class {
1596
2450
  required,
1597
2451
  description,
1598
2452
  in: p.in,
2453
+ style,
2454
+ explode,
1599
2455
  schema: { type: Base.capitalize(Base.ref2name(schema.$ref)) }
1600
2456
  };
1601
2457
  return {
@@ -1603,6 +2459,8 @@ var V2 = class {
1603
2459
  required,
1604
2460
  description,
1605
2461
  in: p.in,
2462
+ style,
2463
+ explode,
1606
2464
  schema: {
1607
2465
  type,
1608
2466
  properties
@@ -1612,16 +2470,16 @@ var V2 = class {
1612
2470
  /**
1613
2471
  * OpenAPI schema to base response
1614
2472
  */
1615
- getResponseByRef(schema) {
2473
+ getResponseByRef(schema, enums = []) {
1616
2474
  if (Base.isRef(schema)) schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
1617
2475
  const { schema: responseSchema } = schema;
1618
2476
  return [{
1619
2477
  type: "application/json",
1620
- schema: responseSchema && this.getSchemaByRef(responseSchema, true)
2478
+ schema: responseSchema && this.getSchemaByRef(responseSchema, true, enums)
1621
2479
  }];
1622
2480
  }
1623
2481
  init() {
1624
- const { definitions = {}, responses = {}, paths = {} } = this.doc;
2482
+ const { definitions = {}, responses = {}, paths = {}, security = [], securityDefinitions = {} } = this.doc;
1625
2483
  const enums = [];
1626
2484
  const definitions_ = Object.keys(definitions).reduce((acc, key) => {
1627
2485
  const schema = definitions[key];
@@ -1634,7 +2492,7 @@ var V2 = class {
1634
2492
  const response = responses[key];
1635
2493
  return {
1636
2494
  ...acc,
1637
- [key]: this.getResponseByRef(response)
2495
+ [key]: this.getResponseByRef(response, enums)
1638
2496
  };
1639
2497
  }, {});
1640
2498
  const apis = Object.keys(paths).reduce((acc, path) => {
@@ -1655,42 +2513,42 @@ var V2 = class {
1655
2513
  if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
1656
2514
  const inBody = baseParameters.filter((p) => p.in === "body" || p.in === "formData");
1657
2515
  const notInBody = baseParameters.filter((p) => p.in !== "body" && p.in !== "formData");
1658
- const httpCodes = Object.keys(responses);
1659
- for (const code of httpCodes) if (code in responses) {
1660
- const response = responses[code];
1661
- const responseSchema = this.getResponseByRef(response);
1662
- const inBodyOnlyHasBody = inBody && inBody.length === 1 && inBody[0].in === "body" && inBody[0].name === "body";
1663
- methodApis.push({
1664
- method,
1665
- operationId,
1666
- summary: summary_,
1667
- deprecated,
1668
- description: description_,
1669
- parameters: uniqueParameterName.map((name) => notInBody.find((p) => p.name === name)).filter(Boolean),
1670
- responses: responseSchema,
1671
- requestBody: inBody.length > 0 ? inBodyOnlyHasBody ? [{
1672
- type: "application/json",
1673
- schema: inBody[0].schema
1674
- }] : [{
1675
- type: "application/json",
1676
- schema: {
1677
- type: "object",
1678
- properties: inBody.reduce((a, p) => {
1679
- return {
1680
- ...a,
1681
- [p.name]: {
1682
- type: p.schema?.type ?? "unknown",
1683
- required: p.schema?.required,
1684
- items: p.schema?.items,
1685
- description: p.schema?.description
1686
- }
1687
- };
1688
- }, {})
1689
- }
1690
- }] : void 0
1691
- });
1692
- break;
1693
- }
2516
+ const httpCodes = Object.keys(responses).filter((code) => code in responses);
2517
+ const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
2518
+ const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
2519
+ const inBodyOnlyHasBody = inBody && inBody.length === 1 && inBody[0].in === "body" && inBody[0].name === "body";
2520
+ methodApis.push({
2521
+ method,
2522
+ operationId,
2523
+ summary: summary_,
2524
+ deprecated,
2525
+ description: description_,
2526
+ parameters: uniqueParameterName.map((name) => notInBody.find((p) => p.name === name)).filter(Boolean),
2527
+ responses: responseTypes[successCode] ?? [],
2528
+ responseTypes,
2529
+ tags: methodObject.tags,
2530
+ security: methodObject.security ?? security,
2531
+ requestBody: inBody.length > 0 ? inBodyOnlyHasBody ? [{
2532
+ type: "application/json",
2533
+ schema: inBody[0].schema
2534
+ }] : [{
2535
+ type: "application/json",
2536
+ schema: {
2537
+ type: "object",
2538
+ properties: inBody.reduce((a, p) => {
2539
+ return {
2540
+ ...a,
2541
+ [p.name]: {
2542
+ type: p.schema?.type ?? "unknown",
2543
+ required: p.schema?.required,
2544
+ items: p.schema?.items,
2545
+ description: p.schema?.description
2546
+ }
2547
+ };
2548
+ }, {})
2549
+ }
2550
+ }] : void 0
2551
+ });
1694
2552
  }
1695
2553
  });
1696
2554
  return {
@@ -1704,12 +2562,12 @@ var V2 = class {
1704
2562
  responses: responses_,
1705
2563
  parameters: {},
1706
2564
  requestBodies: {},
2565
+ securitySchemes: securityDefinitions,
1707
2566
  apis
1708
2567
  };
1709
2568
  }
1710
2569
  };
1711
- //#endregion
1712
- //#region src/openapi/V3.ts
2570
+ // src/openapi/V3.ts
1713
2571
  var V3 = class {
1714
2572
  doc;
1715
2573
  constructor(doc) {
@@ -1769,7 +2627,9 @@ var V3 = class {
1769
2627
  description,
1770
2628
  deprecated,
1771
2629
  in: schema.in,
1772
- schema: { type: sameEnum?.name ?? type }
2630
+ schema: { type: sameEnum?.name ?? type },
2631
+ style: schema.style,
2632
+ explode: schema.explode
1773
2633
  };
1774
2634
  }
1775
2635
  return {
@@ -1778,13 +2638,15 @@ var V3 = class {
1778
2638
  description,
1779
2639
  deprecated,
1780
2640
  in: schema.in,
2641
+ style: schema.style,
2642
+ explode: schema.explode,
1781
2643
  schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
1782
2644
  };
1783
2645
  }
1784
2646
  /**
1785
2647
  * OpenAPI schema to base response
1786
2648
  */
1787
- getResponseByRef(schema) {
2649
+ getResponseByRef(schema, enums = []) {
1788
2650
  if (Base.isRef(schema)) {
1789
2651
  const resolvedSchema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
1790
2652
  if (!resolvedSchema) return [];
@@ -1793,7 +2655,7 @@ var V3 = class {
1793
2655
  const { content = {} } = schema;
1794
2656
  return Object.keys(content).map((c) => ({
1795
2657
  type: c,
1796
- schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
2658
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
1797
2659
  }));
1798
2660
  }
1799
2661
  /**
@@ -1818,25 +2680,27 @@ var V3 = class {
1818
2680
  if (!schema) return { type: "unknown" };
1819
2681
  if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
1820
2682
  if (this.isOpenAPIArraySchema(schema)) {
1821
- const { type, description, items, required } = schema;
2683
+ const { type, description, items, required, nullable } = schema;
1822
2684
  return {
1823
2685
  type,
2686
+ nullable,
1824
2687
  required: !!required,
1825
2688
  description,
1826
2689
  items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
1827
2690
  };
1828
2691
  } else {
1829
- const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
2692
+ const { required = [], allOf, anyOf, description, deprecated, discriminator, enum: enum_, format, oneOf, properties = {} } = schema;
1830
2693
  let { type } = schema;
1831
2694
  if (enum_ && type !== "boolean") {
1832
2695
  const enumObject = {
1833
- name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
2696
+ name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
1834
2697
  enum: [...new Set(enum_)]
1835
2698
  };
1836
2699
  const sameObject = Base.findSameSchema(enumObject, enums);
1837
2700
  if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
1838
2701
  return {
1839
2702
  type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
2703
+ nullable: schema.nullable,
1840
2704
  required,
1841
2705
  description,
1842
2706
  deprecated
@@ -1845,11 +2709,16 @@ var V3 = class {
1845
2709
  if (type === void 0 && Object.keys(properties).length > 0) type = "object";
1846
2710
  return {
1847
2711
  type,
2712
+ nullable: schema.nullable,
2713
+ additionalProperties: schema.additionalProperties && typeof schema.additionalProperties === "object" ? this.toBaseSchema(schema.additionalProperties, enums) : schema.additionalProperties,
1848
2714
  required,
1849
2715
  description,
1850
2716
  deprecated,
2717
+ discriminator,
1851
2718
  enum: enum_,
1852
2719
  format,
2720
+ readOnly: schema.readOnly,
2721
+ writeOnly: schema.writeOnly,
1853
2722
  allOf: allOf?.map((s) => Base.isRef(s) ? {
1854
2723
  ...s,
1855
2724
  ref: s.$ref,
@@ -1879,9 +2748,9 @@ var V3 = class {
1879
2748
  }
1880
2749
  }
1881
2750
  init() {
1882
- const { components = {}, paths = {} } = this.doc;
2751
+ const { components = {}, paths = {}, security = [] } = this.doc;
1883
2752
  const enums = [];
1884
- const { requestBodies = {}, responses = {}, parameters = {}, schemas = {} } = components;
2753
+ const { requestBodies = {}, responses = {}, parameters = {}, schemas = {}, securitySchemes = {} } = components;
1885
2754
  const schemas_ = Object.keys(schemas).reduce((acc, key) => {
1886
2755
  const schema = schemas[key];
1887
2756
  return {
@@ -1900,7 +2769,7 @@ var V3 = class {
1900
2769
  const response = responses[key];
1901
2770
  return {
1902
2771
  ...acc,
1903
- [key]: this.getResponseByRef(response)
2772
+ [key]: this.getResponseByRef(response, enums)
1904
2773
  };
1905
2774
  }, {});
1906
2775
  const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
@@ -1927,22 +2796,22 @@ var V3 = class {
1927
2796
  const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
1928
2797
  const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
1929
2798
  if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
1930
- const httpCodes = Object.keys(responses);
1931
- for (const code of httpCodes) if (code in responses) {
1932
- const response = responses[code];
1933
- const responseSchema = this.getResponseByRef(response);
1934
- methodApis.push({
1935
- method,
1936
- operationId,
1937
- summary: summary_ ?? summary,
1938
- description: description_ ?? description,
1939
- deprecated,
1940
- parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
1941
- responses: responseSchema,
1942
- requestBody: baseRequestBody
1943
- });
1944
- break;
1945
- }
2799
+ const httpCodes = Object.keys(responses).filter((code) => code in responses);
2800
+ const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
2801
+ const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
2802
+ methodApis.push({
2803
+ method,
2804
+ operationId,
2805
+ summary: summary_ ?? summary,
2806
+ description: description_ ?? description,
2807
+ deprecated,
2808
+ parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
2809
+ responses: responseTypes[successCode] ?? [],
2810
+ responseTypes,
2811
+ tags: methodObject.tags,
2812
+ security: methodObject.security ?? security,
2813
+ requestBody: baseRequestBody
2814
+ });
1946
2815
  }
1947
2816
  });
1948
2817
  return {
@@ -1956,12 +2825,12 @@ var V3 = class {
1956
2825
  responses: responses_,
1957
2826
  parameters: parameters_,
1958
2827
  requestBodies: requestBodies_,
2828
+ securitySchemes,
1959
2829
  apis
1960
2830
  };
1961
2831
  }
1962
2832
  };
1963
- //#endregion
1964
- //#region src/openapi/V3_1.ts
2833
+ // src/openapi/V3_1.ts
1965
2834
  var V3_1 = class {
1966
2835
  doc;
1967
2836
  constructor(doc) {
@@ -1978,7 +2847,8 @@ var V3_1 = class {
1978
2847
  * Is array schema.
1979
2848
  */
1980
2849
  isOpenAPIArraySchema(schema) {
1981
- return typeof schema === "object" && schema.type === "array";
2850
+ if (typeof schema !== "object") return false;
2851
+ return schema.type === "array" || Array.isArray(schema.type) && schema.type.includes("array");
1982
2852
  }
1983
2853
  /**
1984
2854
  * OpenAPI schema to base schema.
@@ -2015,7 +2885,9 @@ var V3_1 = class {
2015
2885
  description,
2016
2886
  deprecated,
2017
2887
  in: schema.in,
2018
- schema: { type: sameEnum?.name ?? type }
2888
+ schema: { type: sameEnum?.name ?? type },
2889
+ style: schema.style,
2890
+ explode: schema.explode
2019
2891
  };
2020
2892
  }
2021
2893
  return {
@@ -2024,18 +2896,20 @@ var V3_1 = class {
2024
2896
  description,
2025
2897
  deprecated,
2026
2898
  in: schema.in,
2899
+ style: schema.style,
2900
+ explode: schema.explode,
2027
2901
  schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
2028
2902
  };
2029
2903
  }
2030
2904
  /**
2031
2905
  * OpenAPI schema to base response
2032
2906
  */
2033
- getResponseByRef(schema) {
2907
+ getResponseByRef(schema, enums = []) {
2034
2908
  if (Base.isRef(schema)) schema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
2035
2909
  const { content = {} } = schema;
2036
2910
  return Object.keys(content).map((c) => ({
2037
2911
  type: c,
2038
- schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
2912
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
2039
2913
  }));
2040
2914
  }
2041
2915
  /**
@@ -2056,25 +2930,38 @@ var V3_1 = class {
2056
2930
  if (!schema) return { type: "unknown" };
2057
2931
  if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
2058
2932
  if (this.isOpenAPIArraySchema(schema)) {
2059
- const { type, description, items, required } = schema;
2933
+ const { description, items, required } = schema;
2934
+ const rawType = schema.type;
2060
2935
  return {
2061
- type,
2936
+ type: "array",
2937
+ nullable: Array.isArray(rawType) && rawType.includes("null"),
2062
2938
  required: !!required,
2063
2939
  description,
2064
2940
  items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
2065
2941
  };
2066
2942
  } else {
2067
- const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
2068
- let { type } = schema;
2943
+ const { required = [], allOf, anyOf, description, deprecated, discriminator, enum: enum_, format, oneOf, properties = {}, const: constValue, additionalProperties } = schema;
2944
+ const rawType = schema.type;
2945
+ const typeArray = Array.isArray(rawType) ? rawType.filter((t) => t !== "null") : void 0;
2946
+ let type = Array.isArray(rawType) ? typeArray?.[0] : schema.type;
2947
+ const nullableByType = Array.isArray(rawType) && rawType.includes("null");
2948
+ if (constValue !== void 0) return {
2949
+ type: typeof constValue === "number" ? "number" : typeof constValue === "boolean" ? "boolean" : "string",
2950
+ const: constValue,
2951
+ required,
2952
+ description,
2953
+ deprecated
2954
+ };
2069
2955
  if (enum_ && type !== "boolean") {
2070
2956
  const enumObject = {
2071
- name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
2957
+ name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
2072
2958
  enum: [...new Set(enum_)]
2073
2959
  };
2074
2960
  const sameObject = Base.findSameSchema(enumObject, enums);
2075
2961
  if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
2076
2962
  return {
2077
2963
  type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
2964
+ nullable: nullableByType,
2078
2965
  required,
2079
2966
  description,
2080
2967
  deprecated
@@ -2083,11 +2970,18 @@ var V3_1 = class {
2083
2970
  if (type === void 0 && Object.keys(properties).length > 0) type = "object";
2084
2971
  return {
2085
2972
  type,
2973
+ types: typeArray,
2974
+ nullable: nullableByType,
2975
+ const: constValue,
2976
+ additionalProperties: additionalProperties && typeof additionalProperties === "object" ? this.toBaseSchema(additionalProperties, enums) : additionalProperties,
2086
2977
  required,
2087
2978
  description,
2088
2979
  deprecated,
2980
+ discriminator,
2089
2981
  enum: enum_,
2090
2982
  format,
2983
+ readOnly: schema.readOnly,
2984
+ writeOnly: schema.writeOnly,
2091
2985
  allOf: allOf?.map((s) => Base.isRef(s) ? {
2092
2986
  ...s,
2093
2987
  ref: s.$ref,
@@ -2117,9 +3011,9 @@ var V3_1 = class {
2117
3011
  }
2118
3012
  }
2119
3013
  init() {
2120
- const { components = {}, paths = {} } = this.doc;
3014
+ const { components = {}, paths = {}, security = [] } = this.doc;
2121
3015
  const enums = [];
2122
- const { requestBodies = {}, responses = {}, parameters = {}, schemas = {} } = components;
3016
+ const { requestBodies = {}, responses = {}, parameters = {}, schemas = {}, securitySchemes = {} } = components;
2123
3017
  const schemas_ = Object.keys(schemas).reduce((acc, key) => {
2124
3018
  const schema = schemas[key];
2125
3019
  return {
@@ -2138,7 +3032,7 @@ var V3_1 = class {
2138
3032
  const response = responses[key];
2139
3033
  return {
2140
3034
  ...acc,
2141
- [key]: this.getResponseByRef(response)
3035
+ [key]: this.getResponseByRef(response, enums)
2142
3036
  };
2143
3037
  }, {});
2144
3038
  const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
@@ -2165,22 +3059,22 @@ var V3_1 = class {
2165
3059
  const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
2166
3060
  const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
2167
3061
  if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
2168
- const httpCodes = Object.keys(responses);
2169
- for (const code of httpCodes) if (code in responses) {
2170
- const response = responses[code];
2171
- const responseSchema = this.getResponseByRef(response);
2172
- methodApis.push({
2173
- method,
2174
- operationId,
2175
- summary: summary_ ?? summary,
2176
- description: description_ ?? description,
2177
- deprecated,
2178
- parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
2179
- responses: responseSchema,
2180
- requestBody: baseRequestBody
2181
- });
2182
- break;
2183
- }
3062
+ const httpCodes = Object.keys(responses).filter((code) => code in responses);
3063
+ const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
3064
+ const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
3065
+ methodApis.push({
3066
+ method,
3067
+ operationId,
3068
+ summary: summary_ ?? summary,
3069
+ description: description_ ?? description,
3070
+ deprecated,
3071
+ parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
3072
+ responses: responseTypes[successCode] ?? [],
3073
+ responseTypes,
3074
+ tags: methodObject.tags,
3075
+ security: methodObject.security ?? security,
3076
+ requestBody: baseRequestBody
3077
+ });
2184
3078
  }
2185
3079
  });
2186
3080
  return {
@@ -2194,12 +3088,12 @@ var V3_1 = class {
2194
3088
  responses: responses_,
2195
3089
  parameters: parameters_,
2196
3090
  requestBodies: requestBodies_,
3091
+ securitySchemes,
2197
3092
  apis
2198
3093
  };
2199
3094
  }
2200
3095
  };
2201
- //#endregion
2202
- //#region src/openapi/index.ts
3096
+ // src/openapi/index.ts
2203
3097
  const logger$1 = createScopedLogger("OpenAPI");
2204
3098
  let OpenAPIVersion = /* @__PURE__ */ function(OpenAPIVersion) {
2205
3099
  OpenAPIVersion["v2"] = "v2";
@@ -2236,6 +3130,18 @@ function getAdaptor(type) {
2236
3130
  default: return new FetchAdapter();
2237
3131
  }
2238
3132
  }
3133
+ /**
3134
+ * Use the document's first server when the caller did not configure a base URL.
3135
+ * Server variables fall back to their declared defaults.
3136
+ */
3137
+ function inferBaseURL(doc) {
3138
+ const server = doc.servers?.[0];
3139
+ if (server?.url) return server.url.replace(/\{([^}]+)\}/g, (_, name) => {
3140
+ return server.variables?.[name]?.default ?? `{${name}}`;
3141
+ }).replace(/\/+$/, "");
3142
+ const v2 = doc;
3143
+ if (v2.host) return `${v2.schemes?.[0] ?? "https"}://${v2.host}${(v2.basePath ?? "").replace(/\/+$/, "")}`;
3144
+ }
2239
3145
  async function codeGen(initOptions) {
2240
3146
  const startTime = Date.now();
2241
3147
  const { verbose } = initOptions;
@@ -2243,7 +3149,7 @@ async function codeGen(initOptions) {
2243
3149
  else logger$1.setLevel("info");
2244
3150
  logger$1.info(`Fetch document from ${initOptions.docURL}`);
2245
3151
  const { transport, source } = Base.resolveSpecURL(initOptions.docURL);
2246
- const { enums, schemas, parameters, responses, requestBodies, apis } = new OpenAPIProvider(initOptions, transport === "file" ? await (async () => {
3152
+ const rawDoc = transport === "file" ? await (async () => {
2247
3153
  let raw;
2248
3154
  try {
2249
3155
  raw = await readFile(source, "utf8");
@@ -2251,34 +3157,65 @@ async function codeGen(initOptions) {
2251
3157
  if (error?.code === "ENOENT") throw createErrors.specNotFound(source, error);
2252
3158
  throw new Error(`Failed to read OpenAPI spec from ${source}: ${error instanceof Error ? error.message : String(error)}`);
2253
3159
  }
2254
- try {
2255
- return JSON.parse(raw);
2256
- } catch (error) {
2257
- throw createErrors.specParseFailed(source, void 0, void 0, error);
2258
- }
2259
- })() : await Base.fetchDoc(source, initOptions.requestOptions));
3160
+ return Base.parseDoc(raw, source);
3161
+ })() : await Base.fetchDoc(source, initOptions.requestOptions);
3162
+ const doc = await Base.bundleExternalRefs(rawDoc, source, initOptions.requestOptions);
3163
+ const options = {
3164
+ ...initOptions,
3165
+ baseURL: initOptions.baseURL ?? inferBaseURL(doc)
3166
+ };
3167
+ const { enums, schemas, parameters, responses, requestBodies, securitySchemes, apis } = new OpenAPIProvider(options, doc);
2260
3168
  const adaptor = getAdaptor(initOptions.adaptor ?? "fetch");
2261
- const code = await Generator.genCode({
3169
+ const split = splitReadWrite({
2262
3170
  enums,
2263
3171
  schemas,
2264
3172
  parameters,
2265
3173
  responses,
2266
3174
  requestBodies,
3175
+ securitySchemes,
2267
3176
  apis
2268
- }, initOptions, adaptor);
2269
- if (initOptions.output) await Generator.write(code, initOptions.output);
3177
+ });
3178
+ const parsed = {
3179
+ ...split,
3180
+ apis: filterApis(split.apis, options)
3181
+ };
3182
+ const multi = initOptions.splitBy === "tag" ? await Generator.genCodeMulti(parsed, options, adaptor) : void 0;
3183
+ const code = multi?.code ?? await Generator.genCode(parsed, options, adaptor);
3184
+ if (initOptions.output) {
3185
+ if (multi) for (const [name, content] of Object.entries(multi.files)) await Generator.write(content, join(initOptions.output, name));
3186
+ else await Generator.write(code, initOptions.output);
3187
+ }
2270
3188
  const duration = Date.now() - startTime;
3189
+ const endpoints = Object.keys(apis).length;
3190
+ const schemasCount = Object.keys(schemas).length;
2271
3191
  return {
2272
3192
  code,
3193
+ ...multi ? { files: multi.files } : {},
2273
3194
  stats: {
2274
- endpoints: Object.keys(apis).length,
2275
- schemas: Object.keys(schemas).length,
3195
+ endpoints,
3196
+ schemas: schemasCount,
2276
3197
  duration
2277
3198
  }
2278
3199
  };
2279
3200
  }
2280
- //#endregion
2281
- //#region src/vite-plugin/cache.ts
3201
+ // src/core/typecheck.ts
3202
+ /**
3203
+ * Type-check a generated file with the project's TypeScript.
3204
+ *
3205
+ * @param filePath - Path to the generated file.
3206
+ * @returns Collected error messages; an empty array means success.
3207
+ */
3208
+ async function runTypeCheck(filePath) {
3209
+ try {
3210
+ await execaCommand(`npx tsc ${filePath} --noEmit`, { shell: true });
3211
+ return [];
3212
+ } catch (error) {
3213
+ return [error instanceof Error ? error.message : String(error)];
3214
+ }
3215
+ }
3216
+ // package.json
3217
+ var version = "1.0.0";
3218
+ // src/vite-plugin/cache.ts
2282
3219
  /**
2283
3220
  * Cache for a single vite-plugin codegen run. Lives only for the duration
2284
3221
  * of one plugin invocation — there is no module-level state.
@@ -2297,7 +3234,8 @@ var CodegenCache = class CodegenCache {
2297
3234
  }
2298
3235
  /** Hash the options that affect generated output (excluding the spec). */
2299
3236
  static hashOptions(options) {
2300
- const payload = Object.keys(options).sort().filter((k) => k !== "verbose" && k !== "typeCheck" && k !== "cache").map((k) => `${k}=${JSON.stringify(options[k])}`).join("|");
3237
+ const keys = Object.keys(options).sort();
3238
+ const payload = [`generatorVersion=${version}`, ...keys.filter((k) => k !== "verbose" && k !== "typeCheck" && k !== "cache").map((k) => `${k}=${JSON.stringify(options[k])}`)].join("|");
2301
3239
  return createHash("sha256").update(payload).digest("hex").slice(0, 16);
2302
3240
  }
2303
3241
  /** Hash the raw spec content so unrelated edits are detected. */
@@ -2353,24 +3291,10 @@ var CodegenCache = class CodegenCache {
2353
3291
  await writeFile(cachePath, JSON.stringify(entry));
2354
3292
  }
2355
3293
  };
2356
- //#endregion
2357
- //#region src/vite-plugin/index.ts
3294
+ // src/vite-plugin/index.ts
2358
3295
  const PLUGIN_NAME = "api-code-gen";
2359
3296
  const logger = createScopedLogger("api-code-gen");
2360
3297
  /**
2361
- * Run TypeScript type checking on generated file
2362
- */
2363
- async function runTypeCheck(filePath) {
2364
- const { execaCommand } = await import("execa");
2365
- const errors = [];
2366
- try {
2367
- await execaCommand(`npx tsc ${filePath} --noEmit`, { shell: true });
2368
- } catch (error) {
2369
- if (error instanceof Error) errors.push(error.message);
2370
- }
2371
- return errors;
2372
- }
2373
- /**
2374
3298
  * Validate spec path exists
2375
3299
  */
2376
3300
  async function validateSpecPath(specPath) {
@@ -2379,6 +3303,12 @@ async function validateSpecPath(specPath) {
2379
3303
  const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
2380
3304
  if (!await fs.pathExists(absolutePath)) throw createErrors.specNotFound(absolutePath);
2381
3305
  }
3306
+ /** Resolve a local spec to an absolute path; remote specs return null. */
3307
+ function toWatchPath(spec) {
3308
+ if (!spec || spec.startsWith("http://") || spec.startsWith("https://")) return null;
3309
+ const filePath = spec.replace(/^file:\/\//, "");
3310
+ return path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
3311
+ }
2382
3312
  /**
2383
3313
  * Generate code for a single API configuration
2384
3314
  */
@@ -2394,19 +3324,21 @@ async function generateForOption(option) {
2394
3324
  }
2395
3325
  });
2396
3326
  await validateSpecPath(config.spec);
2397
- if (config.output) {
2398
- const outputDir = path.dirname(config.output);
2399
- await fs.ensureDir(outputDir);
2400
- }
2401
3327
  let docURL = config.spec;
2402
3328
  if (!docURL.startsWith("http://") && !docURL.startsWith("https://") && !docURL.startsWith("file://") && !docURL.startsWith("/") && !/^[A-Za-z]:[\\/]/.test(docURL)) docURL = path.resolve(process.cwd(), docURL);
2403
3329
  const resolvedCacheDir = cacheDir ?? path.join(process.cwd(), "node_modules", ".cache", "apicodegen");
2404
- const codegenCache = cache ? new CodegenCache(resolvedCacheDir) : null;
3330
+ const codegenCache = cache && !config.splitBy ? new CodegenCache(resolvedCacheDir) : null;
2405
3331
  const optionsHash = CodegenCache.hashOptions({
2406
3332
  name,
2407
3333
  spec: docURL,
2408
3334
  output: config.output,
2409
3335
  adaptor: config.adaptor,
3336
+ errorMode: config.errorMode,
3337
+ splitBy: config.splitBy,
3338
+ includeTags: config.includeTags,
3339
+ excludeTags: config.excludeTags,
3340
+ includePaths: config.includePaths,
3341
+ excludePaths: config.excludePaths,
2410
3342
  baseURL: config.baseURL,
2411
3343
  importClientSource: config.importClientSource
2412
3344
  });
@@ -2448,7 +3380,13 @@ async function generateForOption(option) {
2448
3380
  if (verbose) logger.warn(`Cache write failed for ${name}: ${cacheError.message}`);
2449
3381
  }
2450
3382
  }
2451
- if (config.output) await fs.writeFile(config.output, result.code);
3383
+ if (config.output) {
3384
+ if (result.files) {
3385
+ const dir = path.dirname(config.output);
3386
+ for (const [name, content] of Object.entries(result.files)) if (name !== "index.ts") await fs.outputFile(path.join(dir, name), content);
3387
+ }
3388
+ await fs.outputFile(config.output, result.code);
3389
+ }
2452
3390
  if (typeCheck && config.output) {
2453
3391
  const typeErrors = await runTypeCheck(config.output);
2454
3392
  if (typeErrors.length > 0) {
@@ -2498,49 +3436,72 @@ function apiCodeGenPlugin(options) {
2498
3436
  logger.warn("No API configurations provided to apiCodeGenPlugin");
2499
3437
  return { name: PLUGIN_NAME };
2500
3438
  }
3439
+ let mode = "unknown";
3440
+ const watched = /* @__PURE__ */ new Set();
3441
+ const printResults = (results) => {
3442
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
3443
+ console.log(`\x1b[1m\x1b[36mAPI Code Gen\x1b[0m`);
3444
+ console.log(`\x1b[90mMode:\x1b[0m ${mode}`);
3445
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
3446
+ const successCount = results.filter((r) => r.success).length;
3447
+ const failCount = results.length - successCount;
3448
+ for (const result of results) if (result.success) {
3449
+ const { name, output, stats, cached } = result;
3450
+ if (stats) {
3451
+ const cachedTag = cached ? " \x1B[90m[cached]\x1B[0m" : "";
3452
+ console.log(`\x1b[32m✓\x1b[0m ${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms${cachedTag}`);
3453
+ } else console.log(`\x1b[32m✓\x1b[0m ${name} → ${output || "N/A"}`);
3454
+ } else {
3455
+ const { name, error } = result;
3456
+ const wrapped = isApicodegenError(error) ? error : wrapError(error, {
3457
+ code: "E_GENERATION_FAILED",
3458
+ message: `Failed to generate API "${name}"`
3459
+ });
3460
+ console.log(`\x1b[31m✗\x1b[0m ${name}`);
3461
+ console.log(`\x1b[90m${formatError(wrapped, true)}\x1b[0m`);
3462
+ }
3463
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
3464
+ const totalDuration = results.reduce((sum, r) => sum + (r.stats?.duration || 0), 0);
3465
+ const totalEndpoints = results.reduce((sum, r) => sum + (r.stats?.endpoints || 0), 0);
3466
+ const totalSchemas = results.reduce((sum, r) => sum + (r.stats?.schemas || 0), 0);
3467
+ if (failCount === 0) console.log(`\x1b[32m✓\x1b[0m API Code Gen - Complete (\x1b[90m${successCount}/${results.length} succeeded\x1b[0m, ${totalEndpoints} endpoints, ${totalSchemas} schemas, ${totalDuration}ms\x1b[0m)`);
3468
+ else console.log(`\x1b[33m⚠\x1b[0m API Code Gen - Complete (\x1b[90m${successCount} succeeded, ${failCount} failed\x1b[0m, ${totalEndpoints} endpoints, ${totalSchemas} schemas, ${totalDuration}ms\x1b[0m)`);
3469
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
3470
+ };
3471
+ const regenerate = async (option) => {
3472
+ const result = await generateForOption(option);
3473
+ printResults([result]);
3474
+ };
2501
3475
  return {
2502
3476
  name: PLUGIN_NAME,
2503
- async config(_config, env) {
2504
- console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
2505
- console.log(`\x1b[1m\x1b[36mAPI Code Gen\x1b[0m`);
2506
- console.log(`\x1b[90mMode:\x1b[0m ${env?.command || "unknown"}`);
2507
- console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
2508
- const results = await Promise.all(options.map(generateForOption));
2509
- const successCount = results.filter((r) => r.success).length;
2510
- const failCount = options.length - successCount;
2511
- console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
2512
- for (const result of results) if (result.success) {
2513
- const { name, output, stats, cached } = result;
2514
- if (stats) {
2515
- const cachedTag = cached ? " \x1B[90m[cached]\x1B[0m" : "";
2516
- console.log(`\x1b[32m✓\x1b[0m ${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms${cachedTag}`);
2517
- } else console.log(`\x1b[32m✓\x1b[0m ${name} → ${output || "N/A"}`);
2518
- } else {
2519
- const { name, error } = result;
2520
- if (isApicodegenError(error)) {
2521
- console.log(`\x1b[31m✗\x1b[0m ${name}`);
2522
- console.log(`\x1b[90m${formatError(error, true)}\x1b[0m`);
2523
- } else {
2524
- const wrapped = wrapError(error, {
2525
- code: "E_GENERATION_FAILED",
2526
- message: `Failed to generate API "${name}"`
2527
- });
2528
- console.log(`\x1b[31m✗\x1b[0m ${name}`);
2529
- console.log(`\x1b[90m${formatError(wrapped, true)}\x1b[0m`);
2530
- }
2531
- }
2532
- console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
2533
- const totalDuration = results.reduce((sum, r) => sum + (r.stats?.duration || 0), 0);
2534
- const totalEndpoints = results.reduce((sum, r) => sum + (r.stats?.endpoints || 0), 0);
2535
- const totalSchemas = results.reduce((sum, r) => sum + (r.stats?.schemas || 0), 0);
2536
- 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)`);
2537
- 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)`);
2538
- console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
3477
+ config(_config, env) {
3478
+ mode = env?.command || "unknown";
2539
3479
  return {};
3480
+ },
3481
+ async buildStart() {
3482
+ for (const option of options) {
3483
+ const specPath = toWatchPath(option.spec);
3484
+ if (specPath) this.addWatchFile(specPath);
3485
+ }
3486
+ printResults(await Promise.all(options.map(generateForOption)));
3487
+ },
3488
+ configureServer(server) {
3489
+ for (const option of options) {
3490
+ const specPath = toWatchPath(option.spec);
3491
+ if (!specPath || watched.has(specPath)) continue;
3492
+ watched.add(specPath);
3493
+ server.watcher.add(specPath);
3494
+ const onChange = async (changed) => {
3495
+ if (path.resolve(changed) !== path.resolve(specPath)) return;
3496
+ await regenerate(option);
3497
+ server.ws.send({ type: "full-reload" });
3498
+ };
3499
+ server.watcher.on("change", onChange);
3500
+ server.watcher.on("add", onChange);
3501
+ }
2540
3502
  }
2541
3503
  };
2542
3504
  }
2543
- //#endregion
2544
- export { Adapter, Adaptors, ApicodegenError, ArraySchemaType, AxiosAdapter, Base, Colors, ErrorCodes, FetchAdapter, Generator, HttpMethods, MediaTypes, NonArraySchemaType, OpenAPIProvider, OpenAPIVersion, ParameterIn, Provider, SchemaFormatType, SchemaType, SuccessHttpStatusCode, apiCodeGenPlugin, codeGen, configToCLIOptions, createErrors, formatError, isApicodegenError, loadConfig, mergeConfigs, printError, toProviderOptions, validateConfig, wrapError };
3505
+ export { Adapter, Adaptors, ApicodegenError, ArraySchemaType, AxiosAdapter, Base, Colors, ErrorCodes, FetchAdapter, Generator, HttpMethods, MediaTypes, NonArraySchemaType, OpenAPIProvider, OpenAPIVersion, ParameterIn, Provider, SchemaFormatType, SchemaType, SuccessHttpStatusCode, apiCodeGenPlugin, authAccess, authHeaderEntries, codeGen, configToCLIOptions, cookieHeaderExpression, createErrors, fetchSignalExpression, formatError, isApicodegenError, loadConfig, loadConfigs, mergeConfigs, optionalAccess, printError, toProviderOptions, validateConfig, validateConfigShape, withRequestHeaders, wrapError };
2545
3506
 
2546
3507
  //# sourceMappingURL=index.mjs.map