@moccona/apicodegen 0.1.0 → 0.1.2

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.
@@ -1,12 +1,49 @@
1
1
  import path from "node:path";
2
2
  import { createScopedLogger } from "@moccona/logger";
3
3
  import fs from "fs-extra";
4
+ import { readFile, stat, writeFile } from "node:fs/promises";
4
5
  import { Agent, request } from "undici";
5
6
  import { NodeFlags, SyntaxKind, addSyntheticLeadingComment, createPrinter, factory } from "typescript";
6
- import { writeFile } from "node:fs/promises";
7
7
  import { format } from "prettier";
8
+ import { createHash } from "node:crypto";
9
+ //#region src/core/interface.ts
10
+ let MediaTypes = /* @__PURE__ */ function(MediaTypes) {
11
+ MediaTypes["JSON"] = "application/json";
12
+ MediaTypes["TEXT"] = "text";
13
+ MediaTypes["IMAGE"] = "image";
14
+ MediaTypes["AUDIO"] = "audio";
15
+ MediaTypes["VIDEO"] = "video";
16
+ return MediaTypes;
17
+ }({});
18
+ let HttpMethods = /* @__PURE__ */ function(HttpMethods) {
19
+ HttpMethods["GET"] = "get";
20
+ HttpMethods["PUT"] = "put";
21
+ HttpMethods["POST"] = "post";
22
+ HttpMethods["DELETE"] = "delete";
23
+ HttpMethods["OPTIONS"] = "options";
24
+ HttpMethods["HEAD"] = "head";
25
+ HttpMethods["PATCH"] = "patch";
26
+ HttpMethods["TRACE"] = "trace";
27
+ return HttpMethods;
28
+ }({});
29
+ let Adaptors = /* @__PURE__ */ function(Adaptors) {
30
+ Adaptors["fetch"] = "fetch";
31
+ Adaptors["axios"] = "axios";
32
+ return Adaptors;
33
+ }({});
34
+ //#endregion
8
35
  //#region src/core/config.ts
9
36
  /**
37
+ * Strings considered truthy for boolean env vars (verbose/watch/typeCheck).
38
+ */
39
+ const TRUTHY_STRINGS = new Set([
40
+ "true",
41
+ "1",
42
+ "yes",
43
+ "on",
44
+ "enable"
45
+ ]);
46
+ /**
10
47
  * Environment variable mappings
11
48
  */
12
49
  const ENV_MAPPINGS = {
@@ -29,10 +66,10 @@ function loadFromEnv() {
29
66
  case "verbose":
30
67
  case "watch":
31
68
  case "typeCheck":
32
- config[configKey] = value === "true" || value === "1";
69
+ config[configKey] = TRUTHY_STRINGS.has(value.toLowerCase());
33
70
  break;
34
71
  case "adaptor":
35
- config[configKey] = value;
72
+ if (Object.values(Adaptors).includes(value)) config[configKey] = value;
36
73
  break;
37
74
  default: config[configKey] = value;
38
75
  }
@@ -99,7 +136,7 @@ function mergeConfigs(base, ...sources) {
99
136
  const result = { ...base };
100
137
  for (const source of sources) {
101
138
  if (!source) continue;
102
- for (const [key, value] of Object.entries(source)) if (value !== void 0) result[key] = value;
139
+ for (const [key, value] of Object.entries(source)) if (value !== void 0 && value !== null) result[key] = value;
103
140
  }
104
141
  return result;
105
142
  }
@@ -240,6 +277,29 @@ var ApicodegenError = class ApicodegenError extends Error {
240
277
  }
241
278
  };
242
279
  /**
280
+ * ANSI color codes for terminal output
281
+ */
282
+ const Colors = {
283
+ reset: "\x1B[0m",
284
+ bold: "\x1B[1m",
285
+ red: "\x1B[31m",
286
+ green: "\x1B[32m",
287
+ yellow: "\x1B[33m",
288
+ blue: "\x1B[34m",
289
+ cyan: "\x1B[36m",
290
+ gray: "\x1B[90m",
291
+ brightRed: "\x1B[91m",
292
+ brightGreen: "\x1B[92m"
293
+ };
294
+ /**
295
+ * Format error for CLI output
296
+ */
297
+ function formatError(error, verbose = false) {
298
+ if (error instanceof ApicodegenError) return error.toString(verbose);
299
+ if (error instanceof Error) return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${error.message}${verbose && error.stack ? `\n\n${Colors.gray}${error.stack}${Colors.reset}` : ""}`;
300
+ return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${String(error)}`;
301
+ }
302
+ /**
243
303
  * Create error with common patterns
244
304
  */
245
305
  const createErrors = {
@@ -335,6 +395,7 @@ const createErrors = {
335
395
  message: "TypeScript type check failed",
336
396
  location: path,
337
397
  suggestions: [
398
+ ..._errors.length > 0 ? _errors : [],
338
399
  "Review type errors above",
339
400
  "Check for schema inconsistencies",
340
401
  "Update generated types or fix source schema"
@@ -376,68 +437,6 @@ function isApicodegenError(error) {
376
437
  return error instanceof ApicodegenError;
377
438
  }
378
439
  //#endregion
379
- //#region src/core/logger.ts
380
- const cyan = (s) => `\x1b[36m${s}\x1b[0m`;
381
- const green = (s) => `\x1b[32m${s}\x1b[0m`;
382
- const red = (s) => `\x1b[31m${s}\x1b[0m`;
383
- const blue = (s) => `\x1b[34m${s}\x1b[0m`;
384
- const yellow = (s) => `\x1b[33m${s}\x1b[0m`;
385
- const magenta = (s) => `\x1b[35m${s}\x1b[0m`;
386
- const gray = (s) => `\x1b[90m${s}\x1b[0m`;
387
- const bold = (s) => `\x1b[1m${s}\x1b[0m`;
388
- const logger$1 = {
389
- success(msg) {
390
- console.log(`${green("✓")} ${msg}`);
391
- },
392
- error(err, verbose = false) {
393
- if (isApicodegenError(err)) console.error(`${red("✗")} ${err.toString(verbose)}`);
394
- else if (err instanceof Error) {
395
- const msg = `Error: ${err.message}`;
396
- console.error(`${red("✗")} ${msg}${verbose && err.stack ? `\n${gray(err.stack)}` : ""}`);
397
- } else console.error(`${red("✗")} ${String(err)}`);
398
- },
399
- info(msg) {
400
- console.log(`${blue("ℹ")} ${msg}`);
401
- },
402
- warn(msg) {
403
- console.log(`${yellow("⚠")} ${msg}`);
404
- },
405
- loading(msg) {
406
- console.log(`${yellow("🔄")} ${msg}`);
407
- },
408
- watching(msg) {
409
- console.log(`${magenta("⟳")} ${msg}`);
410
- },
411
- fileChange(filePath) {
412
- console.log(`${yellow("↓")} ${filePath}`);
413
- },
414
- fileAdd(filePath) {
415
- console.log(`${green("+")} ${filePath}`);
416
- },
417
- shutdown() {
418
- console.log(`\n${gray("👋 Shutting down...")}`);
419
- },
420
- divider(width = 50) {
421
- console.log(`${bold(cyan("─".repeat(width)))}`);
422
- },
423
- heading(text, mode, width = 50) {
424
- console.log(`${bold(cyan("─".repeat(width)))}`);
425
- console.log(`${bold(cyan(text))}`);
426
- console.log(`${gray("Mode:")} ${mode || "unknown"}`);
427
- console.log(`${bold(cyan("─".repeat(width)))}`);
428
- },
429
- item(label, color = "green") {
430
- const icon = color === "green" ? "✓" : color === "red" ? "✗" : "⚠";
431
- console.log(`${color === "green" ? green(icon) : color === "red" ? red(icon) : yellow(icon)} ${label}`);
432
- },
433
- summary(stats) {
434
- const { succeeded, failed, endpoints, schemas, duration } = stats;
435
- const label = `API Code Gen - Complete (${succeeded} succeeded${failed > 0 ? `, ${failed} failed` : ""}, ${endpoints} endpoints, ${schemas} schemas, ${duration}ms)`;
436
- if (failed === 0) console.log(`${green("✓")} ${label}`);
437
- else console.log(`${yellow("⚠")} ${label}`);
438
- }
439
- };
440
- //#endregion
441
440
  //#region src/core/base/Adaptor.ts
442
441
  /**
443
442
  * Base adapter for tool
@@ -523,28 +522,6 @@ const typescriptKeywords = new Set([
523
522
  "bigint"
524
523
  ]);
525
524
  //#endregion
526
- //#region src/core/interface.ts
527
- let MediaTypes = /* @__PURE__ */ function(MediaTypes) {
528
- MediaTypes["JSON"] = "application/json";
529
- MediaTypes["EVENT_STREAM"] = "text/event-stream";
530
- MediaTypes["TEXT"] = "text";
531
- MediaTypes["IMAGE"] = "image";
532
- MediaTypes["AUDIO"] = "audio";
533
- MediaTypes["VIDEO"] = "video";
534
- return MediaTypes;
535
- }({});
536
- let HttpMethods = /* @__PURE__ */ function(HttpMethods) {
537
- HttpMethods["GET"] = "get";
538
- HttpMethods["PUT"] = "put";
539
- HttpMethods["POST"] = "post";
540
- HttpMethods["DELETE"] = "delete";
541
- HttpMethods["OPTIONS"] = "options";
542
- HttpMethods["HEAD"] = "head";
543
- HttpMethods["PATCH"] = "patch";
544
- HttpMethods["TRACE"] = "trace";
545
- return HttpMethods;
546
- }({});
547
- //#endregion
548
525
  //#region src/core/base/Base.ts
549
526
  /**
550
527
  * @file Base class implementation
@@ -584,8 +561,20 @@ var Base = class Base {
584
561
  * @param [operationId] - Unique identifier for the operation.
585
562
  * @returns - The generated function name.
586
563
  */
587
- static pathToFnName(path, method, _operationId = "") {
588
- return Base.normalize(Base.camelCase(Base.normalize(path))) + (method ? Base.capitalize(Base.upperCamelCase(`using_${method}`)) : "");
564
+ static pathToFnName(path, method, operationId) {
565
+ let name = "";
566
+ let keywordProtected = false;
567
+ if (operationId) {
568
+ keywordProtected = typescriptKeywords.has(operationId);
569
+ name = Base.camelCase(Base.normalize(operationId));
570
+ }
571
+ if (!name) {
572
+ keywordProtected = typescriptKeywords.has(path);
573
+ name = Base.camelCase(Base.normalize(path));
574
+ }
575
+ if (keywordProtected && !name.endsWith("_")) name = `${name}_`;
576
+ const suffix = method ? Base.capitalize(Base.upperCamelCase(`using_${method}`)) : "";
577
+ return name + suffix;
589
578
  }
590
579
  /**
591
580
  * Normalizes a string by replacing special characters and avoiding TypeScript keywords.
@@ -594,7 +583,37 @@ var Base = class Base {
594
583
  */
595
584
  static normalize(text) {
596
585
  if (typescriptKeywords.has(text)) text += "_";
597
- return text.replace(/[/\-_{}():\s`,*<>$#.]/gm, "_").replace(/^\d./gm, "").replaceAll("...", "");
586
+ return text.replaceAll("...", "").replace(/[/\-_{}():\s`,*<>$#.]/gm, "_").replace(/^\d/gm, "");
587
+ }
588
+ /**
589
+ * Map a request body media type to a stable function-name suffix.
590
+ *
591
+ * Used to disambiguate sibling operations sharing the same path+method
592
+ * but different request body media types. The result is appended (in
593
+ * upperCamelCase) to the operation's base function name.
594
+ *
595
+ * Known types are mapped to short, human-readable names. Unknown types
596
+ * fall back to `camelCase(normalize(<sub-type>))`.
597
+ *
598
+ * @param mediaType - The OpenAPI media type (e.g. `application/json`).
599
+ * @returns - The suffix without leading underscore, or empty string.
600
+ */
601
+ static mediaTypeToSuffix(mediaType) {
602
+ const known = {
603
+ "application/json": "Json",
604
+ "multipart/form-data": "FormData",
605
+ "application/x-www-form-urlencoded": "FormUrlencoded",
606
+ "application/octet-stream": "OctetStream",
607
+ "text/plain": "Text",
608
+ "text/html": "Html",
609
+ "application/xml": "Xml",
610
+ "text/xml": "Xml"
611
+ };
612
+ const normalized = mediaType.toLowerCase().split(";")[0]?.trim() ?? "";
613
+ if (known[normalized]) return known[normalized];
614
+ const sub = normalized.split("/")[1];
615
+ if (!sub || sub === "*" || normalized === "*/*" || normalized === "") return "";
616
+ return Base.upperCamelCase(Base.normalize(sub));
598
617
  }
599
618
  /**
600
619
  * Capitalizes the first character of a string.
@@ -622,25 +641,91 @@ var Base = class Base {
622
641
  * @returns - UpperCamelCase string.
623
642
  */
624
643
  static upperCamelCase(text) {
625
- return Base.normalize(text).replaceAll("...", "").split("_").filter(Boolean).map(Base.capitalize).join("");
644
+ return Base.normalize(text).replaceAll("...", "").split("_").filter(Boolean).map((part) => part.match(/^\d/) ? `N${part}` : Base.capitalize(part)).join("");
645
+ }
646
+ /**
647
+ * Classify a spec location string into a transport + source pair.
648
+ *
649
+ * Returns:
650
+ * - `{ transport: 'file', source }` when `input` looks like a local
651
+ * filesystem path (`file://...`, POSIX absolute, Windows absolute).
652
+ * - `{ transport: 'http', source }` for `http(s)://...` URLs.
653
+ *
654
+ * Relative paths are treated as `http` so that callers (CLI / Vite
655
+ * plugin) must resolve them against cwd first. This makes intent
656
+ * explicit and avoids accidentally reading from process.cwd().
657
+ */
658
+ static resolveSpecURL(input) {
659
+ if (input.startsWith("file://")) {
660
+ const stripped = input.replace(/^file:\/\//, "");
661
+ return {
662
+ transport: "file",
663
+ source: /^\/[A-Za-z]:/.test(stripped) ? stripped.slice(1) : stripped
664
+ };
665
+ }
666
+ if (input.startsWith("/")) return {
667
+ transport: "file",
668
+ source: input
669
+ };
670
+ if (/^[A-Za-z]:[\\/]/.test(input)) return {
671
+ transport: "file",
672
+ source: input
673
+ };
674
+ return {
675
+ transport: "http",
676
+ source: input
677
+ };
678
+ }
679
+ /**
680
+ * Read and parse a local OpenAPI document from the filesystem.
681
+ *
682
+ * @param filePath - Absolute filesystem path to the spec.
683
+ * @returns - A promise resolving to the parsed document.
684
+ */
685
+ static async readLocalDoc(filePath) {
686
+ let raw;
687
+ try {
688
+ raw = await readFile(filePath, "utf8");
689
+ } catch (error) {
690
+ if (error?.code === "ENOENT") throw createErrors.specNotFound(filePath, error);
691
+ throw new Error(`Failed to read OpenAPI spec from ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
692
+ }
693
+ try {
694
+ return JSON.parse(raw);
695
+ } catch (error) {
696
+ throw createErrors.specParseFailed(filePath, void 0, void 0, error);
697
+ }
626
698
  }
627
699
  /**
628
700
  * Fetches documentation from a given URL.
629
- * @param url - The URL to fetch the documentation from.
630
- * @param requestInit - Additional request parameters.
701
+ *
702
+ * Supports three transport modes:
703
+ * - `file://...` URLs → read from filesystem (parsed as JSON)
704
+ * - absolute filesystem paths → read from filesystem (parsed as JSON)
705
+ * - `http(s)://...` URLs (and unrecognised inputs like relative paths)
706
+ * → fetched via undici (existing behavior)
707
+ *
708
+ * Callers should pass an already-resolved absolute path or URL. Relative
709
+ * paths fall through to undici by design — CLI / Vite plugin should
710
+ * resolve them against cwd first.
711
+ *
712
+ * @param url - The URL or filesystem path to fetch the documentation from.
713
+ * @param requestInit - Additional request parameters (only used for http(s)).
631
714
  * @returns - A promise resolving to the fetched documentation data.
632
715
  */
633
716
  static async fetchDoc(url, requestInit = {}) {
634
- const { body, statusCode } = await request(url, {
717
+ const { transport, source } = Base.resolveSpecURL(url);
718
+ if (transport === "file") return Base.readLocalDoc(source);
719
+ const { body, statusCode } = await request(source, {
635
720
  method: "GET",
636
721
  dispatcher: new Agent({ connect: { rejectUnauthorized: false } }),
637
722
  ...requestInit
638
723
  });
639
- if (statusCode >= 400) throw new Error(`Failed to fetch OpenAPI documentation from ${url}: HTTP ${statusCode}`);
724
+ if (statusCode >= 400) throw new Error(`Failed to fetch OpenAPI documentation from ${source}: HTTP ${statusCode}`);
640
725
  try {
641
726
  return body.json();
642
727
  } catch (error) {
643
- throw new Error(`Failed to parse JSON response from ${url}: ${error instanceof Error ? error.message : String(error)}`);
728
+ throw new Error(`Failed to parse JSON response from ${source}: ${error instanceof Error ? error.message : String(error)}`);
644
729
  }
645
730
  }
646
731
  /**
@@ -789,6 +874,30 @@ var Provider = class {
789
874
  }
790
875
  };
791
876
  //#endregion
877
+ //#region src/core/generator/naming.ts
878
+ /**
879
+ * Create a per-generation unique-name resolver.
880
+ *
881
+ * Tracks how many times each base name has been seen during a single
882
+ * code generation pass and returns a unique variant on every call:
883
+ *
884
+ * reserve('foo') // 'foo'
885
+ * reserve('foo') // 'foo2'
886
+ * reserve('foo') // 'foo3'
887
+ * reserve('bar') // 'bar' (independent counter)
888
+ *
889
+ * The resolver holds no module-level state — create one per generation pass
890
+ * and let it go out of scope when the pass completes.
891
+ */
892
+ const createUniqueNameResolver = () => {
893
+ const seen = /* @__PURE__ */ new Map();
894
+ return (name) => {
895
+ const next = (seen.get(name) ?? 0) + 1;
896
+ seen.set(name, next);
897
+ return next === 1 ? name : `${name}${next}`;
898
+ };
899
+ };
900
+ //#endregion
792
901
  //#region src/core/generator/index.ts
793
902
  var Generator = class Generator {
794
903
  /**
@@ -804,19 +913,10 @@ var Generator = class Generator {
804
913
  return createPrinter().printFile(sourceFile);
805
914
  }
806
915
  static async write(code, filepath) {
807
- const { mkdir } = await import("node:fs/promises");
808
- const { dirname } = await import("node:path");
809
916
  try {
810
- await mkdir(dirname(filepath), { recursive: true });
811
917
  await writeFile(filepath, code);
812
918
  } catch (error) {
813
- throw new ApicodegenError({
814
- code: ErrorCodes.OUTPUT_DIR_MISSING,
815
- message: "Failed to write generated code to output file",
816
- location: filepath,
817
- cause: error instanceof Error ? error : new Error(String(error)),
818
- suggestions: ["Verify the output directory path is writable", "Check that the parent directory exists or can be created"]
819
- });
919
+ console.error(error);
820
920
  }
821
921
  }
822
922
  /**
@@ -831,7 +931,7 @@ var Generator = class Generator {
831
931
  static toUrlTemplate(path, parameters, basePath = "") {
832
932
  const queryParameters = parameters.filter((p) => p.in === "query");
833
933
  if (queryParameters.length > 0) {
834
- const queryString = queryParameters.map((qp, index) => `${index === 0 ? "?" : "&"}${encodeURIComponent(qp.name)}={${Base.normalize(qp.name)}}`).join("");
934
+ const queryString = queryParameters.map((qp, index) => `${index === 0 ? "?" : "&"}${encodeURIComponent(qp.name)}={${Base.camelCase(Base.normalize(qp.name))}}`).join("");
835
935
  path += queryString;
836
936
  }
837
937
  const pathSegments = path.replaceAll("{", "${").split("$").filter(Boolean);
@@ -840,7 +940,7 @@ var Generator = class Generator {
840
940
  const match = /^{(.+)}(.+)?/gm.exec(segment);
841
941
  const isLastSegment = index === pathSegments.length - 2;
842
942
  if (!match) throw new Error(`Invalid path segment: ${segment}`);
843
- return factory.createTemplateSpan(factory.createIdentifier(Base.normalize(match[1])), !isLastSegment ? factory.createTemplateMiddle(match[2]) : factory.createTemplateTail(match[2] || ""));
943
+ return factory.createTemplateSpan(factory.createIdentifier(match[1]), !isLastSegment ? factory.createTemplateMiddle(match[2]) : factory.createTemplateTail(match[2] || ""));
844
944
  }));
845
945
  }
846
946
  /**
@@ -853,7 +953,10 @@ var Generator = class Generator {
853
953
  if (!Array.isArray(comments) || comments.filter(Boolean).length === 0) return;
854
954
  const formatComment = (comment) => {
855
955
  if (comment.tag === "returns") return `* @returns {${comment.type}} ${comment.comment ?? ""}`;
856
- if (comment.tag === "param") return comment.comment ? `* @param ${comment.paramName} - ${comment.comment}` : `* @param ${comment.paramName}`;
956
+ if (comment.tag === "param") {
957
+ const typePart = comment.type ? `{${comment.type}} ` : "";
958
+ return comment.comment ? `* @param ${typePart}${comment.paramName} - ${comment.comment}` : `* @param ${typePart}${comment.paramName}`;
959
+ }
857
960
  if (comment.tag) return `* @${comment.tag} ${comment.comment ?? ""}`;
858
961
  return `* ${comment.comment}`;
859
962
  };
@@ -892,15 +995,16 @@ var Generator = class Generator {
892
995
  static generateParamTags(parameters, requestBody) {
893
996
  const tags = [];
894
997
  for (const p of parameters) {
895
- const paramName = Base.normalize(p.name);
998
+ const paramName = Base.camelCase(Base.normalize(p.name));
896
999
  let paramType = "unknown";
897
1000
  if (p.schema) paramType = Generator.schemaToTypeString(p.schema);
898
1001
  const isOptional = p.required === false;
1002
+ const inPrefix = p.in ? `[${p.in}] ` : "";
899
1003
  tags.push({
900
1004
  tag: "param",
901
1005
  paramName,
902
1006
  type: `${paramType}${isOptional ? " | undefined" : ""}`,
903
- comment: p.description ?? ""
1007
+ comment: `${inPrefix}${p.description ?? ""}`
904
1008
  });
905
1009
  }
906
1010
  if (requestBody?.schema && "properties" in requestBody.schema) {
@@ -939,9 +1043,10 @@ var Generator = class Generator {
939
1043
  const propsCount = Object.keys(schema.properties ?? {}).length;
940
1044
  if (!schema.properties || propsCount === 0) return factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), factory.createToken(SyntaxKind.UnknownKeyword)]);
941
1045
  const props = Object.keys(schema.properties);
1046
+ const required = Array.isArray(schema.required) ? schema.required : [];
942
1047
  return factory.createTypeLiteralNode(props.map((propKey) => {
943
1048
  const propSchema = schema.properties[propKey];
944
- return factory.createPropertySignature(void 0, factory.createStringLiteral(propKey), schema.required || schema.ref || Generator.isBinarySchema(schema) ? void 0 : factory.createToken(SyntaxKind.QuestionToken), Generator.toTypeNode(propSchema));
1049
+ return factory.createPropertySignature(void 0, factory.createStringLiteral(propKey), required.includes(propKey) ? void 0 : factory.createToken(SyntaxKind.QuestionToken), Generator.toTypeNode(propSchema));
945
1050
  }));
946
1051
  }
947
1052
  case "integer":
@@ -962,25 +1067,46 @@ var Generator = class Generator {
962
1067
  }
963
1068
  if (enum_) return factory.createUnionTypeNode(enum_.map((e) => factory.createLiteralTypeNode(factory.createStringLiteral(e))));
964
1069
  if (type === "string") return factory.createToken(SyntaxKind.StringKeyword);
965
- if (oneOf) return factory.createUnionTypeNode(oneOf.map((schema) => Generator.toTypeNode(schema)));
966
- if (anyOf) return factory.createUnionTypeNode(anyOf.map((schema) => Generator.toTypeNode(schema)));
1070
+ if (oneOf) {
1071
+ const uniqueTypes = Generator.deduplicateTypes(oneOf.map((s) => Generator.toTypeNode(s)));
1072
+ return factory.createUnionTypeNode(uniqueTypes);
1073
+ }
1074
+ if (anyOf) {
1075
+ const uniqueTypes = Generator.deduplicateTypes(anyOf.map((s) => Generator.toTypeNode(s)));
1076
+ return factory.createUnionTypeNode(uniqueTypes);
1077
+ }
967
1078
  if (allOf) return factory.createIntersectionTypeNode(allOf.map((schema) => Generator.toTypeNode(schema)));
968
1079
  if (type && typeof type === "string") return factory.createTypeReferenceNode(type !== "unknown" && type !== "null" ? factory.createIdentifier(Base.upperCamelCase(type)) : type);
969
1080
  }
970
1081
  }
971
1082
  return factory.createToken(SyntaxKind.UnknownKeyword);
972
1083
  }
1084
+ static deduplicateTypes(types) {
1085
+ const seen = /* @__PURE__ */ new Set();
1086
+ const unique = [];
1087
+ for (const type of types) {
1088
+ const key = Generator.getTypeNodeKey(type);
1089
+ if (!seen.has(key)) {
1090
+ seen.add(key);
1091
+ unique.push(type);
1092
+ }
1093
+ }
1094
+ return unique;
1095
+ }
1096
+ static getTypeNodeKey(type) {
1097
+ return JSON.stringify(type);
1098
+ }
973
1099
  static toDeclarationNodes(parameters) {
974
1100
  const objectElements = [];
975
1101
  const typeObjectElements = [];
976
1102
  const refParameters = [];
977
1103
  for (const parameter of parameters) if (parameter.ref) {
978
1104
  const refName = Base.ref2name(parameter.ref);
979
- refParameters.push(factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(Base.normalize(refName)), void 0, factory.createTypeReferenceNode(factory.createIdentifier(Base.upperCamelCase(Base.normalize(refName)))), void 0));
1105
+ 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));
980
1106
  } else {
981
1107
  const { name, schema, required } = parameter;
982
- objectElements.push(factory.createBindingElement(void 0, void 0, factory.createIdentifier(Base.normalize(name))));
983
- typeObjectElements.push(factory.createPropertySignature([], factory.createIdentifier(Base.normalize(name)), required ? void 0 : factory.createToken(SyntaxKind.QuestionToken), !schema ? factory.createToken(SyntaxKind.UnknownKeyword) : Generator.toTypeNode(schema)));
1108
+ objectElements.push(factory.createBindingElement(void 0, void 0, factory.createIdentifier(Base.camelCase(Base.normalize(name)))));
1109
+ 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)));
984
1110
  }
985
1111
  if (objectElements.length > 0) return [factory.createParameterDeclaration(void 0, void 0, factory.createObjectBindingPattern(objectElements), void 0, factory.createTypeLiteralNode(typeObjectElements), void 0), ...refParameters];
986
1112
  return refParameters;
@@ -1004,17 +1130,77 @@ var Generator = class Generator {
1004
1130
  });
1005
1131
  return statements;
1006
1132
  }
1133
+ /**
1134
+ * Build statements that construct a `URLSearchParams` from request body
1135
+ * fields for an `application/x-www-form-urlencoded` request.
1136
+ *
1137
+ * Skips `undefined` / `null` values so optional fields don't end up as
1138
+ * the literal string `"undefined"` in the URL (fixes #8).
1139
+ *
1140
+ * The resulting `sp` variable is referenced by the adapter as the
1141
+ * `body` payload.
1142
+ */
1143
+ static toURLSearchParamsStatement(parameters, requestBody) {
1144
+ const statements = [];
1145
+ const spDeclaration = factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier("sp"), void 0, void 0, factory.createNewExpression(factory.createIdentifier("URLSearchParams"), void 0, []))], NodeFlags.Const));
1146
+ statements.push(spDeclaration);
1147
+ const appendValue = (key, valueExpr) => factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("sp"), factory.createIdentifier("append")), void 0, [factory.createStringLiteral(key), valueExpr]));
1148
+ if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) for (const key of Object.keys(requestBody.properties)) {
1149
+ const fieldSchema = requestBody.properties[key];
1150
+ const required = !!fieldSchema.required;
1151
+ const accessor = factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key));
1152
+ const append = appendValue(key, Generator.toFormDataCompatibleString(accessor, fieldSchema));
1153
+ if (required) statements.push(append);
1154
+ else statements.push(factory.createIfStatement(factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([append], true)));
1155
+ }
1156
+ for (const parameter of parameters) {
1157
+ if (parameter.in === "header" || parameter.in === "cookie" || parameter.in === "path") continue;
1158
+ const accessor = factory.createIdentifier(Base.camelCase(Base.normalize(parameter.name)));
1159
+ statements.push(factory.createIfStatement(factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([appendValue(parameter.name, Generator.toFormDataCompatibleString(accessor))], true)));
1160
+ }
1161
+ return statements;
1162
+ }
1163
+ /**
1164
+ * Render `expr` as a string suitable for `FormData.append` /
1165
+ * `URLSearchParams.append`. Object/array schemas are JSON-stringified,
1166
+ * everything else is coerced via `String(...)`.
1167
+ */
1168
+ static toFormDataCompatibleString(expr, schema) {
1169
+ if (schema && (schema.type === "object" || schema.type === "array")) return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), void 0, [expr]);
1170
+ return factory.createCallExpression(factory.createIdentifier("String"), void 0, [expr]);
1171
+ }
1007
1172
  static bodyBlock(uri, method, parameters, requestBody, response, adapter) {
1008
- const isFormDataRequest = requestBody && ["multipart/form-data", "application/x-www-form-urlencoded"].includes(requestBody.type);
1009
1173
  const shouldParseResponseToJSON = "application/json" === response?.type;
1010
- const isEventStream = response?.type === "text/event-stream";
1011
- const isRequestBodyBinary = requestBody?.schema && requestBody.schema.type === "array" && Generator.isBinarySchema(requestBody.schema);
1012
1174
  const parametersShouldPutInFormData = parameters.filter((p) => p.in === "formData" || p.schema && Generator.isBinarySchema(p.schema));
1013
1175
  const parametersShouldNotPutInFormData = parameters.filter((p) => !parametersShouldPutInFormData.includes(p));
1176
+ const inBody = parametersShouldNotPutInFormData.filter((p) => !p.in || p.in === "body");
1014
1177
  const isRequestBodyContainsBinary = requestBody?.schema && "properties" in requestBody.schema && Object.values(requestBody.schema?.properties ?? {}).some((p) => Generator.isBinarySchema(p));
1015
1178
  const hasBinaryInParameters = parameters.some((p) => p?.schema && Generator.isBinarySchema(p.schema));
1016
- const shouldPutParametersOrBodyInFormData = !!isFormDataRequest && (isRequestBodyBinary || hasBinaryInParameters || isRequestBodyContainsBinary || parametersShouldPutInFormData.length > 0);
1017
- return factory.createBlock([...shouldPutParametersOrBodyInFormData ? Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema) : [], ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, shouldPutParametersOrBodyInFormData, shouldParseResponseToJSON, isEventStream)]);
1179
+ const mediaType = (requestBody?.type ?? "").toLowerCase().split(";")[0]?.trim();
1180
+ const requestSchemaIsBinary = requestBody?.schema && Generator.isBinarySchema(requestBody.schema);
1181
+ let bodyKind = "none";
1182
+ let bodyContentType;
1183
+ if (mediaType === "multipart/form-data") {
1184
+ if (hasBinaryInParameters || isRequestBodyContainsBinary || parametersShouldPutInFormData.length > 0) bodyKind = "form-data";
1185
+ } else if (mediaType === "application/x-www-form-urlencoded") {
1186
+ bodyKind = "urlencoded";
1187
+ bodyContentType = "application/x-www-form-urlencoded";
1188
+ } else if (mediaType === "application/json") {
1189
+ if (requestBody?.schema || inBody.length > 0) {
1190
+ bodyKind = "json";
1191
+ bodyContentType = "application/json";
1192
+ }
1193
+ } else if (requestSchemaIsBinary) {
1194
+ bodyKind = "binary";
1195
+ bodyContentType = requestBody?.type;
1196
+ } else if (requestBody?.schema) {
1197
+ bodyKind = "json";
1198
+ bodyContentType = requestBody?.type;
1199
+ }
1200
+ const preStatements = [];
1201
+ if (bodyKind === "form-data") preStatements.push(...Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema));
1202
+ else if (bodyKind === "urlencoded") preStatements.push(...Generator.toURLSearchParamsStatement(parametersShouldNotPutInFormData, requestBody?.schema));
1203
+ return factory.createBlock([...preStatements, ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, bodyKind, bodyContentType, shouldParseResponseToJSON)]);
1018
1204
  }
1019
1205
  static schemaToStatemets(parsedDoc, adaptor, options) {
1020
1206
  const statements = [];
@@ -1022,14 +1208,16 @@ var Generator = class Generator {
1022
1208
  const enumNames = [];
1023
1209
  for (const enumObject of enums) {
1024
1210
  enumNames.push(Base.upperCamelCase(enumObject.name));
1025
- statements.push(factory.createEnumDeclaration([factory.createToken(SyntaxKind.ExportKeyword)], factory.createIdentifier(Base.upperCamelCase(enumObject.name)), enumObject.enum.map((member) => {
1026
- return factory.createEnumMember(factory.createStringLiteral(typeof member === "string" ? member : `${member}_`), typeof member === "string" ? factory.createStringLiteral(member) : factory.createNumericLiteral(member));
1211
+ statements.push(factory.createEnumDeclaration([factory.createToken(SyntaxKind.ExportKeyword)], factory.createIdentifier(Base.upperCamelCase(enumObject.name)), enumObject.enum.map((member, index) => {
1212
+ const key = typeof member === "string" ? member : `Value${member}`;
1213
+ return factory.createEnumMember(factory.createStringLiteral(key), typeof member === "string" ? factory.createStringLiteral(member) : factory.createNumericLiteral(member));
1027
1214
  })));
1028
1215
  }
1029
1216
  for (const schemaKey in schemas) if (Object.hasOwn(schemas, schemaKey) && !enumNames.includes(Base.upperCamelCase(schemaKey))) {
1030
1217
  const schema = schemas[schemaKey];
1031
1218
  statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(Base.upperCamelCase(schemaKey)), void 0, Generator.toTypeNode(schema)));
1032
1219
  }
1220
+ const reserveUnique = createUniqueNameResolver();
1033
1221
  for (const uri in apis) {
1034
1222
  const operations = apis[uri];
1035
1223
  for (const operation of operations) {
@@ -1039,7 +1227,7 @@ var Generator = class Generator {
1039
1227
  if (requestBody.length === 0) requestBody.push({ type: "application/json" });
1040
1228
  const shouldAddExtraMethodNameSuffix = requestBody.length > 1;
1041
1229
  for (const req of requestBody) {
1042
- const statement = factory.createFunctionDeclaration([factory.createModifier(SyntaxKind.ExportKeyword), factory.createModifier(SyntaxKind.AsyncKeyword)], void 0, Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.capitalize(req.type.split("/")[1]) : ""), 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));
1230
+ const statement = factory.createFunctionDeclaration([factory.createModifier(SyntaxKind.ExportKeyword), factory.createModifier(SyntaxKind.AsyncKeyword)], void 0, reserveUnique(Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.mediaTypeToSuffix(req.type) : "")), void 0, [...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));
1043
1231
  const mergedDescription = [description, summary].filter(Boolean).join(". ");
1044
1232
  Generator.addComments(statement, [
1045
1233
  mergedDescription && { comment: mergedDescription },
@@ -1067,7 +1255,7 @@ var Generator = class Generator {
1067
1255
  //#region src/core/client/axios.ts
1068
1256
  /**
1069
1257
  * Adapter class implementing support for generating code that makes use of the Axios HTTP client library.
1070
- * This class defines custom behavior and field mappings specific to the Axios client.
1258
+ * This adapter defines custom behavior and field mappings specific to the Axios client.
1071
1259
  */
1072
1260
  var AxiosAdapter = class extends Adapter {
1073
1261
  /**
@@ -1091,35 +1279,38 @@ var AxiosAdapter = class extends Adapter {
1091
1279
  */
1092
1280
  name = "axios";
1093
1281
  /**
1094
- * Generates client code for making API requests using Axios.
1095
- * @param uri - The API endpoint URI
1096
- * @param method - The HTTP method (GET, POST, etc.)
1097
- * @param parameters - Array of parameters to include in the request
1098
- * @param requestBody - The request body media type definition
1099
- * @param response - The response media type definition
1100
- * @param adapter - The adapter instance
1101
- * @param shouldUseFormData - Flag to use FormData for the request body
1102
- * @param shouldUseJSONResponse - Unused by AxiosAdapter; present to align with the abstract signature so positional args bind correctly
1103
- * @param isEventStream - Flag indicating a text/event-stream response; when true the raw AxiosResponse is returned without JSON parsing
1104
- * @return - An array of generated TypeScript statements
1282
+ * Method that should generate and return the client-specific configuration statements.
1283
+ *
1284
+ * @returns {Statement[]} An array of TypeScript statements that define the client configuration.
1105
1285
  */
1106
- client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData, _shouldUseJSONResponse, isEventStream) {
1286
+ client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, _shouldUseJSONResponse) {
1107
1287
  const statements = [];
1108
- const inBody = parameters.filter((p) => !p.in || p.in === "body");
1288
+ parameters.filter((p) => !p.in || p.in === "body");
1109
1289
  const inHeader = parameters.filter((p) => p.in === "header");
1110
- /**
1111
- * Creates the literal object expression for fetch options
1112
- * including method, headers, and body.
1113
- * @returns - The constructed fetch options object
1114
- */
1115
1290
  const toLiterlExpression = () => {
1116
- return factory.createObjectLiteralExpression([factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))].concat(inHeader.length > 0 ? factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(inHeader.map((p) => factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.normalize(p.name))])]))))) : []).concat(shouldUseFormData || inBody.length > 0 || requestBody?.schema ? factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), shouldUseFormData ? factory.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? factory.createIdentifier("req") : factory.createIdentifier("req")) : []), true);
1291
+ const headerEntries = [];
1292
+ for (const p of inHeader) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.camelCase(Base.normalize(p.name)))])])));
1293
+ if (bodyContentType !== void 0) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Content-Type"), factory.createStringLiteral(bodyContentType)));
1294
+ const properties = [factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))];
1295
+ if (headerEntries.length > 0) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(headerEntries)));
1296
+ let bodyExpr;
1297
+ switch (bodyKind) {
1298
+ case "form-data":
1299
+ bodyExpr = factory.createIdentifier("fd");
1300
+ break;
1301
+ case "urlencoded":
1302
+ bodyExpr = factory.createIdentifier("sp");
1303
+ break;
1304
+ case "json":
1305
+ case "binary":
1306
+ bodyExpr = factory.createIdentifier("req");
1307
+ break;
1308
+ case "none": break;
1309
+ }
1310
+ if (bodyExpr) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
1311
+ return factory.createObjectLiteralExpression(properties, true);
1117
1312
  };
1118
- if (isEventStream) {
1119
- statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1120
- return statements;
1121
- }
1122
- statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createIdentifier(adapter.name), response?.schema ? [Generator.toTypeNode(response.schema)] : void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1313
+ 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()])));
1123
1314
  return statements;
1124
1315
  }
1125
1316
  };
@@ -1143,12 +1334,12 @@ var FetchAdapter = class extends Adapter {
1143
1334
  * @param requestBody - The request body media type definition
1144
1335
  * @param response - The response media type definition
1145
1336
  * @param adapter - The adapter instance
1146
- * @param shouldUseFormData - Flag to use FormData for the request body
1337
+ * @param bodyKind - How the body should be encoded (json / form-data / urlencoded / binary / none)
1338
+ * @param bodyContentType - Content-Type header to inject (undefined means "let runtime decide", e.g. multipart boundary)
1147
1339
  * @param shouldUseJSONResponse - Flag to use JSON parsing for the response
1148
- * @param isEventStream - Flag indicating a text/event-stream response; when true the raw Response is returned unparsed
1149
1340
  * @return - An array of generated TypeScript statements
1150
1341
  */
1151
- client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData, shouldUseJSONResponse, isEventStream) {
1342
+ client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, shouldUseJSONResponse) {
1152
1343
  const statements = [];
1153
1344
  const inBody = parameters.filter((p) => !p.in || p.in === "body");
1154
1345
  const inHeader = parameters.filter((p) => p.in === "header");
@@ -1158,23 +1349,43 @@ var FetchAdapter = class extends Adapter {
1158
1349
  * @returns - The constructed fetch options object
1159
1350
  */
1160
1351
  const toLiterlExpression = () => {
1161
- return factory.createObjectLiteralExpression([factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))].concat(inHeader.length > 0 ? factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(inHeader.map((p) => factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.normalize(p.name))])]))))) : []).concat(shouldUseFormData || inBody.length > 0 || requestBody?.schema ? factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), shouldUseFormData ? factory.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), [], [requestBody ? factory.createIdentifier("req") : factory.createObjectLiteralExpression(inBody.map((b) => factory.createShorthandPropertyAssignment(factory.createIdentifier(b.name))), true)]) : factory.createIdentifier("req")) : []), true);
1352
+ const headerEntries = [];
1353
+ for (const p of inHeader) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.camelCase(Base.normalize(p.name)))])])));
1354
+ if (bodyContentType !== void 0) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Content-Type"), factory.createStringLiteral(bodyContentType)));
1355
+ const properties = [factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))];
1356
+ if (headerEntries.length > 0) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(headerEntries)));
1357
+ let bodyExpr;
1358
+ switch (bodyKind) {
1359
+ case "form-data":
1360
+ bodyExpr = factory.createIdentifier("fd");
1361
+ break;
1362
+ case "urlencoded":
1363
+ bodyExpr = factory.createIdentifier("sp");
1364
+ break;
1365
+ case "json": {
1366
+ const arg = requestBody ? factory.createIdentifier("req") : factory.createObjectLiteralExpression(inBody.map((b) => factory.createShorthandPropertyAssignment(factory.createIdentifier(b.name))), true);
1367
+ bodyExpr = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), [], [arg]);
1368
+ break;
1369
+ }
1370
+ case "binary":
1371
+ bodyExpr = factory.createIdentifier("req");
1372
+ break;
1373
+ case "none": break;
1374
+ }
1375
+ if (bodyExpr) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
1376
+ return factory.createObjectLiteralExpression(properties, true);
1162
1377
  };
1163
- if (isEventStream) {
1164
- statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1165
- return statements;
1166
- }
1167
- 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, []))), response?.schema ? Generator.toTypeNode(response.schema) : factory.createToken(SyntaxKind.UnknownKeyword)) : factory.createParenthesizedExpression(factory.createAwaitExpression(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("response"), factory.createIdentifier("json")), void 0, []))))]) : factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1378
+ 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()])));
1168
1379
  return statements;
1169
1380
  }
1170
1381
  };
1171
1382
  //#endregion
1172
- //#region src/openapi/VersionedProvider.ts
1173
- /**
1174
- * Abstract base class. Subclasses implement the four container accessors
1175
- * and a version tag. The shared logic lives here.
1176
- */
1177
- var VersionedProvider = class {
1383
+ //#region src/openapi/V2.ts
1384
+ var V2 = class {
1385
+ doc;
1386
+ constructor(doc) {
1387
+ this.doc = doc;
1388
+ }
1178
1389
  /**
1179
1390
  * Resolves a path $ref to the actual path object.
1180
1391
  */
@@ -1186,99 +1397,342 @@ var VersionedProvider = class {
1186
1397
  * Is array schema.
1187
1398
  */
1188
1399
  isOpenAPIArraySchema(schema) {
1189
- return typeof schema === "object" && schema !== null && schema.type === "array";
1400
+ return typeof schema === "object" && schema.type === "array";
1190
1401
  }
1191
1402
  /**
1192
- * OpenAPI schema to base schema. Override for version-specific quirks
1193
- * (V3_1 throws on missing ref; V3 returns `{ type: 'unknown' }`).
1403
+ * OpenAPI schema to base schema.
1194
1404
  */
1195
1405
  getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
1196
1406
  let refName = "";
1197
1407
  if (Base.isRef(schema)) {
1198
- refName = this.formatRefName(Base.ref2name(schema.$ref));
1408
+ refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
1199
1409
  if (reserveRef) return { type: upLevelSchemaKey + refName };
1200
- const resolvedSchema = this.getSchemaContainer()?.[Base.ref2name(schema.$ref, this.doc)];
1201
- if (!resolvedSchema) return { type: "unknown" };
1202
- schema = resolvedSchema;
1410
+ if (!this.doc.definitions) this.doc.definitions = {};
1411
+ schema = this.doc.definitions[Base.ref2name(schema.$ref, this.doc)];
1203
1412
  }
1204
1413
  return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
1205
1414
  }
1206
1415
  /**
1207
- * Format a ref name for the schema's `type` field.
1208
- * V3 uses `capitalize`; V3_1 uses `upperCamelCase` (preserved for compat).
1416
+ * Transform all OpenAPI schema to Base Schema
1209
1417
  */
1210
- formatRefName(name) {
1211
- return Base.capitalize(name);
1418
+ toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
1419
+ if (!schema) return { type: "unknown" };
1420
+ if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
1421
+ if (this.isOpenAPIArraySchema(schema)) {
1422
+ const { type, description, items, required } = schema;
1423
+ return {
1424
+ type,
1425
+ required: !!required,
1426
+ description,
1427
+ items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
1428
+ };
1429
+ } else {
1430
+ const { required = [], allOf, anyOf, description, enum: enum_, format, oneOf, properties = {} } = schema;
1431
+ let { type } = schema;
1432
+ if (enum_ && type !== "boolean") {
1433
+ const enumObject = {
1434
+ name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
1435
+ enum: [...new Set(enum_)]
1436
+ };
1437
+ const sameObject = Base.findSameSchema(enumObject, enums);
1438
+ if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
1439
+ return {
1440
+ type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
1441
+ required,
1442
+ description
1443
+ };
1444
+ }
1445
+ if (type === void 0 && Object.keys(properties).length > 0) type = "object";
1446
+ return {
1447
+ type,
1448
+ required,
1449
+ description,
1450
+ enum: enum_,
1451
+ format,
1452
+ allOf: allOf?.map((s) => Base.isRef(s) ? {
1453
+ ...s,
1454
+ ref: s.$ref,
1455
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1456
+ } : this.toBaseSchema(s, enums)),
1457
+ anyOf: anyOf?.map((s) => Base.isRef(s) ? {
1458
+ ...s,
1459
+ ref: s.$ref,
1460
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1461
+ } : this.toBaseSchema(s, enums)),
1462
+ oneOf: oneOf?.map((s) => Base.isRef(s) ? {
1463
+ ...s,
1464
+ ref: s.$ref,
1465
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1466
+ } : this.toBaseSchema(s, enums)),
1467
+ properties: Object.keys(properties).reduce((acc, p) => {
1468
+ const propSchema = properties[p];
1469
+ return {
1470
+ ...acc,
1471
+ [p]: Base.isRef(propSchema) ? { type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)) } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
1472
+ };
1473
+ }, {})
1474
+ };
1475
+ }
1212
1476
  }
1213
1477
  /**
1214
- * OpenAPI parameter to base parameter. Override in V2 — its parameter
1215
- * shape is structurally different (top-level `items`/`properties`/`enum`).
1478
+ * OpenAPI parameter to base parameter.
1216
1479
  */
1217
- getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
1218
- if (Base.isRef(schema)) {
1219
- const resolvedSchema = this.getParameterContainer()?.[Base.ref2name(schema.$ref, this.doc)];
1220
- if (!resolvedSchema) return {
1221
- name: "unknown",
1222
- in: "query"
1223
- };
1224
- schema = resolvedSchema;
1480
+ getParameterByRef(parameter, enums = [], upLevelSchemaKey = "") {
1481
+ if (Base.isRef(parameter)) {
1482
+ const refName = Base.ref2name(parameter.$ref, this.doc);
1483
+ const resolved = this.doc.parameters?.[refName];
1484
+ if (!resolved) throw new Error(`Parameter reference not found: ${parameter.$ref}`);
1485
+ parameter = resolved;
1225
1486
  }
1226
- const { name, required, deprecated, description, schema: parameterSchema } = schema;
1227
- if (parameterSchema && !Base.isRef(parameterSchema) && parameterSchema.enum) {
1487
+ const p = parameter;
1488
+ const { name, required, description, type, items, enum: enum_, properties, schema } = p;
1489
+ if (enum_) {
1228
1490
  const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
1229
1491
  const enumSchema = {
1230
1492
  name: type,
1231
- enum: [...new Set(parameterSchema.enum)]
1493
+ enum: [...new Set(enum_)]
1232
1494
  };
1233
1495
  const sameEnum = Base.findSameSchema(enumSchema, enums);
1234
- if (!sameEnum && Base.isValidEnumType(parameterSchema)) enums.push(enumSchema);
1496
+ if (!sameEnum && Base.isValidEnumType({
1497
+ type,
1498
+ enum: enum_
1499
+ })) enums.push(enumSchema);
1235
1500
  return {
1236
1501
  name,
1237
1502
  required,
1238
1503
  description,
1239
- deprecated,
1240
- in: schema.in,
1504
+ in: p.in,
1241
1505
  schema: { type: sameEnum?.name ?? type }
1242
1506
  };
1243
1507
  }
1508
+ if (items) return {
1509
+ name,
1510
+ required,
1511
+ description,
1512
+ in: p.in,
1513
+ schema: {
1514
+ type,
1515
+ items
1516
+ }
1517
+ };
1518
+ if (schema && Base.isRef(schema)) return {
1519
+ name,
1520
+ required,
1521
+ description,
1522
+ in: p.in,
1523
+ schema: { type: Base.capitalize(Base.ref2name(schema.$ref)) }
1524
+ };
1244
1525
  return {
1245
1526
  name,
1246
1527
  required,
1247
1528
  description,
1248
- deprecated,
1249
- in: schema.in,
1250
- schema: schema.schema ? this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name)) : void 0
1529
+ in: p.in,
1530
+ schema: {
1531
+ type,
1532
+ properties
1533
+ }
1251
1534
  };
1252
1535
  }
1253
1536
  /**
1254
- * OpenAPI schema to base response. Override in V2 (its response shape
1255
- * lacks the `content` wrapper).
1537
+ * OpenAPI schema to base response
1256
1538
  */
1257
1539
  getResponseByRef(schema) {
1258
- if (Base.isRef(schema)) {
1259
- const resolvedSchema = this.getResponseContainer()?.[Base.ref2name(schema.$ref, this.doc)];
1260
- if (!resolvedSchema) return [];
1261
- schema = resolvedSchema;
1262
- }
1263
- const { content = {} } = schema;
1264
- return Object.keys(content).map((c) => ({
1265
- type: c,
1266
- schema: content[c].schema ? this.getSchemaByRef(content[c].schema, true) : void 0
1267
- }));
1540
+ if (Base.isRef(schema)) schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
1541
+ const { schema: responseSchema } = schema;
1542
+ return [{
1543
+ type: "application/json",
1544
+ schema: responseSchema && this.getSchemaByRef(responseSchema, true)
1545
+ }];
1268
1546
  }
1269
- /**
1270
- * OpenAPI schema to requestBody. V2 has no requestBody concept.
1271
- */
1547
+ init() {
1548
+ const { definitions = {}, responses = {}, paths = {} } = this.doc;
1549
+ const enums = [];
1550
+ const definitions_ = Object.keys(definitions).reduce((acc, key) => {
1551
+ const schema = definitions[key];
1552
+ return {
1553
+ ...acc,
1554
+ [key]: this.getSchemaByRef(schema, false, enums, key)
1555
+ };
1556
+ }, {});
1557
+ const responses_ = Object.keys(responses).reduce((acc, key) => {
1558
+ const response = responses[key];
1559
+ return {
1560
+ ...acc,
1561
+ [key]: this.getResponseByRef(response)
1562
+ };
1563
+ }, {});
1564
+ const apis = Object.keys(paths).reduce((acc, path) => {
1565
+ let pathObject = paths[path] ?? {};
1566
+ if (pathObject.$ref) {
1567
+ const resolved = this.resolvePathRef(pathObject.$ref);
1568
+ if (resolved) pathObject = resolved;
1569
+ }
1570
+ const { parameters = [] } = pathObject;
1571
+ const methodApis = [];
1572
+ Object.values(HttpMethods).forEach((method) => {
1573
+ const methodObject = pathObject[method];
1574
+ if (methodObject) {
1575
+ const { deprecated, operationId, summary: summary_, description: description_, responses = {} } = methodObject;
1576
+ const { parameters: parameters_ = [] } = methodObject;
1577
+ const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
1578
+ const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
1579
+ if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
1580
+ const inBody = baseParameters.filter((p) => p.in === "body" || p.in === "formData");
1581
+ const notInBody = baseParameters.filter((p) => p.in !== "body" && p.in !== "formData");
1582
+ const httpCodes = Object.keys(responses);
1583
+ for (const code of httpCodes) if (code in responses) {
1584
+ const response = responses[code];
1585
+ const responseSchema = this.getResponseByRef(response);
1586
+ const inBodyOnlyHasBody = inBody && inBody.length === 1 && inBody[0].in === "body" && inBody[0].name === "body";
1587
+ methodApis.push({
1588
+ method,
1589
+ operationId,
1590
+ summary: summary_,
1591
+ deprecated,
1592
+ description: description_,
1593
+ parameters: uniqueParameterName.map((name) => notInBody.find((p) => p.name === name)).filter(Boolean),
1594
+ responses: responseSchema,
1595
+ requestBody: inBody.length > 0 ? inBodyOnlyHasBody ? [{
1596
+ type: "application/json",
1597
+ schema: inBody[0].schema
1598
+ }] : [{
1599
+ type: "application/json",
1600
+ schema: {
1601
+ type: "object",
1602
+ properties: inBody.reduce((a, p) => {
1603
+ return {
1604
+ ...a,
1605
+ [p.name]: {
1606
+ type: p.schema?.type ?? "unknown",
1607
+ required: p.schema?.required,
1608
+ items: p.schema?.items,
1609
+ description: p.schema?.description
1610
+ }
1611
+ };
1612
+ }, {})
1613
+ }
1614
+ }] : void 0
1615
+ });
1616
+ break;
1617
+ }
1618
+ }
1619
+ });
1620
+ return {
1621
+ ...acc,
1622
+ [path]: methodApis
1623
+ };
1624
+ }, {});
1625
+ return {
1626
+ enums: Base.uniqueEnums(enums),
1627
+ schemas: definitions_,
1628
+ responses: responses_,
1629
+ parameters: {},
1630
+ requestBodies: {},
1631
+ apis
1632
+ };
1633
+ }
1634
+ };
1635
+ //#endregion
1636
+ //#region src/openapi/V3.ts
1637
+ var V3 = class {
1638
+ doc;
1639
+ constructor(doc) {
1640
+ this.doc = doc;
1641
+ }
1642
+ /**
1643
+ * Resolves a path $ref to the actual path object.
1644
+ */
1645
+ resolvePathRef($ref) {
1646
+ const refName = Base.ref2name($ref, this.doc);
1647
+ return this.doc.paths?.[refName];
1648
+ }
1649
+ /**
1650
+ * Is array schema.
1651
+ */
1652
+ isOpenAPIArraySchema(schema) {
1653
+ return typeof schema === "object" && schema.type === "array";
1654
+ }
1655
+ /**
1656
+ * OpenAPI schema to base schema.
1657
+ */
1658
+ getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
1659
+ let refName = "";
1660
+ if (Base.isRef(schema)) {
1661
+ refName = Base.capitalize(Base.ref2name(schema.$ref));
1662
+ if (reserveRef) return { type: upLevelSchemaKey + refName };
1663
+ const resolvedSchema = this.doc.components?.schemas?.[Base.ref2name(schema.$ref, this.doc)];
1664
+ if (!resolvedSchema) return { type: "unknown" };
1665
+ schema = resolvedSchema;
1666
+ }
1667
+ return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
1668
+ }
1669
+ /**
1670
+ * OpenAPI parameter to base parameter.
1671
+ */
1672
+ getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
1673
+ if (Base.isRef(schema)) {
1674
+ const resolvedSchema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
1675
+ if (!resolvedSchema) return {
1676
+ name: "unknown",
1677
+ in: "query"
1678
+ };
1679
+ schema = resolvedSchema;
1680
+ }
1681
+ const { name, required, deprecated, description, schema: parameterSchema } = schema;
1682
+ if (parameterSchema && !Base.isRef(parameterSchema) && parameterSchema.enum) {
1683
+ const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
1684
+ const enumSchema = {
1685
+ name: type,
1686
+ enum: [...new Set(parameterSchema.enum)]
1687
+ };
1688
+ const sameEnum = Base.findSameSchema(enumSchema, enums);
1689
+ if (!sameEnum && Base.isValidEnumType(parameterSchema)) enums.push(enumSchema);
1690
+ return {
1691
+ name,
1692
+ required,
1693
+ description,
1694
+ deprecated,
1695
+ in: schema.in,
1696
+ schema: { type: sameEnum?.name ?? type }
1697
+ };
1698
+ }
1699
+ return {
1700
+ name,
1701
+ required,
1702
+ description,
1703
+ deprecated,
1704
+ in: schema.in,
1705
+ schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
1706
+ };
1707
+ }
1708
+ /**
1709
+ * OpenAPI schema to base response
1710
+ */
1711
+ getResponseByRef(schema) {
1712
+ if (Base.isRef(schema)) {
1713
+ const resolvedSchema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
1714
+ if (!resolvedSchema) return [];
1715
+ schema = resolvedSchema;
1716
+ }
1717
+ const { content = {} } = schema;
1718
+ return Object.keys(content).map((c) => ({
1719
+ type: c,
1720
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
1721
+ }));
1722
+ }
1723
+ /**
1724
+ * OpenAPI schema to requestBody.
1725
+ */
1272
1726
  getRequestBodyByRef(schema, enums = []) {
1273
1727
  if (Base.isRef(schema)) {
1274
- const resolvedSchema = this.getRequestBodyContainer()?.[Base.ref2name(schema.$ref, this.doc)];
1728
+ const resolvedSchema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
1275
1729
  if (!resolvedSchema) return [];
1276
1730
  schema = resolvedSchema;
1277
1731
  }
1278
1732
  const { content = {} } = schema;
1279
1733
  return Object.keys(content).map((c) => ({
1280
1734
  type: c,
1281
- schema: content[c].schema ? this.getSchemaByRef(content[c].schema, false, enums) : void 0
1735
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, false, enums)
1282
1736
  }));
1283
1737
  }
1284
1738
  /**
@@ -1289,98 +1743,92 @@ var VersionedProvider = class {
1289
1743
  if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
1290
1744
  if (this.isOpenAPIArraySchema(schema)) {
1291
1745
  const { type, description, items, required } = schema;
1292
- const itemsSchema = items ? this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey) : { type: "unknown" };
1293
1746
  return {
1294
1747
  type,
1295
1748
  required: !!required,
1296
1749
  description,
1297
- items: itemsSchema
1298
- };
1299
- }
1300
- const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
1301
- let { type } = schema;
1302
- if (enum_ && type !== "boolean") {
1303
- const enumObject = {
1304
- name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
1305
- enum: [...new Set(enum_)]
1750
+ items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
1306
1751
  };
1307
- const sameObject = Base.findSameSchema(enumObject, enums);
1308
- if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
1752
+ } else {
1753
+ const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
1754
+ let { type } = schema;
1755
+ if (enum_ && type !== "boolean") {
1756
+ const enumObject = {
1757
+ name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
1758
+ enum: [...new Set(enum_)]
1759
+ };
1760
+ const sameObject = Base.findSameSchema(enumObject, enums);
1761
+ if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
1762
+ return {
1763
+ type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
1764
+ required,
1765
+ description,
1766
+ deprecated
1767
+ };
1768
+ }
1769
+ if (type === void 0 && Object.keys(properties).length > 0) type = "object";
1309
1770
  return {
1310
- type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
1771
+ type,
1311
1772
  required,
1312
1773
  description,
1313
- deprecated
1774
+ deprecated,
1775
+ enum: enum_,
1776
+ format,
1777
+ allOf: allOf?.map((s) => Base.isRef(s) ? {
1778
+ ...s,
1779
+ ref: s.$ref,
1780
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1781
+ } : this.toBaseSchema(s, enums)),
1782
+ anyOf: anyOf?.map((s) => Base.isRef(s) ? {
1783
+ ...s,
1784
+ ref: s.$ref,
1785
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1786
+ } : this.toBaseSchema(s, enums)),
1787
+ oneOf: oneOf?.map((s) => Base.isRef(s) ? {
1788
+ ...s,
1789
+ ref: s.$ref,
1790
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1791
+ } : this.toBaseSchema(s, enums)),
1792
+ properties: Object.keys(properties).reduce((acc, p) => {
1793
+ const propSchema = properties[p];
1794
+ return {
1795
+ ...acc,
1796
+ [p]: Base.isRef(propSchema) ? {
1797
+ type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)),
1798
+ isRef: true
1799
+ } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
1800
+ };
1801
+ }, {})
1314
1802
  };
1315
1803
  }
1316
- if (type === void 0 && Object.keys(properties).length > 0) type = "object";
1317
- return {
1318
- type,
1319
- required,
1320
- description,
1321
- deprecated,
1322
- enum: enum_,
1323
- format,
1324
- allOf: allOf?.map((s) => Base.isRef(s) ? {
1325
- ...s,
1326
- ref: s.$ref,
1327
- type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1328
- } : this.toBaseSchema(s, enums)),
1329
- anyOf: anyOf?.map((s) => Base.isRef(s) ? {
1330
- ...s,
1331
- ref: s.$ref,
1332
- type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1333
- } : this.toBaseSchema(s, enums)),
1334
- oneOf: oneOf?.map((s) => Base.isRef(s) ? {
1335
- ...s,
1336
- ref: s.$ref,
1337
- type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1338
- } : this.toBaseSchema(s, enums)),
1339
- properties: Object.keys(properties).reduce((acc, p) => {
1340
- const propSchema = properties[p];
1341
- return {
1342
- ...acc,
1343
- [p]: Base.isRef(propSchema) ? {
1344
- type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)),
1345
- isRef: true
1346
- } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
1347
- };
1348
- }, {})
1349
- };
1350
1804
  }
1351
- /**
1352
- * Run the parsing pipeline and return a ProviderInitResult.
1353
- */
1354
1805
  init() {
1355
- const { paths = {} } = this.doc;
1806
+ const { components = {}, paths = {} } = this.doc;
1356
1807
  const enums = [];
1357
- const schemaContainer = this.getSchemaContainer() ?? {};
1358
- const parameterContainer = this.getParameterContainer() ?? {};
1359
- const responseContainer = this.getResponseContainer() ?? {};
1360
- const requestBodyContainer = this.getRequestBodyContainer() ?? {};
1361
- const schemas_ = Object.keys(schemaContainer).reduce((acc, key) => {
1362
- const schema = schemaContainer[key];
1808
+ const { requestBodies = {}, responses = {}, parameters = {}, schemas = {} } = components;
1809
+ const schemas_ = Object.keys(schemas).reduce((acc, key) => {
1810
+ const schema = schemas[key];
1363
1811
  return {
1364
1812
  ...acc,
1365
1813
  [key]: this.getSchemaByRef(schema, false, enums, key)
1366
1814
  };
1367
1815
  }, {});
1368
- const parameters_ = Object.keys(parameterContainer).reduce((acc, key) => {
1369
- const parameter = parameterContainer[key];
1816
+ const parameters_ = Object.keys(parameters).reduce((acc, key) => {
1817
+ const parameter = parameters[key];
1370
1818
  return {
1371
1819
  ...acc,
1372
1820
  [key]: this.getParameterByRef(parameter, enums, key)
1373
1821
  };
1374
1822
  }, {});
1375
- const responses_ = Object.keys(responseContainer).reduce((acc, key) => {
1376
- const response = responseContainer[key];
1823
+ const responses_ = Object.keys(responses).reduce((acc, key) => {
1824
+ const response = responses[key];
1377
1825
  return {
1378
1826
  ...acc,
1379
1827
  [key]: this.getResponseByRef(response)
1380
1828
  };
1381
1829
  }, {});
1382
- const requestBodies_ = Object.keys(requestBodyContainer).reduce((acc, key) => {
1383
- const requestBody = requestBodyContainer[key];
1830
+ const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
1831
+ const requestBody = requestBodies[key];
1384
1832
  return {
1385
1833
  ...acc,
1386
1834
  [key]: this.getRequestBodyByRef(requestBody, enums)
@@ -1397,16 +1845,15 @@ var VersionedProvider = class {
1397
1845
  Object.values(HttpMethods).forEach((method) => {
1398
1846
  const methodObject = pathObject[method];
1399
1847
  if (methodObject) {
1400
- const { deprecated, operationId, responses, summary: summary_, description: description_, requestBody = { content: {} } } = methodObject;
1401
- const responsesClone = responses ? { ...responses } : {};
1848
+ const { deprecated, operationId, responses = {}, summary: summary_, description: description_, requestBody = { content: {} } } = methodObject;
1402
1849
  const { parameters: parameters_ = [] } = methodObject;
1403
1850
  const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
1404
1851
  const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
1405
1852
  const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
1406
- if (Object.keys(responsesClone).length === 0) responsesClone[200] = { description: "Successful response" };
1407
- const httpCodes = Object.keys(responsesClone);
1408
- for (const code of httpCodes) if (code in responsesClone) {
1409
- const response = responsesClone[code];
1853
+ if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
1854
+ const httpCodes = Object.keys(responses);
1855
+ for (const code of httpCodes) if (code in responses) {
1856
+ const response = responses[code];
1410
1857
  const responseSchema = this.getResponseByRef(response);
1411
1858
  methodApis.push({
1412
1859
  method,
@@ -1438,250 +1885,250 @@ var VersionedProvider = class {
1438
1885
  }
1439
1886
  };
1440
1887
  //#endregion
1441
- //#region src/openapi/V2.ts
1442
- var V2 = class extends VersionedProvider {
1888
+ //#region src/openapi/V3_1.ts
1889
+ var V3_1 = class {
1443
1890
  doc;
1444
- version = "v2";
1445
1891
  constructor(doc) {
1446
- super();
1447
1892
  this.doc = doc;
1448
1893
  }
1449
- getSchemaContainer() {
1450
- return this.doc.definitions;
1451
- }
1452
- getParameterContainer() {
1453
- return this.doc.parameters;
1894
+ /**
1895
+ * Resolves a path $ref to the actual path object.
1896
+ */
1897
+ resolvePathRef($ref) {
1898
+ const refName = Base.ref2name($ref, this.doc);
1899
+ return this.doc.paths?.[refName];
1454
1900
  }
1455
- getResponseContainer() {
1456
- return this.doc.responses;
1901
+ /**
1902
+ * Is array schema.
1903
+ */
1904
+ isOpenAPIArraySchema(schema) {
1905
+ return typeof schema === "object" && schema.type === "array";
1457
1906
  }
1458
- getRequestBodyContainer() {}
1459
1907
  /**
1460
- * V2 parameter shape differs from V3: top-level `items`/`properties`/`enum`
1461
- * rather than nested under `schema`. Override accordingly.
1908
+ * OpenAPI schema to base schema.
1462
1909
  */
1463
- getParameterByRef(parameter, enums = [], upLevelSchemaKey = "") {
1464
- if (Base.isRef(parameter)) {
1465
- const refName = Base.ref2name(parameter.$ref, this.doc);
1466
- const resolved = this.doc.parameters?.[refName];
1467
- if (!resolved) throw new Error(`Parameter reference not found: ${parameter.$ref}`);
1468
- parameter = resolved;
1910
+ getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
1911
+ let refName = "";
1912
+ if (Base.isRef(schema)) {
1913
+ refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
1914
+ if (reserveRef) return { type: upLevelSchemaKey + refName };
1915
+ if (!this.doc.components) this.doc.components = { schemas: {} };
1916
+ const resolvedSchema = this.doc.components.schemas?.[Base.ref2name(schema.$ref, this.doc)];
1917
+ if (!resolvedSchema) throw new Error(`Schema reference not found: ${refName}`);
1918
+ schema = resolvedSchema;
1469
1919
  }
1470
- const p = parameter;
1471
- const { name, required, description, type, items, enum: enum_, properties, schema } = p;
1472
- if (enum_) {
1473
- const enumType = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
1920
+ return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
1921
+ }
1922
+ /**
1923
+ * OpenAPI parameter to base parameter.
1924
+ */
1925
+ getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
1926
+ if (Base.isRef(schema)) schema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
1927
+ const { name, required, deprecated, description, schema: parameterSchema } = schema;
1928
+ if (parameterSchema && !Base.isRef(parameterSchema) && parameterSchema.enum) {
1929
+ const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
1474
1930
  const enumSchema = {
1475
- name: enumType,
1476
- enum: [...new Set(enum_)]
1931
+ name: type,
1932
+ enum: [...new Set(parameterSchema.enum)]
1477
1933
  };
1478
1934
  const sameEnum = Base.findSameSchema(enumSchema, enums);
1479
- if (!sameEnum && Base.isValidEnumType({
1480
- type: enumType,
1481
- enum: enum_
1482
- })) enums.push(enumSchema);
1935
+ if (!sameEnum && Base.isValidEnumType(parameterSchema)) enums.push(enumSchema);
1483
1936
  return {
1484
1937
  name,
1485
1938
  required,
1486
1939
  description,
1487
- in: p.in,
1488
- schema: { type: sameEnum?.name ?? enumType }
1940
+ deprecated,
1941
+ in: schema.in,
1942
+ schema: { type: sameEnum?.name ?? type }
1489
1943
  };
1490
1944
  }
1491
- if (items) return {
1492
- name,
1493
- required,
1494
- description,
1495
- in: p.in,
1496
- schema: {
1497
- type,
1498
- items
1499
- }
1500
- };
1501
- if (schema && Base.isRef(schema)) return {
1502
- name,
1503
- required,
1504
- description,
1505
- in: p.in,
1506
- schema: { type: Base.capitalize(Base.ref2name(schema.$ref)) }
1507
- };
1508
1945
  return {
1509
1946
  name,
1510
1947
  required,
1511
1948
  description,
1512
- in: p.in,
1513
- schema: {
1514
- type,
1515
- properties
1516
- }
1949
+ deprecated,
1950
+ in: schema.in,
1951
+ schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
1517
1952
  };
1518
1953
  }
1519
1954
  /**
1520
- * V2 response shape: a `schema` field directly, not `content`. V2 always
1521
- * emits JSON.
1955
+ * OpenAPI schema to base response
1522
1956
  */
1523
1957
  getResponseByRef(schema) {
1524
- if (Base.isRef(schema)) schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
1525
- const { schema: responseSchema } = schema;
1526
- return [{
1527
- type: "application/json",
1528
- schema: responseSchema ? this.getSchemaByRef(responseSchema, true) : void 0
1529
- }];
1958
+ if (Base.isRef(schema)) schema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
1959
+ const { content = {} } = schema;
1960
+ return Object.keys(content).map((c) => ({
1961
+ type: c,
1962
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
1963
+ }));
1964
+ }
1965
+ /**
1966
+ * OpenAPI schema to requestBody.
1967
+ */
1968
+ getRequestBodyByRef(schema, enums = []) {
1969
+ if (Base.isRef(schema)) schema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
1970
+ const { content = {} } = schema;
1971
+ return Object.keys(content).map((c) => ({
1972
+ type: c,
1973
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
1974
+ }));
1530
1975
  }
1531
1976
  /**
1532
- * V2 has no `requestBody` concept; parameters with `in: body` or
1533
- * `in: formData` are split out and turned into a synthetic requestBody
1534
- * here. A single body param named `body` is used directly; otherwise
1535
- * the body / formData params are wrapped in a synthetic object.
1977
+ * Transform all OpenAPI schema to Base Schema
1536
1978
  */
1979
+ toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
1980
+ if (!schema) return { type: "unknown" };
1981
+ if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
1982
+ if (this.isOpenAPIArraySchema(schema)) {
1983
+ const { type, description, items, required } = schema;
1984
+ return {
1985
+ type,
1986
+ required: !!required,
1987
+ description,
1988
+ items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
1989
+ };
1990
+ } else {
1991
+ const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
1992
+ let { type } = schema;
1993
+ if (enum_ && type !== "boolean") {
1994
+ const enumObject = {
1995
+ name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
1996
+ enum: [...new Set(enum_)]
1997
+ };
1998
+ const sameObject = Base.findSameSchema(enumObject, enums);
1999
+ if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
2000
+ return {
2001
+ type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
2002
+ required,
2003
+ description,
2004
+ deprecated
2005
+ };
2006
+ }
2007
+ if (type === void 0 && Object.keys(properties).length > 0) type = "object";
2008
+ return {
2009
+ type,
2010
+ required,
2011
+ description,
2012
+ deprecated,
2013
+ enum: enum_,
2014
+ format,
2015
+ allOf: allOf?.map((s) => Base.isRef(s) ? {
2016
+ ...s,
2017
+ ref: s.$ref,
2018
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
2019
+ } : this.toBaseSchema(s, enums)),
2020
+ anyOf: anyOf?.map((s) => Base.isRef(s) ? {
2021
+ ...s,
2022
+ ref: s.$ref,
2023
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
2024
+ } : this.toBaseSchema(s, enums)),
2025
+ oneOf: oneOf?.map((s) => Base.isRef(s) ? {
2026
+ ...s,
2027
+ ref: s.$ref,
2028
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
2029
+ } : this.toBaseSchema(s, enums)),
2030
+ properties: Object.keys(properties).reduce((acc, p) => {
2031
+ const propSchema = properties[p];
2032
+ return {
2033
+ ...acc,
2034
+ [p]: Base.isRef(propSchema) ? {
2035
+ type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)),
2036
+ isRef: true
2037
+ } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
2038
+ };
2039
+ }, {})
2040
+ };
2041
+ }
2042
+ }
1537
2043
  init() {
1538
- const { paths = {} } = this.doc;
2044
+ const { components = {}, paths = {} } = this.doc;
1539
2045
  const enums = [];
1540
- const schemaContainer = this.getSchemaContainer() ?? {};
1541
- const parameterContainer = this.getParameterContainer() ?? {};
1542
- const responseContainer = this.getResponseContainer() ?? {};
1543
- const schemas_ = Object.keys(schemaContainer).reduce((acc, key) => {
1544
- const schema = schemaContainer[key];
2046
+ const { requestBodies = {}, responses = {}, parameters = {}, schemas = {} } = components;
2047
+ const schemas_ = Object.keys(schemas).reduce((acc, key) => {
2048
+ const schema = schemas[key];
1545
2049
  return {
1546
2050
  ...acc,
1547
2051
  [key]: this.getSchemaByRef(schema, false, enums, key)
1548
2052
  };
1549
2053
  }, {});
1550
- const parameters_ = Object.keys(parameterContainer).reduce((acc, key) => {
1551
- const parameter = parameterContainer[key];
2054
+ const parameters_ = Object.keys(parameters).reduce((acc, key) => {
2055
+ const parameter = parameters[key];
1552
2056
  return {
1553
2057
  ...acc,
1554
2058
  [key]: this.getParameterByRef(parameter, enums, key)
1555
2059
  };
1556
2060
  }, {});
1557
- const responses_ = Object.keys(responseContainer).reduce((acc, key) => {
1558
- const response = responseContainer[key];
2061
+ const responses_ = Object.keys(responses).reduce((acc, key) => {
2062
+ const response = responses[key];
1559
2063
  return {
1560
2064
  ...acc,
1561
2065
  [key]: this.getResponseByRef(response)
1562
2066
  };
1563
2067
  }, {});
1564
- const apis = {};
1565
- for (const path of Object.keys(paths)) {
2068
+ const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
2069
+ const requestBody = requestBodies[key];
2070
+ return {
2071
+ ...acc,
2072
+ [key]: this.getRequestBodyByRef(requestBody, enums)
2073
+ };
2074
+ }, {});
2075
+ const apis = Object.keys(paths).reduce((acc, path) => {
1566
2076
  let pathObject = paths[path] ?? {};
1567
2077
  if (pathObject.$ref) {
1568
2078
  const resolved = this.resolvePathRef(pathObject.$ref);
1569
2079
  if (resolved) pathObject = resolved;
1570
2080
  }
1571
- const { parameters = [] } = pathObject;
2081
+ const { parameters = [], description, summary } = pathObject;
1572
2082
  const methodApis = [];
1573
2083
  Object.values(HttpMethods).forEach((method) => {
1574
2084
  const methodObject = pathObject[method];
1575
- if (!methodObject) return;
1576
- const { deprecated, operationId, summary: summary_, description: description_, responses } = methodObject;
1577
- const { parameters: parameters_ = [] } = methodObject;
1578
- const baseParameters = [...parameters, ...parameters_].map((p) => this.getParameterByRef(p, enums));
1579
- const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
1580
- const responsesClone = responses ? { ...responses } : {};
1581
- if (Object.keys(responsesClone).length === 0) responsesClone[200] = { description: "Successful response" };
1582
- const inBody = baseParameters.filter((p) => p.in === "body" || p.in === "formData");
1583
- const notInBody = baseParameters.filter((p) => p.in !== "body" && p.in !== "formData");
1584
- const httpCodes = Object.keys(responsesClone);
1585
- for (const code of httpCodes) if (code in responsesClone) {
1586
- const response = responsesClone[code];
1587
- const responseSchema = this.getResponseByRef(response);
1588
- const inBodyOnlyHasBody = inBody.length === 1 && inBody[0].in === "body" && inBody[0].name === "body";
1589
- methodApis.push({
1590
- method,
1591
- operationId,
1592
- summary: summary_,
1593
- deprecated,
1594
- description: description_,
1595
- parameters: uniqueParameterName.map((name) => notInBody.find((p) => p.name === name)).filter((p) => p !== void 0),
1596
- responses: responseSchema,
1597
- requestBody: inBody.length > 0 ? inBodyOnlyHasBody ? [{
1598
- type: "application/json",
1599
- schema: inBody[0].schema
1600
- }] : [{
1601
- type: "application/json",
1602
- schema: {
1603
- type: "object",
1604
- properties: inBody.reduce((a, p) => {
1605
- return {
1606
- ...a,
1607
- [p.name]: {
1608
- type: p.schema?.type ?? "unknown",
1609
- required: p.schema?.required,
1610
- items: p.schema?.items,
1611
- description: p.schema?.description
1612
- }
1613
- };
1614
- }, {})
1615
- }
1616
- }] : void 0
1617
- });
1618
- break;
2085
+ if (methodObject) {
2086
+ const { deprecated, operationId, summary: summary_, description: description_, responses = {}, requestBody = { content: {} } } = methodObject;
2087
+ const { parameters: parameters_ = [] } = methodObject;
2088
+ const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
2089
+ const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
2090
+ const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
2091
+ if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
2092
+ const httpCodes = Object.keys(responses);
2093
+ for (const code of httpCodes) if (code in responses) {
2094
+ const response = responses[code];
2095
+ const responseSchema = this.getResponseByRef(response);
2096
+ methodApis.push({
2097
+ method,
2098
+ operationId,
2099
+ summary: summary_ ?? summary,
2100
+ description: description_ ?? description,
2101
+ deprecated,
2102
+ parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
2103
+ responses: responseSchema,
2104
+ requestBody: baseRequestBody
2105
+ });
2106
+ break;
2107
+ }
1619
2108
  }
1620
2109
  });
1621
- apis[path] = methodApis;
1622
- }
2110
+ return {
2111
+ ...acc,
2112
+ [path]: methodApis
2113
+ };
2114
+ }, {});
1623
2115
  return {
1624
2116
  enums: Base.uniqueEnums(enums),
1625
2117
  schemas: schemas_,
1626
2118
  responses: responses_,
1627
2119
  parameters: parameters_,
1628
- requestBodies: {},
2120
+ requestBodies: requestBodies_,
1629
2121
  apis
1630
2122
  };
1631
2123
  }
1632
2124
  };
1633
2125
  //#endregion
1634
- //#region src/openapi/V3.ts
1635
- var V3 = class extends VersionedProvider {
1636
- doc;
1637
- version = "v3";
1638
- constructor(doc) {
1639
- super();
1640
- this.doc = doc;
1641
- }
1642
- getSchemaContainer() {
1643
- return this.doc.components?.schemas;
1644
- }
1645
- getParameterContainer() {
1646
- return this.doc.components?.parameters;
1647
- }
1648
- getResponseContainer() {
1649
- return this.doc.components?.responses;
1650
- }
1651
- getRequestBodyContainer() {
1652
- return this.doc.components?.requestBodies;
1653
- }
1654
- };
1655
- //#endregion
1656
- //#region src/openapi/V3_1.ts
1657
- var V3_1 = class extends VersionedProvider {
1658
- doc;
1659
- version = "v3_1";
1660
- constructor(doc) {
1661
- super();
1662
- this.doc = doc;
1663
- }
1664
- formatRefName(name) {
1665
- return Base.upperCamelCase(name);
1666
- }
1667
- getSchemaContainer() {
1668
- return this.doc.components?.schemas;
1669
- }
1670
- getParameterContainer() {
1671
- return this.doc.components?.parameters;
1672
- }
1673
- getResponseContainer() {
1674
- return this.doc.components?.responses;
1675
- }
1676
- getRequestBodyContainer() {
1677
- return this.doc.components?.requestBodies;
1678
- }
1679
- };
1680
- //#endregion
1681
2126
  //#region src/openapi/index.ts
1682
- const logger = createScopedLogger("OpenAPI");
2127
+ const logger$1 = createScopedLogger("OpenAPI");
1683
2128
  function getDocVersion(doc) {
1684
- switch ((doc.openapi || doc.swagger).slice(0, 3)) {
2129
+ const raw = doc.openapi || doc.swagger;
2130
+ if (typeof raw !== "string" || raw.length === 0) return "unknown";
2131
+ switch (raw.slice(0, 3)) {
1685
2132
  case "3.1": return "v3_1";
1686
2133
  case "3.0": return "v3";
1687
2134
  case "2.0": return "v2";
@@ -1691,7 +2138,7 @@ function getDocVersion(doc) {
1691
2138
  var OpenAPIProvider = class extends Provider {
1692
2139
  parse(doc) {
1693
2140
  const version = getDocVersion(doc);
1694
- logger.debug(`openapi version ${version}`);
2141
+ logger$1.debug(`openapi version ${version}`);
1695
2142
  switch (version) {
1696
2143
  case "v2": return new V2(doc).init();
1697
2144
  case "v3": return new V3(doc).init();
@@ -1709,10 +2156,24 @@ function getAdaptor(type) {
1709
2156
  async function codeGen(initOptions) {
1710
2157
  const startTime = Date.now();
1711
2158
  const { verbose } = initOptions;
1712
- if (verbose) logger.setLevel("debug");
1713
- else logger.setLevel("info");
1714
- logger.info(`Fetch document from ${initOptions.docURL}`);
1715
- const { enums, schemas, parameters, responses, requestBodies, apis } = new OpenAPIProvider(initOptions, await Base.fetchDoc(initOptions.docURL, initOptions.requestOptions));
2159
+ if (verbose) logger$1.setLevel("debug");
2160
+ else logger$1.setLevel("info");
2161
+ logger$1.info(`Fetch document from ${initOptions.docURL}`);
2162
+ const { transport, source } = Base.resolveSpecURL(initOptions.docURL);
2163
+ const { enums, schemas, parameters, responses, requestBodies, apis } = new OpenAPIProvider(initOptions, transport === "file" ? await (async () => {
2164
+ let raw;
2165
+ try {
2166
+ raw = await readFile(source, "utf8");
2167
+ } catch (error) {
2168
+ if (error?.code === "ENOENT") throw createErrors.specNotFound(source, error);
2169
+ throw new Error(`Failed to read OpenAPI spec from ${source}: ${error instanceof Error ? error.message : String(error)}`);
2170
+ }
2171
+ try {
2172
+ return JSON.parse(raw);
2173
+ } catch (error) {
2174
+ throw createErrors.specParseFailed(source, void 0, void 0, error);
2175
+ }
2176
+ })() : await Base.fetchDoc(source, initOptions.requestOptions));
1716
2177
  const adaptor = getAdaptor(initOptions.adaptor ?? "fetch");
1717
2178
  const code = await Generator.genCode({
1718
2179
  enums,
@@ -1734,61 +2195,95 @@ async function codeGen(initOptions) {
1734
2195
  };
1735
2196
  }
1736
2197
  //#endregion
1737
- //#region src/vite-plugin/index.ts
1738
- const PLUGIN_NAME = "api-code-gen";
1739
- const pluginLogger = createScopedLogger("api-code-gen");
2198
+ //#region src/vite-plugin/cache.ts
1740
2199
  /**
1741
- * Find the nearest tsconfig.json or jsconfig.json by searching upward.
1742
- * Bounded by process.cwd() — the Vite project root — to avoid picking up
1743
- * unrelated configs outside the project.
2200
+ * Cache for a single vite-plugin codegen run. Lives only for the duration
2201
+ * of one plugin invocation — there is no module-level state.
2202
+ *
2203
+ * Cache files are stored at:
2204
+ *
2205
+ * <cacheDir>/<optionsHash>.json
2206
+ *
2207
+ * where `<cacheDir>` defaults to `node_modules/.cache/apicodegen` but can
2208
+ * be overridden via `cacheDir`.
1744
2209
  */
1745
- async function findNearestTsConfig(filePath) {
1746
- let dir = path.dirname(path.resolve(filePath));
1747
- const rootDir = process.cwd();
1748
- const fsRoot = path.parse(dir).root;
1749
- while (true) {
1750
- for (const name of ["tsconfig.json", "jsconfig.json"]) {
1751
- const configPath = path.join(dir, name);
1752
- if (await fs.pathExists(configPath)) return configPath;
2210
+ var CodegenCache = class CodegenCache {
2211
+ cacheDir;
2212
+ constructor(cacheDir) {
2213
+ this.cacheDir = cacheDir;
2214
+ }
2215
+ /** Hash the options that affect generated output (excluding the spec). */
2216
+ static hashOptions(options) {
2217
+ const payload = Object.keys(options).sort().filter((k) => k !== "verbose" && k !== "typeCheck" && k !== "cache").map((k) => `${k}=${JSON.stringify(options[k])}`).join("|");
2218
+ return createHash("sha256").update(payload).digest("hex").slice(0, 16);
2219
+ }
2220
+ /** Hash the raw spec content so unrelated edits are detected. */
2221
+ static hashContent(content) {
2222
+ return createHash("sha256").update(content).digest("hex").slice(0, 16);
2223
+ }
2224
+ /**
2225
+ * Look up a cached entry. Returns `null` on miss / corruption / disabled.
2226
+ *
2227
+ * @param optionsHash Options hash from `hashOptions`.
2228
+ * @param specSource Resolved spec path or URL. Local paths use mtime +
2229
+ * content hash; URLs always miss (no cache).
2230
+ */
2231
+ async lookup(optionsHash, specSource) {
2232
+ const cachePath = path.join(this.cacheDir, `${optionsHash}.json`);
2233
+ let raw;
2234
+ try {
2235
+ raw = await readFile(cachePath, "utf8");
2236
+ } catch {
2237
+ return null;
2238
+ }
2239
+ let entry;
2240
+ try {
2241
+ entry = JSON.parse(raw);
2242
+ } catch {
2243
+ return null;
2244
+ }
2245
+ if (entry.optionsHash !== optionsHash) return null;
2246
+ if (specSource.startsWith("http://") || specSource.startsWith("https://")) return null;
2247
+ let currentMtimeMs;
2248
+ try {
2249
+ currentMtimeMs = (await stat(specSource)).mtimeMs;
2250
+ } catch {
2251
+ return null;
2252
+ }
2253
+ if (currentMtimeMs !== entry.specMtimeMs) return null;
2254
+ if (entry.specContentHash) {
2255
+ let content;
2256
+ try {
2257
+ content = await readFile(specSource, "utf8");
2258
+ } catch {
2259
+ return null;
2260
+ }
2261
+ if (CodegenCache.hashContent(content) !== entry.specContentHash) return null;
1753
2262
  }
1754
- if (dir === rootDir || dir === fsRoot) break;
1755
- dir = path.dirname(dir);
2263
+ return entry;
1756
2264
  }
1757
- return null;
1758
- }
2265
+ /** Persist a successful codegen result. */
2266
+ async store(entry) {
2267
+ const cachePath = path.join(this.cacheDir, `${entry.optionsHash}.json`);
2268
+ const dir = path.dirname(cachePath);
2269
+ await import("fs-extra").then((fs) => fs.ensureDir(dir));
2270
+ await writeFile(cachePath, JSON.stringify(entry));
2271
+ }
2272
+ };
2273
+ //#endregion
2274
+ //#region src/vite-plugin/index.ts
2275
+ const PLUGIN_NAME = "api-code-gen";
2276
+ const logger = createScopedLogger("api-code-gen");
1759
2277
  /**
1760
2278
  * Run TypeScript type checking on generated file
1761
2279
  */
1762
2280
  async function runTypeCheck(filePath) {
1763
2281
  const { execaCommand } = await import("execa");
1764
2282
  const errors = [];
1765
- const resolvedPath = path.resolve(filePath);
1766
- const tsconfigPath = await findNearestTsConfig(resolvedPath);
1767
- if (!tsconfigPath) {
1768
- try {
1769
- await execaCommand(`npx tsc ${resolvedPath} --noEmit`, { shell: true });
1770
- } catch (error) {
1771
- if (error instanceof Error) errors.push(error.message);
1772
- }
1773
- return errors;
1774
- }
1775
- const outputDir = path.dirname(resolvedPath);
1776
- const tempConfigName = `.${path.basename(resolvedPath).replace(/\.ts$/i, "")}.${Date.now()}.apicodegen.json`;
1777
- const tempConfigPath = path.join(outputDir, tempConfigName);
1778
- const tempConfig = {
1779
- extends: path.relative(outputDir, tsconfigPath),
1780
- compilerOptions: { noEmit: true },
1781
- include: [path.basename(resolvedPath)]
1782
- };
1783
2283
  try {
1784
- await fs.writeJson(tempConfigPath, tempConfig);
1785
- await execaCommand(`npx tsc --project "${tempConfigPath}" --noEmit`, { shell: true });
2284
+ await execaCommand(`npx tsc ${filePath} --noEmit`, { shell: true });
1786
2285
  } catch (error) {
1787
2286
  if (error instanceof Error) errors.push(error.message);
1788
- } finally {
1789
- try {
1790
- await fs.remove(tempConfigPath);
1791
- } catch {}
1792
2287
  }
1793
2288
  return errors;
1794
2289
  }
@@ -1805,9 +2300,9 @@ async function validateSpecPath(specPath) {
1805
2300
  * Generate code for a single API configuration
1806
2301
  */
1807
2302
  async function generateForOption(option) {
1808
- const { name, typeCheck = true, verbose, ...restOptions } = option;
2303
+ const { name, typeCheck = true, verbose, cache = true, cacheDir, ...restOptions } = option;
1809
2304
  try {
1810
- logger$1.info(`Generating ${name}...`);
2305
+ console.log(`\x1b[36m├─\x1b[0m ${name}`);
1811
2306
  const config = await loadConfig({
1812
2307
  name,
1813
2308
  cliOptions: {
@@ -1821,25 +2316,69 @@ async function generateForOption(option) {
1821
2316
  await fs.ensureDir(outputDir);
1822
2317
  }
1823
2318
  let docURL = config.spec;
1824
- if (!docURL.startsWith("http://") && !docURL.startsWith("https://")) if (docURL.startsWith("/") || docURL.match(/^[A-Za-z]:/)) docURL = `file://${docURL}`;
1825
- else docURL = path.resolve(process.cwd(), docURL);
1826
- const result = await codeGen({
1827
- ...toProviderOptions(config),
1828
- docURL
2319
+ if (!docURL.startsWith("http://") && !docURL.startsWith("https://") && !docURL.startsWith("file://") && !docURL.startsWith("/") && !/^[A-Za-z]:[\\/]/.test(docURL)) docURL = path.resolve(process.cwd(), docURL);
2320
+ const resolvedCacheDir = cacheDir ?? path.join(process.cwd(), "node_modules", ".cache", "apicodegen");
2321
+ const codegenCache = cache ? new CodegenCache(resolvedCacheDir) : null;
2322
+ const optionsHash = CodegenCache.hashOptions({
2323
+ name,
2324
+ spec: docURL,
2325
+ output: config.output,
2326
+ adaptor: config.adaptor,
2327
+ baseURL: config.baseURL,
2328
+ importClientSource: config.importClientSource
1829
2329
  });
2330
+ let result = null;
2331
+ let cached = false;
2332
+ if (codegenCache) {
2333
+ const cachedEntry = await codegenCache.lookup(optionsHash, docURL);
2334
+ if (cachedEntry) {
2335
+ result = {
2336
+ code: cachedEntry.code,
2337
+ stats: cachedEntry.stats
2338
+ };
2339
+ cached = true;
2340
+ if (verbose) logger.debug(`Cache hit for ${name} (${optionsHash})`);
2341
+ }
2342
+ }
2343
+ if (!result) {
2344
+ result = await codeGen({
2345
+ ...toProviderOptions(config),
2346
+ docURL
2347
+ });
2348
+ if (codegenCache) try {
2349
+ const fsPromises = await import("node:fs/promises");
2350
+ let specMtimeMs;
2351
+ let specContentHash;
2352
+ if (!(docURL.startsWith("http://") || docURL.startsWith("https://"))) try {
2353
+ specMtimeMs = (await fsPromises.stat(docURL)).mtimeMs;
2354
+ const content = await fsPromises.readFile(docURL, "utf8");
2355
+ specContentHash = CodegenCache.hashContent(content);
2356
+ } catch {}
2357
+ await codegenCache.store({
2358
+ optionsHash,
2359
+ specMtimeMs,
2360
+ specContentHash,
2361
+ code: result.code,
2362
+ stats: result.stats
2363
+ });
2364
+ } catch (cacheError) {
2365
+ if (verbose) logger.warn(`Cache write failed for ${name}: ${cacheError.message}`);
2366
+ }
2367
+ }
1830
2368
  if (config.output) await fs.writeFile(config.output, result.code);
1831
2369
  if (typeCheck && config.output) {
1832
2370
  const typeErrors = await runTypeCheck(config.output);
1833
2371
  if (typeErrors.length > 0) {
1834
- pluginLogger.warn(`Type check failed for ${config.output}`);
1835
- if (verbose) for (const error of typeErrors) pluginLogger.warn(` ${error}`);
2372
+ logger.warn(`Type check failed for ${config.output}`);
2373
+ if (verbose) for (const error of typeErrors) logger.warn(` ${error}`);
1836
2374
  }
1837
2375
  }
1838
2376
  return {
1839
2377
  success: true,
1840
2378
  name,
1841
2379
  output: config.output,
1842
- stats: result.stats
2380
+ stats: result.stats,
2381
+ cached
1843
2382
  };
1844
2383
  } catch (error) {
1845
2384
  return {
@@ -1873,47 +2412,47 @@ async function generateForOption(option) {
1873
2412
  */
1874
2413
  function apiCodeGenPlugin(options) {
1875
2414
  if (!Array.isArray(options) || options.length === 0) {
1876
- pluginLogger.warn("No API configurations provided to apiCodeGenPlugin");
2415
+ logger.warn("No API configurations provided to apiCodeGenPlugin");
1877
2416
  return { name: PLUGIN_NAME };
1878
2417
  }
1879
2418
  return {
1880
2419
  name: PLUGIN_NAME,
1881
2420
  async config(_config, env) {
1882
- logger$1.heading("API Code Gen", env?.command);
2421
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
2422
+ console.log(`\x1b[1m\x1b[36mAPI Code Gen\x1b[0m`);
2423
+ console.log(`\x1b[90mMode:\x1b[0m ${env?.command || "unknown"}`);
2424
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
1883
2425
  const results = await Promise.all(options.map(generateForOption));
1884
2426
  const successCount = results.filter((r) => r.success).length;
1885
2427
  const failCount = options.length - successCount;
1886
- logger$1.divider();
2428
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
1887
2429
  for (const result of results) if (result.success) {
1888
- const { name, output, stats } = result;
1889
- if (stats) logger$1.item(`${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms`, "green");
1890
- else logger$1.item(`${name} → ${output || "N/A"}`, "green");
2430
+ const { name, output, stats, cached } = result;
2431
+ if (stats) {
2432
+ const cachedTag = cached ? " \x1B[90m[cached]\x1B[0m" : "";
2433
+ console.log(`\x1b[32m✓\x1b[0m ${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms${cachedTag}`);
2434
+ } else console.log(`\x1b[32m✓\x1b[0m ${name} → ${output || "N/A"}`);
1891
2435
  } else {
1892
2436
  const { name, error } = result;
1893
2437
  if (isApicodegenError(error)) {
1894
- logger$1.item(name, "red");
1895
- logger$1.error(error, true);
2438
+ console.log(`\x1b[31m✗\x1b[0m ${name}`);
2439
+ console.log(`\x1b[90m${formatError(error, true)}\x1b[0m`);
1896
2440
  } else {
1897
2441
  const wrapped = wrapError(error, {
1898
- code: ErrorCodes.GENERATION_FAILED,
2442
+ code: "E_GENERATION_FAILED",
1899
2443
  message: `Failed to generate API "${name}"`
1900
2444
  });
1901
- logger$1.item(name, "red");
1902
- logger$1.error(wrapped, true);
2445
+ console.log(`\x1b[31m✗\x1b[0m ${name}`);
2446
+ console.log(`\x1b[90m${formatError(wrapped, true)}\x1b[0m`);
1903
2447
  }
1904
2448
  }
1905
- logger$1.divider();
2449
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
1906
2450
  const totalDuration = results.reduce((sum, r) => sum + (r.stats?.duration || 0), 0);
1907
2451
  const totalEndpoints = results.reduce((sum, r) => sum + (r.stats?.endpoints || 0), 0);
1908
2452
  const totalSchemas = results.reduce((sum, r) => sum + (r.stats?.schemas || 0), 0);
1909
- logger$1.summary({
1910
- succeeded: successCount,
1911
- failed: failCount,
1912
- endpoints: totalEndpoints,
1913
- schemas: totalSchemas,
1914
- duration: totalDuration
1915
- });
1916
- logger$1.divider();
2453
+ if (failCount === 0) console.log(`\x1b[32m✓\x1b[0m API Code Gen - Complete (\x1b[90m${successCount}/${options.length} succeeded\x1b[0m, ${totalEndpoints} endpoints, ${totalSchemas} schemas, ${totalDuration}ms\x1b[0m)`);
2454
+ else console.log(`\x1b[33m⚠\x1b[0m API Code Gen - Complete (\x1b[90m${successCount} succeeded, ${failCount} failed\x1b[0m, ${totalEndpoints} endpoints, ${totalSchemas} schemas, ${totalDuration}ms\x1b[0m)`);
2455
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
1917
2456
  return {};
1918
2457
  }
1919
2458
  };