@kubb/adapter-oas 5.26.0 → 5.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -18,7 +18,7 @@ var compatibility = {
18
18
  "node": ">=22.22"
19
19
  };
20
20
  // package.json
21
- var version = "5.26.0";
21
+ var version = "5.27.1";
22
22
  // src/constants.ts
23
23
  /**
24
24
  * Default parser options applied when no explicit options are provided.
@@ -242,29 +242,44 @@ function memo(store, key, compute) {
242
242
  store.set(key, value);
243
243
  return value;
244
244
  }
245
+ var BoundedStore = class {
246
+ #entry = /* @__PURE__ */ new Map();
247
+ #max;
248
+ constructor(max) {
249
+ this.#max = max;
250
+ }
251
+ has(key) {
252
+ return this.#entry.has(key);
253
+ }
254
+ get(key) {
255
+ return this.#entry.get(key);
256
+ }
257
+ set(key, value) {
258
+ if (this.#entry.size >= this.#max) this.#entry.clear();
259
+ this.#entry.set(key, value);
260
+ }
261
+ };
262
+ var LastEntryStore = class extends BoundedStore {
263
+ constructor() {
264
+ super(1);
265
+ }
266
+ #touch(key) {
267
+ if (!super.has(key)) return false;
268
+ this.set(key, super.get(key));
269
+ return true;
270
+ }
271
+ has(key) {
272
+ return this.#touch(key);
273
+ }
274
+ get(key) {
275
+ return this.#touch(key) ? super.get(key) : void 0;
276
+ }
277
+ };
245
278
  function createStore({ weak, max } = {}) {
246
279
  if (weak) return /* @__PURE__ */ new WeakMap();
247
- const entry = /* @__PURE__ */ new Map();
248
- if (max === void 0) return entry;
249
- const set = (key, value) => {
250
- if (entry.size >= max) entry.clear();
251
- entry.set(key, value);
252
- };
253
- if (max !== 1) return {
254
- has: (key) => entry.has(key),
255
- get: (key) => entry.get(key),
256
- set
257
- };
258
- const touch = (key) => {
259
- if (!entry.has(key)) return false;
260
- set(key, entry.get(key));
261
- return true;
262
- };
263
- return {
264
- has: touch,
265
- get: (key) => touch(key) ? entry.get(key) : void 0,
266
- set
267
- };
280
+ if (max === void 0) return /* @__PURE__ */ new Map();
281
+ if (max !== 1) return new BoundedStore(max);
282
+ return new LastEntryStore();
268
283
  }
269
284
  memo.create = createStore;
270
285
  // ../../internals/utils/src/errors.ts
@@ -531,7 +546,8 @@ function isJsonMimeType(mimeType) {
531
546
  }
532
547
  // src/refs.ts
533
548
  /**
534
- * Creates the `$ref` resolution service for one document. One pointer walk backs every method.
549
+ * The `$ref` service bound to one document: pointer resolution and resolved-node parsing, each
550
+ * with its own instance-scoped memoization.
535
551
  *
536
552
  * @example
537
553
  * ```ts
@@ -543,28 +559,32 @@ function isJsonMimeType(mimeType) {
543
559
  * refs.derefKeepingRef(parameter)
544
560
  * ```
545
561
  */
546
- function createRefs(document) {
547
- const pointerCache = /* @__PURE__ */ new Map();
548
- const resolvedNodeCache = memo.create();
549
- const resolvingRefs = /* @__PURE__ */ new Set();
550
- function walkPointer($ref) {
562
+ var Refs = class {
563
+ #document;
564
+ #pointerCache = /* @__PURE__ */ new Map();
565
+ #resolvedNodeCache = memo.create();
566
+ #resolvingRefs = /* @__PURE__ */ new Set();
567
+ constructor(document) {
568
+ this.#document = document;
569
+ }
570
+ #walkPointer($ref) {
551
571
  const trimmed = $ref.trim();
552
572
  if (trimmed === "" || !trimmed.startsWith("#")) return {
553
573
  applicable: false,
554
574
  value: null
555
575
  };
556
576
  const pointer = trimmed.substring(1);
557
- if (pointerCache.has(pointer)) return {
577
+ if (this.#pointerCache.has(pointer)) return {
558
578
  applicable: true,
559
- value: pointerCache.get(pointer)
579
+ value: this.#pointerCache.get(pointer)
560
580
  };
561
581
  let current;
562
582
  try {
563
- current = pointer.split("/").filter(Boolean).map((token) => unescapePointerToken(globalThis.decodeURIComponent(token))).reduce((obj, key) => obj != null && Object.hasOwn(obj, key) ? obj[key] : void 0, document);
583
+ current = pointer.split("/").filter(Boolean).map((token) => unescapePointerToken(globalThis.decodeURIComponent(token))).reduce((obj, key) => obj != null && Object.hasOwn(obj, key) ? obj[key] : void 0, this.#document);
564
584
  } catch {
565
585
  current = void 0;
566
586
  }
567
- if (current) pointerCache.set(pointer, current);
587
+ if (current) this.#pointerCache.set(pointer, current);
568
588
  return {
569
589
  applicable: true,
570
590
  value: current ?? null
@@ -576,8 +596,8 @@ function createRefs(document) {
576
596
  * outside one) when the pointer cannot be resolved. `report: false` resolves to `null` silently,
577
597
  * for a speculative lookup where a missing ref is not an error.
578
598
  */
579
- function resolve(refPath, options) {
580
- const { applicable, value } = walkPointer(refPath);
599
+ resolve(refPath, options) {
600
+ const { applicable, value } = this.#walkPointer(refPath);
581
601
  if (!applicable || value || options?.report === false) return value;
582
602
  const diagnostic = {
583
603
  code: _kubb_kit.Diagnostics.code.refNotFound,
@@ -599,22 +619,22 @@ function createRefs(document) {
599
619
  * resolved (e.g. a minimal document in a unit test). An error from `parse` is thrown, so a bug
600
620
  * in a converter is not mistaken for a missing ref.
601
621
  */
602
- function resolveNode(refPath, parse) {
603
- if (resolvingRefs.has(refPath)) return null;
604
- return memo(resolvedNodeCache, refPath, () => {
622
+ resolveNode(refPath, parse) {
623
+ if (this.#resolvingRefs.has(refPath)) return null;
624
+ return memo(this.#resolvedNodeCache, refPath, () => {
605
625
  let referenced;
606
626
  try {
607
- referenced = resolve(refPath);
627
+ referenced = this.resolve(refPath);
608
628
  } catch (error) {
609
629
  if (_kubb_kit.Diagnostics.isError(error) && error.diagnostic.code === _kubb_kit.Diagnostics.code.refNotFound) return null;
610
630
  throw error;
611
631
  }
612
632
  if (!referenced) return null;
613
- resolvingRefs.add(refPath);
633
+ this.#resolvingRefs.add(refPath);
614
634
  try {
615
635
  return parse({ schema: referenced });
616
636
  } finally {
617
- resolvingRefs.delete(refPath);
637
+ this.#resolvingRefs.delete(refPath);
618
638
  }
619
639
  });
620
640
  }
@@ -624,26 +644,28 @@ function createRefs(document) {
624
644
  * `$ref` after resolving (e.g. a document with no component registry). A non-`$ref` value is
625
645
  * returned as-is.
626
646
  */
627
- function deref(value) {
647
+ deref(value) {
628
648
  if (!isReference(value)) return value ? value : null;
629
- const resolved = resolve(value.$ref);
649
+ const resolved = this.resolve(value.$ref);
630
650
  return resolved && !isReference(resolved) ? resolved : null;
631
651
  }
632
- /** Resolves a `$ref` object but keeps the `$ref` field on the result; other values pass through. */
633
- function derefKeepingRef(value) {
652
+ /**
653
+ * Resolves a `$ref` object but keeps the `$ref` field on the result; other values pass through.
654
+ */
655
+ derefKeepingRef(value) {
634
656
  if (isReference(value)) return {
635
657
  ...value,
636
- ...resolve(value.$ref),
658
+ ...this.resolve(value.$ref),
637
659
  $ref: value.$ref
638
660
  };
639
661
  return value;
640
662
  }
641
- return {
642
- resolve,
643
- resolveNode,
644
- deref,
645
- derefKeepingRef
646
- };
663
+ };
664
+ /**
665
+ * Creates the `$ref` resolution service for one document. One pointer walk backs every method.
666
+ */
667
+ function createRefs(document) {
668
+ return new Refs(document);
647
669
  }
648
670
  // src/load/schemaIds.ts
649
671
  const DATA_KEYS = /* @__PURE__ */ new Set([
@@ -784,11 +806,69 @@ function indexEvents(events) {
784
806
  collections: /* @__PURE__ */ new Map()
785
807
  };
786
808
  }
787
- function createLocator({ index, source }) {
788
- const { types, styles, starts, ends, collections } = index;
789
- const isCollection = (at) => types[at] === js_yaml.EVENT_ID.MAPPING || types[at] === js_yaml.EVENT_ID.SEQUENCE;
790
- const readText = (at) => {
791
- const text = source.slice(starts[at], ends[at]);
809
+ var SourceLocator = class {
810
+ #index;
811
+ #source;
812
+ #types;
813
+ #styles;
814
+ #starts;
815
+ #ends;
816
+ constructor({ index, source }) {
817
+ this.#index = index;
818
+ this.#source = source;
819
+ this.#types = index.types;
820
+ this.#styles = index.styles;
821
+ this.#starts = index.starts;
822
+ this.#ends = index.ends;
823
+ }
824
+ find(pointer) {
825
+ return this.#walk({
826
+ at: 1,
827
+ tokens: pointer.replace(/^#/, "").split("/").slice(1).map(unescapePointerToken),
828
+ range: void 0
829
+ });
830
+ }
831
+ findRef(ref) {
832
+ this.#index.refs ??= this.#indexRefs();
833
+ return this.#index.refs.get(ref);
834
+ }
835
+ #indexRefs() {
836
+ const types = this.#types;
837
+ const refs = /* @__PURE__ */ new Map();
838
+ const frames = [];
839
+ for (let at = 1; at + 1 < types.length; at++) {
840
+ if (!this.#stepFrames({
841
+ frames,
842
+ at
843
+ }) || !this.#isRefKey(at)) continue;
844
+ const text = this.#readText(at + 1);
845
+ if (!refs.has(text)) refs.set(text, {
846
+ start: this.#starts[at + 1],
847
+ end: this.#ends[at + 1]
848
+ });
849
+ }
850
+ return refs;
851
+ }
852
+ #stepFrames({ frames, at }) {
853
+ if (this.#types[at] === js_yaml.EVENT_ID.POP) {
854
+ frames.pop();
855
+ return false;
856
+ }
857
+ const top = frames.length - 1;
858
+ const isKey = frames[top] === 0;
859
+ if (frames[top] >= 0) frames[top] = 1 - frames[top];
860
+ if (this.#isCollection(at)) frames.push(this.#types[at] === js_yaml.EVENT_ID.MAPPING ? 0 : -1);
861
+ return isKey;
862
+ }
863
+ #isRefKey(at) {
864
+ return this.#types[at] === js_yaml.EVENT_ID.SCALAR && this.#types[at + 1] === js_yaml.EVENT_ID.SCALAR && this.#readText(at) === "$ref";
865
+ }
866
+ #isCollection(at) {
867
+ return this.#types[at] === js_yaml.EVENT_ID.MAPPING || this.#types[at] === js_yaml.EVENT_ID.SEQUENCE;
868
+ }
869
+ #readText(at) {
870
+ const styles = this.#styles;
871
+ const text = this.#source.slice(this.#starts[at], this.#ends[at]);
792
872
  if (styles[at] === js_yaml.SCALAR_STYLE.SINGLE_QUOTED) return text.slice(1, -1).replaceAll("''", "'");
793
873
  if (styles[at] !== js_yaml.SCALAR_STYLE.DOUBLE_QUOTED) return text;
794
874
  try {
@@ -796,19 +876,20 @@ function createLocator({ index, source }) {
796
876
  } catch {
797
877
  return String((0, js_yaml.load)(text, { schema: js_yaml.CORE_SCHEMA }));
798
878
  }
799
- };
800
- const readNode = (at) => {
801
- if (!isCollection(at)) return {
879
+ }
880
+ #readNode(at) {
881
+ const starts = this.#starts;
882
+ if (!this.#isCollection(at)) return {
802
883
  start: starts[at],
803
- end: ends[at],
884
+ end: this.#ends[at],
804
885
  next: at + 1
805
886
  };
806
887
  let next = at + 1;
807
888
  let end = starts[at];
808
- while (types[next] !== js_yaml.EVENT_ID.POP) ({end, next} = readNode(next));
809
- if (styles[at] === js_yaml.COLLECTION_STYLE.FLOW) {
889
+ while (this.#types[next] !== js_yaml.EVENT_ID.POP) ({end, next} = this.#readNode(next));
890
+ if (this.#styles[at] === js_yaml.COLLECTION_STYLE.FLOW) {
810
891
  flowGap.lastIndex = end;
811
- flowGap.exec(source);
892
+ flowGap.exec(this.#source);
812
893
  end = flowGap.lastIndex + 1;
813
894
  }
814
895
  return {
@@ -816,15 +897,16 @@ function createLocator({ index, source }) {
816
897
  end,
817
898
  next: next + 1
818
899
  };
819
- };
820
- const readChildren = (collection) => {
900
+ }
901
+ #readChildren(collection) {
902
+ const types = this.#types;
821
903
  const keys = /* @__PURE__ */ new Map();
822
904
  const items = [];
823
905
  const isMapping = types[collection] === js_yaml.EVENT_ID.MAPPING;
824
906
  for (let at = collection + 1; types[at] !== js_yaml.EVENT_ID.POP;) {
825
907
  const key = isMapping ? at : void 0;
826
- if (key !== void 0) at = readNode(at).next;
827
- const { start, end, next } = readNode(at);
908
+ if (key !== void 0) at = this.#readNode(at).next;
909
+ const { start, end, next } = this.#readNode(at);
828
910
  if (key === void 0) items.push({
829
911
  index: at,
830
912
  range: {
@@ -832,13 +914,12 @@ function createLocator({ index, source }) {
832
914
  end
833
915
  }
834
916
  });
835
- const raw = key !== void 0 && types[key] === js_yaml.EVENT_ID.SCALAR ? readText(key) : void 0;
836
- const text = raw !== void 0 && styles[key] === js_yaml.SCALAR_STYLE.PLAIN ? toKeyText(raw) : raw;
917
+ const text = key !== void 0 ? this.#readKey(key) : void 0;
837
918
  if (text !== void 0 && !keys.has(text)) keys.set(text, {
838
919
  index: at,
839
920
  range: {
840
- start: starts[key],
841
- end: ends[key]
921
+ start: this.#starts[key],
922
+ end: this.#ends[key]
842
923
  }
843
924
  });
844
925
  at = next;
@@ -847,50 +928,26 @@ function createLocator({ index, source }) {
847
928
  keys,
848
929
  items
849
930
  };
850
- };
851
- const walk = ({ at, tokens: [token, ...rest], range }) => {
931
+ }
932
+ #readKey(key) {
933
+ if (this.#types[key] !== js_yaml.EVENT_ID.SCALAR) return void 0;
934
+ const raw = this.#readText(key);
935
+ return this.#styles[key] === js_yaml.SCALAR_STYLE.PLAIN ? toKeyText(raw) : raw;
936
+ }
937
+ #walk({ at, tokens: [token, ...rest], range }) {
852
938
  if (token === void 0) return range;
853
- if (!isCollection(at)) return void 0;
854
- const { keys, items } = memo(collections, at, () => readChildren(at));
939
+ if (!this.#isCollection(at)) return void 0;
940
+ const { keys, items } = memo(this.#index.collections, at, () => this.#readChildren(at));
855
941
  const child = keys.get(token) ?? items[Number(token)];
856
- return child ? walk({
942
+ return child ? this.#walk({
857
943
  at: child.index,
858
944
  tokens: rest,
859
945
  range: child.range
860
946
  }) : void 0;
861
- };
862
- return {
863
- find(pointer) {
864
- return walk({
865
- at: 1,
866
- tokens: pointer.replace(/^#/, "").split("/").slice(1).map(unescapePointerToken),
867
- range: void 0
868
- });
869
- },
870
- findRef(ref) {
871
- if (!index.refs) {
872
- index.refs = /* @__PURE__ */ new Map();
873
- const frames = [];
874
- for (let at = 1; at + 1 < types.length; at++) {
875
- if (types[at] === js_yaml.EVENT_ID.POP) {
876
- frames.pop();
877
- continue;
878
- }
879
- const top = frames.length - 1;
880
- const isKey = frames[top] === 0;
881
- if (frames[top] >= 0) frames[top] = 1 - frames[top];
882
- if (isCollection(at)) frames.push(types[at] === js_yaml.EVENT_ID.MAPPING ? 0 : -1);
883
- if (!isKey || types[at] !== js_yaml.EVENT_ID.SCALAR || types[at + 1] !== js_yaml.EVENT_ID.SCALAR || readText(at) !== "$ref") continue;
884
- const text = readText(at + 1);
885
- if (!index.refs.has(text)) index.refs.set(text, {
886
- start: starts[at + 1],
887
- end: ends[at + 1]
888
- });
889
- }
890
- }
891
- return index.refs.get(ref);
892
- }
893
- };
947
+ }
948
+ };
949
+ function createSourceLocator(options) {
950
+ return new SourceLocator(options);
894
951
  }
895
952
  function parse$1(source) {
896
953
  try {
@@ -910,12 +967,12 @@ const locate = (source, location) => {
910
967
  if (!("pointer" in location)) return void 0;
911
968
  const index = memo(indexes, source, () => parse$1(source));
912
969
  if (!index) return void 0;
913
- const { find, findRef } = createLocator({
970
+ const locator = createSourceLocator({
914
971
  index,
915
972
  source
916
973
  });
917
974
  const ref = "ref" in location ? location.ref : void 0;
918
- return find(location.pointer) ?? (ref ? findRef(ref) : void 0);
975
+ return locator.find(location.pointer) ?? (ref ? locator.findRef(ref) : void 0);
919
976
  };
920
977
  // src/load/source.ts
921
978
  const urlRegExp = /^https?:\/+/i;
@@ -1383,6 +1440,7 @@ function reportValidationErrors({ errors, additionalErrors }) {
1383
1440
  for (const { message } of errors) reportInvalidSpec(message.replace(/\n.*/s, ""));
1384
1441
  if (additionalErrors > 0) reportInvalidSpec(`${additionalErrors} more validation errors are not listed.`);
1385
1442
  }
1443
+ const VALIDATION_WORKER_LIMITS = { maxYoungGenerationSizeMb: 4 };
1386
1444
  /**
1387
1445
  * Validates like {@link validateDocument} without `throwOnError`, but in a worker thread, so the
1388
1446
  * build keeps generating while `@readme/openapi-parser` dereferences and checks the spec. Await the
@@ -1395,7 +1453,10 @@ async function validateDocumentInWorker(document) {
1395
1453
  try {
1396
1454
  const { Worker } = await import("node:worker_threads");
1397
1455
  const workerFile = require("url").pathToFileURL(__filename).href.endsWith(".ts") ? "./validateWorker.ts" : "./validateWorker.js";
1398
- const worker = new Worker(new URL(workerFile, require("url").pathToFileURL(__filename).href), { workerData: document });
1456
+ const worker = new Worker(new URL(workerFile, require("url").pathToFileURL(__filename).href), {
1457
+ workerData: document,
1458
+ resourceLimits: VALIDATION_WORKER_LIMITS
1459
+ });
1399
1460
  message = await new Promise((resolve, reject) => {
1400
1461
  worker.once("message", resolve);
1401
1462
  worker.once("error", reject);
@@ -2001,25 +2062,31 @@ function flattenSchema(schema) {
2001
2062
  function scanSchema(node, pointer = node.pointer) {
2002
2063
  if (pointer) visit(node, pointer);
2003
2064
  }
2004
- let formatTally;
2065
+ var FormatTally = class {
2066
+ #pointers;
2067
+ group(fn) {
2068
+ this.#pointers = memo.create();
2069
+ try {
2070
+ return fn();
2071
+ } finally {
2072
+ const tally = this.#pointers;
2073
+ this.#pointers = void 0;
2074
+ for (const [format, pointers] of tally) reportUnsupportedFormat(format, [...pointers]);
2075
+ }
2076
+ }
2077
+ add(format, pointer) {
2078
+ if (!this.#pointers) return reportUnsupportedFormat(format, [pointer]);
2079
+ memo(this.#pointers, format, () => /* @__PURE__ */ new Set()).add(pointer);
2080
+ }
2081
+ };
2082
+ const formatTally = new FormatTally();
2005
2083
  /**
2006
2084
  * Runs `fn` and reports `KUBB_UNSUPPORTED_FORMAT` once per format with the number of schemas that use it,
2007
2085
  * instead of once per schema. `format` is an open value in OpenAPI, so a large spec would otherwise print
2008
2086
  * thousands of warnings that say the same thing. `fn` must be synchronous.
2009
2087
  */
2010
2088
  function groupUnsupportedFormats(fn) {
2011
- formatTally = memo.create();
2012
- try {
2013
- return fn();
2014
- } finally {
2015
- const tally = formatTally;
2016
- formatTally = void 0;
2017
- for (const [format, pointers] of tally) reportUnsupportedFormat(format, [...pointers]);
2018
- }
2019
- }
2020
- function tallyFormat(format, pointer) {
2021
- if (!formatTally) return reportUnsupportedFormat(format, [pointer]);
2022
- memo(formatTally, format, () => /* @__PURE__ */ new Set()).add(pointer);
2089
+ return formatTally.group(fn);
2023
2090
  }
2024
2091
  function reportUnsupportedFormat(format, pointers) {
2025
2092
  const count = pointers.length;
@@ -2045,7 +2112,7 @@ function visit(node, pointer) {
2045
2112
  pointer
2046
2113
  }
2047
2114
  });
2048
- if (typeof node.format === "string" && !isHandledFormat(node.format)) tallyFormat(node.format, pointer);
2115
+ if (typeof node.format === "string" && !isHandledFormat(node.format)) formatTally.add(node.format, pointer);
2049
2116
  if (node.type === "object") {
2050
2117
  for (const property of node.properties) visit(property.schema, `${pointer}/properties/${escapePointerToken(property.name)}`);
2051
2118
  if (node.additionalProperties && typeof node.additionalProperties === "object") visit(node.additionalProperties, `${pointer}/additionalProperties`);
@@ -2388,10 +2455,15 @@ function parseParameter({ param, pointer, parentName, options, parseSchema, refs
2388
2455
  refs
2389
2456
  });
2390
2457
  const rawSchema = param.schema ?? mediaType?.schema;
2391
- const schema = rawSchema ? parseSchema({
2458
+ const parsed = rawSchema ? parseSchema({
2392
2459
  schema: rawSchema,
2393
2460
  name: schemaName
2394
2461
  }) : _kubb_kit.ast.factory.createSchema({ type: options.unknownType });
2462
+ const schema = parentName && param.name ? _kubb_kit.ast.macro.apply(parsed, [(0, _kubb_kit.macroEnumName)({
2463
+ parentName,
2464
+ propName: param.name,
2465
+ enumSuffix: options.enumSuffix
2466
+ })], { depth: "shallow" }) : parsed;
2395
2467
  if (rawSchema) scanSchema(schema, contentType ? `${pointer}/content/${escapePointerToken(contentType)}/schema` : `${pointer}/schema`);
2396
2468
  return _kubb_kit.ast.factory.createParameter({
2397
2469
  pointer,
@@ -3502,6 +3574,17 @@ function convertFormat(context) {
3502
3574
  });
3503
3575
  }
3504
3576
  /**
3577
+ * Primitive of an enum's members. Without a `type`, the values decide: `{ enum: [0, 1] }` is a number enum.
3578
+ */
3579
+ function getEnumPrimitive(type, values) {
3580
+ if (type === "boolean") return "boolean";
3581
+ if (type === "number" || type === "integer") return "number";
3582
+ if (type !== void 0 || values.length === 0) return "string";
3583
+ if (values.every((value) => typeof value === "boolean")) return "boolean";
3584
+ if (values.every((value) => typeof value === "number")) return "number";
3585
+ return "string";
3586
+ }
3587
+ /**
3505
3588
  * Converts an `enum` schema into an `EnumSchemaNode`.
3506
3589
  */
3507
3590
  function convertEnum({ schema, name, nullable, type, parse }) {
@@ -3515,8 +3598,8 @@ function convertEnum({ schema, name, nullable, type, parse }) {
3515
3598
  if (nullInEnum && filteredValues.length === 0) return createNullNode(schema, name);
3516
3599
  const enumNullable = nullable || nullInEnum || void 0;
3517
3600
  const enumDefault = schema.default === null && enumNullable ? void 0 : schema.default;
3518
- const primitive = type === "boolean" ? "boolean" : type === "number" || type === "integer" ? "number" : "string";
3519
3601
  const uniqueValues = [...new Set(filteredValues)];
3602
+ const primitive = getEnumPrimitive(type, uniqueValues);
3520
3603
  const ctx = {
3521
3604
  schema,
3522
3605
  name,
@@ -3534,16 +3617,18 @@ function convertEnum({ schema, name, nullable, type, parse }) {
3534
3617
  const rawEnumNames = extensionKey ? memberSlots(schema[extensionKey]) : void 0;
3535
3618
  const rawEnumDescriptions = descriptionKey ? memberSlots(schema[descriptionKey]) : void 0;
3536
3619
  const seenNames = /* @__PURE__ */ new Set();
3620
+ const seenValues = /* @__PURE__ */ new Set();
3537
3621
  return createNode(ctx, {
3538
3622
  type: "enum",
3539
3623
  primitive,
3540
- namedEnumValues: uniqueValues.map((value, index) => ({
3624
+ namedEnumValues: filteredValues.map((value, index) => ({
3541
3625
  name: String(rawEnumNames?.[index] ?? value),
3542
3626
  value,
3543
3627
  primitive,
3544
3628
  description: rawEnumDescriptions?.[index]
3545
3629
  })).filter((entry) => {
3546
- if (seenNames.has(entry.name)) return false;
3630
+ if (seenValues.has(entry.value) || seenNames.has(entry.name)) return false;
3631
+ seenValues.add(entry.value);
3547
3632
  seenNames.add(entry.name);
3548
3633
  return true;
3549
3634
  })
@@ -3833,7 +3918,7 @@ const schemaRules = [
3833
3918
  },
3834
3919
  {
3835
3920
  match: (ctx) => ctx.type !== "array" && !!ctx.schema.enum?.some((value) => value !== null) && matchesFormat(ctx) && formatPrintsPlainType(ctx),
3836
- convert: convertFormattedEnum
3921
+ convert: (ctx) => enumExtensionKeys.some((key) => key in ctx.schema) ? convertEnum(ctx) : convertFormattedEnum(ctx)
3837
3922
  },
3838
3923
  {
3839
3924
  match: matchesFormat,
@@ -3895,7 +3980,7 @@ const schemaRules = [
3895
3980
  convert: ({ schema, name, nullable }) => createNullNode(schema, name, nullable)
3896
3981
  }
3897
3982
  ];
3898
- // src/parser.ts
3983
+ // src/schemaParser.ts
3899
3984
  /**
3900
3985
  * `unevaluated*` also sees what composition siblings evaluate, so with such a sibling it is dropped to keep the schema open.
3901
3986
  */
@@ -3910,20 +3995,35 @@ function hasUnevaluatedSiblings(schema) {
3910
3995
  schema.$ref
3911
3996
  ].some((value) => value !== void 0);
3912
3997
  }
3998
+ function isKeyList(value) {
3999
+ return Array.isArray(value) && value.length > 0 && value.every((name) => typeof name === "string");
4000
+ }
3913
4001
  /**
3914
- * Creates the schema converter bound to one OpenAPI document: `parseSchema` dispatches each
3915
- * schema through the ordered `schemaRules` table, with the parser options merged once.
4002
+ * The schema converter bound to one OpenAPI document: `parse` dispatches each schema through the
4003
+ * ordered `schemaRules` table, with the parser options merged once.
3916
4004
  *
3917
4005
  * @internal
3918
4006
  */
3919
- function createSchemaParser(ctx) {
3920
- const { document, refs, renames } = ctx;
3921
- const options = {
3922
- ...DEFAULT_PARSER_OPTIONS,
3923
- ...ctx.options
3924
- };
3925
- /** Converts one OpenAPI schema into a `SchemaNode`, through the first matching rule of `schemaRules`. */
3926
- function parseSchema({ schema, name }) {
4007
+ var SchemaParser = class {
4008
+ #document;
4009
+ #refs;
4010
+ #renames;
4011
+ #options;
4012
+ #presenceKeys = /* @__PURE__ */ new WeakMap();
4013
+ constructor(ctx) {
4014
+ this.#document = ctx.document;
4015
+ this.#refs = ctx.refs;
4016
+ this.#renames = ctx.renames;
4017
+ this.#options = {
4018
+ ...DEFAULT_PARSER_OPTIONS,
4019
+ ...ctx.options
4020
+ };
4021
+ }
4022
+ /**
4023
+ * Converts one OpenAPI schema into a `SchemaNode`, through the first matching rule of `schemaRules`.
4024
+ */
4025
+ parse = ({ schema, name }) => {
4026
+ const options = this.#options;
3927
4027
  if (typeof schema === "boolean") return _kubb_kit.ast.factory.createSchema({
3928
4028
  type: schema ? options.emptySchemaType : "never",
3929
4029
  name: name ?? void 0
@@ -3931,19 +4031,26 @@ function createSchemaParser(ctx) {
3931
4031
  const flattenedSchema = flattenSchema(schema);
3932
4032
  if (flattenedSchema !== schema) {
3933
4033
  const { if: _if, then: _then, else: _else, dependentRequired: _required, dependentSchemas: _schemas, ...shape } = flattenedSchema;
3934
- return withConditionals(parseSchema({
4034
+ return this.#withConditionals(this.parse({
3935
4035
  schema: shape,
3936
4036
  name
3937
4037
  }), [schema, ...schema.allOf]);
3938
4038
  }
3939
4039
  if (hasUnevaluatedSiblings(schema)) {
3940
4040
  const { unevaluatedProperties: _properties, unevaluatedItems: _items, ...open } = schema;
3941
- return parseSchema({
4041
+ return this.parse({
3942
4042
  schema: open,
3943
4043
  name
3944
4044
  });
3945
4045
  }
3946
- const nullable = isNullable(schema, document) || void 0;
4046
+ return this.#convert({
4047
+ schema,
4048
+ name
4049
+ });
4050
+ };
4051
+ #convert({ schema, name }) {
4052
+ const options = this.#options;
4053
+ const nullable = isNullable(schema, this.#document) || void 0;
3947
4054
  const context = {
3948
4055
  schema,
3949
4056
  name,
@@ -3951,16 +4058,17 @@ function createSchemaParser(ctx) {
3951
4058
  defaultValue: schema.default === null && nullable ? void 0 : schema.default,
3952
4059
  type: Array.isArray(schema.type) ? schema.type.find((t) => t !== "null") ?? schema.type[0] : schema.type,
3953
4060
  options,
3954
- parse: parseSchema,
3955
- document,
3956
- refs,
3957
- renames
4061
+ parse: this.parse,
4062
+ document: this.#document,
4063
+ refs: this.#refs,
4064
+ renames: this.#renames
3958
4065
  };
3959
4066
  const rule = schemaRules.find((entry) => entry.match(context));
3960
- return withConditionals(rule ? rule.convert(context) : createNode(context, { type: options.emptySchemaType }), [schema, ...Array.isArray(schema.allOf) ? schema.allOf.filter(isAnnotationMember) : []]);
4067
+ const node = rule ? rule.convert(context) : createNode(context, { type: options.emptySchemaType });
4068
+ const annotationMembers = Array.isArray(schema.allOf) ? schema.allOf.filter(isAnnotationMember) : [];
4069
+ return this.#withConditionals(node, [schema, ...annotationMembers]);
3961
4070
  }
3962
- const presenceKeys = /* @__PURE__ */ new WeakMap();
3963
- function requireKeys(keys) {
4071
+ #requireKeys(keys) {
3964
4072
  const unknown = _kubb_kit.ast.factory.createSchema({ type: _kubb_kit.ast.schema.types.unknown });
3965
4073
  const node = _kubb_kit.ast.factory.createSchema({
3966
4074
  type: _kubb_kit.ast.schema.types.object,
@@ -3971,17 +4079,14 @@ function createSchemaParser(ctx) {
3971
4079
  schema: unknown
3972
4080
  }))
3973
4081
  });
3974
- presenceKeys.set(node, keys.join("\0"));
4082
+ this.#presenceKeys.set(node, keys.join("\0"));
3975
4083
  return node;
3976
4084
  }
3977
- /**
3978
- * Adds `if`/`then`/`else`, `dependentRequired` and `dependentSchemas` to the node as `conditionals`.
3979
- */
3980
- function withConditionals(node, sources) {
3981
- const conditionals = sources.flatMap(toConditionals);
3982
- const existing = new Set((node.conditionals ?? []).map(presenceKey));
4085
+ #withConditionals(node, sources) {
4086
+ const conditionals = sources.flatMap((source) => this.#toConditionals(source));
4087
+ const existing = new Set((node.conditionals ?? []).map((entry) => this.#presenceKey(entry)));
3983
4088
  const added = conditionals.filter((entry) => {
3984
- const key = presenceKey(entry);
4089
+ const key = this.#presenceKey(entry);
3985
4090
  return key === void 0 || !existing.has(key);
3986
4091
  });
3987
4092
  return added.length ? {
@@ -3989,50 +4094,54 @@ function createSchemaParser(ctx) {
3989
4094
  conditionals: [...node.conditionals ?? [], ...added]
3990
4095
  } : node;
3991
4096
  }
3992
- /**
3993
- * The keys an entry checks for presence, or `undefined` when a branch checks more than presence and the entry is always kept.
3994
- */
3995
- function presenceKey({ if: condition, then: thenNode, else: elseNode }) {
4097
+ #presenceKey({ if: condition, then: thenNode, else: elseNode }) {
3996
4098
  const keys = [
3997
4099
  condition,
3998
4100
  thenNode,
3999
4101
  elseNode
4000
- ].map((branch) => branch ? presenceKeys.get(branch) : "");
4102
+ ].map((branch) => branch ? this.#presenceKeys.get(branch) : "");
4001
4103
  return keys.includes(void 0) ? void 0 : keys.join("\n");
4002
4104
  }
4003
- function toConditionals(schema) {
4004
- const branch = (value) => {
4005
- if (!value || typeof value !== "object") return void 0;
4006
- const { required, type, ...rest } = value;
4007
- if (Array.isArray(required) && required.length && (type === void 0 || type === "object") && !Object.keys(rest).length) return requireKeys(required);
4008
- return parseSchema({ schema: value });
4009
- };
4105
+ #toBranch(value) {
4106
+ if (!value || typeof value !== "object") return void 0;
4107
+ const { required, type, ...rest } = value;
4108
+ if (Array.isArray(required) && required.length && (type === void 0 || type === "object") && !Object.keys(rest).length) return this.#requireKeys(required);
4109
+ return this.parse({ schema: value });
4110
+ }
4111
+ #toConditionals(schema) {
4010
4112
  const entries = (value) => value && typeof value === "object" ? Object.entries(value) : [];
4011
4113
  const conditionals = [];
4012
- const condition = branch(schema.if);
4114
+ const condition = this.#toBranch(schema.if);
4013
4115
  if (condition) {
4014
- const thenNode = branch(schema.then);
4015
- const elseNode = branch(schema.else);
4116
+ const thenNode = this.#toBranch(schema.then);
4117
+ const elseNode = this.#toBranch(schema.else);
4016
4118
  conditionals.push({
4017
4119
  if: condition,
4018
4120
  ...thenNode && { then: thenNode },
4019
4121
  ...elseNode && { else: elseNode }
4020
4122
  });
4021
4123
  }
4022
- for (const [key, required] of entries(schema.dependentRequired)) if (Array.isArray(required) && required.length && required.every((name) => typeof name === "string")) conditionals.push({
4023
- if: requireKeys([key]),
4024
- then: requireKeys(required)
4124
+ for (const [key, required] of entries(schema.dependentRequired)) if (isKeyList(required)) conditionals.push({
4125
+ if: this.#requireKeys([key]),
4126
+ then: this.#requireKeys(required)
4025
4127
  });
4026
4128
  for (const [key, dependent] of entries(schema.dependentSchemas)) {
4027
- const thenNode = branch(dependent);
4129
+ const thenNode = this.#toBranch(dependent);
4028
4130
  if (thenNode) conditionals.push({
4029
- if: requireKeys([key]),
4131
+ if: this.#requireKeys([key]),
4030
4132
  then: thenNode
4031
4133
  });
4032
4134
  }
4033
4135
  return conditionals;
4034
4136
  }
4035
- return parseSchema;
4137
+ };
4138
+ /**
4139
+ * Creates the schema converter bound to one OpenAPI document.
4140
+ *
4141
+ * @internal
4142
+ */
4143
+ function createSchemaParser(ctx) {
4144
+ return new SchemaParser(ctx);
4036
4145
  }
4037
4146
  // src/promoteEnums.ts
4038
4147
  /**
@@ -4085,6 +4194,237 @@ function refPromotedEnums(node, promoted) {
4085
4194
  * The `name` of `@kubb/adapter-oas`, used to identify this adapter in a Kubb config.
4086
4195
  */
4087
4196
  const adapterOasName = "oas";
4197
+ var Adapter = class {
4198
+ locate = locate;
4199
+ #settings;
4200
+ #parserOptions;
4201
+ #document = null;
4202
+ #sources = [];
4203
+ #pendingValidations = [];
4204
+ #inputCache = /* @__PURE__ */ new WeakMap();
4205
+ constructor({ validate, contentType, server, discriminator, enums, pathParamsCasing, ...parserOptions }) {
4206
+ this.#settings = {
4207
+ validate,
4208
+ contentType,
4209
+ server,
4210
+ discriminator,
4211
+ enums,
4212
+ pathParamsCasing
4213
+ };
4214
+ this.#parserOptions = parserOptions;
4215
+ }
4216
+ get document() {
4217
+ return this.#document;
4218
+ }
4219
+ get sources() {
4220
+ return this.#sources;
4221
+ }
4222
+ validate = async (input, options) => {
4223
+ const document = await parseFromConfig({
4224
+ type: "path",
4225
+ path: input
4226
+ }, [], { fileRefs: options?.fileRefs });
4227
+ assertDocument(document);
4228
+ await validateDocument(document, options);
4229
+ };
4230
+ settle = async () => {
4231
+ await Promise.all(this.#pendingValidations.splice(0));
4232
+ };
4233
+ parse = async (source, { signal, fileRefs } = {}) => {
4234
+ signal?.throwIfAborted();
4235
+ const cached = this.#inputCache.get(source);
4236
+ if (cached) {
4237
+ this.#sources = cached.sources;
4238
+ this.#document = cached.document;
4239
+ return cached.promise;
4240
+ }
4241
+ const read = [];
4242
+ this.#sources = read;
4243
+ const entry = {
4244
+ sources: read,
4245
+ document: null
4246
+ };
4247
+ const promise = (async () => {
4248
+ const document = await parseFromConfig(source, read, {
4249
+ fileRefs,
4250
+ signal
4251
+ });
4252
+ signal?.throwIfAborted();
4253
+ assertDocument(document);
4254
+ if (this.#settings.validate) this.#pendingValidations.push(validateDocumentInWorker(document));
4255
+ entry.document = document;
4256
+ this.#document = document;
4257
+ const refs = createRefs(document);
4258
+ const { schemas, renames, pointers } = getSchemas(document, { contentType: this.#settings.contentType }, refs);
4259
+ const parseSchema = createSchemaParser({
4260
+ document,
4261
+ refs,
4262
+ renames,
4263
+ options: this.#parserOptions
4264
+ }).parse;
4265
+ return groupUnsupportedFormats(() => this.#parseInput({
4266
+ document,
4267
+ refs,
4268
+ schemas,
4269
+ pointers,
4270
+ parseSchema
4271
+ }));
4272
+ })();
4273
+ this.#inputCache.set(source, Object.assign(entry, { promise }));
4274
+ return promise.catch((error) => {
4275
+ if (signal?.aborted) this.#inputCache.delete(source);
4276
+ throw error;
4277
+ });
4278
+ };
4279
+ /**
4280
+ * Parses every schema and operation once, resolving ref aliases and discriminator children from that same pass.
4281
+ */
4282
+ #parseInput({ document, refs, schemas, pointers, parseSchema }) {
4283
+ const { contentType, server, enums, pathParamsCasing } = this.#settings;
4284
+ const parserOptions = this.#parserOptions;
4285
+ const parsed = this.#parseSchemas({
4286
+ schemas,
4287
+ pointers,
4288
+ parseSchema
4289
+ });
4290
+ const operationNodes = getOperations(document, refs).map((operation) => {
4291
+ const node = parseOperation({
4292
+ operation,
4293
+ document,
4294
+ refs,
4295
+ contentType,
4296
+ options: parserOptions,
4297
+ parseSchema
4298
+ });
4299
+ return pathParamsCasing === "camelcase" ? camelCasePathParams(node) : node;
4300
+ });
4301
+ const promotedEnums = enums === "root" ? collectInlineEnums([...parsed.parsedByName.values(), ...operationNodes], new Set(Object.keys(schemas))) : null;
4302
+ const schemaNodes = resolveSchemaNodes({
4303
+ names: Object.keys(schemas),
4304
+ parsed,
4305
+ promotedEnums
4306
+ });
4307
+ const operations = promotedEnums ? operationNodes.map((node) => refPromotedEnums(node, promotedEnums)) : operationNodes;
4308
+ const authSchemes = toAuthSchemes(document.components?.securitySchemes, refs);
4309
+ return _kubb_kit.ast.factory.createInput({
4310
+ schemas: schemaNodes,
4311
+ operations,
4312
+ meta: toInputMeta({
4313
+ document,
4314
+ server,
4315
+ authSchemes
4316
+ })
4317
+ });
4318
+ }
4319
+ #parseSchemas({ schemas, pointers, parseSchema }) {
4320
+ const { discriminator } = this.#settings;
4321
+ const parsedByName = /* @__PURE__ */ new Map();
4322
+ const refAliasMap = /* @__PURE__ */ new Map();
4323
+ const discriminatorParentNodes = [];
4324
+ for (const [name, schema] of Object.entries(schemas)) {
4325
+ const node = {
4326
+ ...parseSchema({
4327
+ schema,
4328
+ name
4329
+ }),
4330
+ pointer: pointers.get(name)
4331
+ };
4332
+ parsedByName.set(name, node);
4333
+ scanSchema(node);
4334
+ if (node.type === "ref" && node.name) refAliasMap.set(name, node);
4335
+ if (discriminator === "propagate" && isDiscriminatorParent(schema)) discriminatorParentNodes.push(node);
4336
+ }
4337
+ return {
4338
+ parsedByName,
4339
+ refAliasMap,
4340
+ discriminatorChildMap: discriminatorParentNodes.length > 0 ? buildDiscriminatorChildMap(discriminatorParentNodes) : null
4341
+ };
4342
+ }
4343
+ };
4344
+ function isDiscriminatorParent(schema) {
4345
+ return Boolean((schema.oneOf ?? schema.anyOf) && schema.discriminator?.propertyName);
4346
+ }
4347
+ function resolveSchemaNodes({ names, parsed: { parsedByName, refAliasMap, discriminatorChildMap }, promotedEnums }) {
4348
+ const aliasTargetOf = (name) => {
4349
+ const node = refAliasMap.get(name);
4350
+ return node?.ref ? _kubb_kit.ast.ref.getName(node.ref) : node?.name;
4351
+ };
4352
+ function isAliasCycle(name) {
4353
+ const seen = /* @__PURE__ */ new Set([name]);
4354
+ for (let next = aliasTargetOf(name); next; next = aliasTargetOf(next)) {
4355
+ if (next === name) return true;
4356
+ if (seen.has(next)) return false;
4357
+ seen.add(next);
4358
+ }
4359
+ return false;
4360
+ }
4361
+ const schemaNodes = promotedEnums ? [...promotedEnums.values()] : [];
4362
+ for (const name of names) {
4363
+ const aliasTarget = refAliasMap.get(name)?.name;
4364
+ const aliased = aliasTarget ? parsedByName.get(aliasTarget) : void 0;
4365
+ const parsed = parsedByName.get(name);
4366
+ const child = discriminatorChildMap?.get(name);
4367
+ const base = child ? patchDiscriminatorNode(parsed, child) : parsed;
4368
+ const resolved = aliased ? {
4369
+ ...aliased,
4370
+ name,
4371
+ pointer: parsed.pointer
4372
+ } : base;
4373
+ const node = isAliasCycle(name) ? createCycleNode(name, parsed.pointer) : resolved;
4374
+ schemaNodes.push(promotedEnums ? refPromotedEnums(node, promotedEnums) : node);
4375
+ }
4376
+ return schemaNodes;
4377
+ }
4378
+ function createCycleNode(name, pointer) {
4379
+ _kubb_kit.Diagnostics.report({
4380
+ code: _kubb_kit.Diagnostics.code.aliasCycle,
4381
+ severity: "warning",
4382
+ message: `${name} only refers to other schemas that lead back to it, so it is resolved to unknown.`,
4383
+ help: "Give one of the schemas in the loop a real definition, or remove the `$ref` that closes it.",
4384
+ location: {
4385
+ kind: "schema",
4386
+ pointer: pointer ?? `#/components/schemas/${name}`
4387
+ }
4388
+ });
4389
+ return _kubb_kit.ast.factory.createSchema({
4390
+ type: "unknown",
4391
+ name,
4392
+ pointer
4393
+ });
4394
+ }
4395
+ function toInfoMeta(info) {
4396
+ return {
4397
+ title: info?.title,
4398
+ description: info?.description,
4399
+ version: info?.version,
4400
+ summary: info?.summary,
4401
+ termsOfService: info?.termsOfService,
4402
+ contact: pickStrings(info?.contact, [
4403
+ "name",
4404
+ "url",
4405
+ "email"
4406
+ ]),
4407
+ license: typeof info?.license?.name === "string" ? {
4408
+ ...pickStrings(info.license, ["identifier", "url"]),
4409
+ name: info.license.name
4410
+ } : void 0
4411
+ };
4412
+ }
4413
+ function toInputMeta({ document, server, authSchemes }) {
4414
+ return {
4415
+ ...toInfoMeta(document.info),
4416
+ externalDocs: getExternalDocs(document.externalDocs),
4417
+ baseURL: resolveBaseUrl({
4418
+ document,
4419
+ server
4420
+ }),
4421
+ ...server?.index !== void 0 && { serverIndex: server.index },
4422
+ servers: toInputServers(document.servers ?? []),
4423
+ ...document.tags?.length && { tags: toInputTags(document.tags) },
4424
+ ...authSchemes.length && { auth: authSchemes },
4425
+ extensions: pickExtensions(document)
4426
+ };
4427
+ }
4088
4428
  /**
4089
4429
  * Default Kubb adapter for OpenAPI 2.0, 3.0, 3.1, and 3.2 specifications. Reads the
4090
4430
  * spec from `input` (a file path, URL, inline content, or parsed object), validates
@@ -4133,189 +4473,7 @@ const adapterOas = (0, _kubb_core.defineExtension)({
4133
4473
  emptySchemaType,
4134
4474
  enumSuffix
4135
4475
  }),
4136
- build({ validate, contentType, server, discriminator, enums, pathParamsCasing, ...parserOptions }) {
4137
- let parsedDocument = null;
4138
- let sources = [];
4139
- const pendingValidations = [];
4140
- const inputCache = /* @__PURE__ */ new WeakMap();
4141
- /**
4142
- * Parses every schema and operation once, resolving ref aliases and discriminator children from that same pass.
4143
- */
4144
- function parseInput({ document, refs, schemas, pointers, parseSchema }) {
4145
- const parsedByName = /* @__PURE__ */ new Map();
4146
- const refAliasMap = /* @__PURE__ */ new Map();
4147
- const discriminatorParentNodes = [];
4148
- for (const [name, schema] of Object.entries(schemas)) {
4149
- const node = {
4150
- ...parseSchema({
4151
- schema,
4152
- name
4153
- }),
4154
- pointer: pointers.get(name)
4155
- };
4156
- parsedByName.set(name, node);
4157
- scanSchema(node);
4158
- if (node.type === "ref" && node.name) refAliasMap.set(name, node);
4159
- if (discriminator === "propagate" && (schema.oneOf ?? schema.anyOf) && schema.discriminator?.propertyName) discriminatorParentNodes.push(node);
4160
- }
4161
- const discriminatorChildMap = discriminatorParentNodes.length > 0 ? buildDiscriminatorChildMap(discriminatorParentNodes) : null;
4162
- const operationNodes = getOperations(document, refs).map((operation) => {
4163
- const node = parseOperation({
4164
- operation,
4165
- document,
4166
- refs,
4167
- contentType,
4168
- options: parserOptions,
4169
- parseSchema
4170
- });
4171
- return pathParamsCasing === "camelcase" ? camelCasePathParams(node) : node;
4172
- });
4173
- const promotedEnums = enums === "root" ? collectInlineEnums([...parsedByName.values(), ...operationNodes], new Set(Object.keys(schemas))) : null;
4174
- const aliasTargetOf = (name) => {
4175
- const node = refAliasMap.get(name);
4176
- return node?.ref ? _kubb_kit.ast.ref.getName(node.ref) : node?.name;
4177
- };
4178
- function isAliasCycle(name) {
4179
- const seen = /* @__PURE__ */ new Set([name]);
4180
- for (let next = aliasTargetOf(name); next; next = aliasTargetOf(next)) {
4181
- if (next === name) return true;
4182
- if (seen.has(next)) return false;
4183
- seen.add(next);
4184
- }
4185
- return false;
4186
- }
4187
- function createCycleNode(name, pointer) {
4188
- _kubb_kit.Diagnostics.report({
4189
- code: _kubb_kit.Diagnostics.code.aliasCycle,
4190
- severity: "warning",
4191
- message: `${name} only refers to other schemas that lead back to it, so it is resolved to unknown.`,
4192
- help: "Give one of the schemas in the loop a real definition, or remove the `$ref` that closes it.",
4193
- location: {
4194
- kind: "schema",
4195
- pointer: pointer ?? `#/components/schemas/${name}`
4196
- }
4197
- });
4198
- return _kubb_kit.ast.factory.createSchema({
4199
- type: "unknown",
4200
- name,
4201
- pointer
4202
- });
4203
- }
4204
- const schemaNodes = promotedEnums ? [...promotedEnums.values()] : [];
4205
- for (const name of Object.keys(schemas)) {
4206
- const aliasTarget = refAliasMap.get(name)?.name;
4207
- const aliased = aliasTarget ? parsedByName.get(aliasTarget) : void 0;
4208
- const parsed = parsedByName.get(name);
4209
- const child = discriminatorChildMap?.get(name);
4210
- const base = child ? patchDiscriminatorNode(parsed, child) : parsed;
4211
- const resolved = aliased ? {
4212
- ...aliased,
4213
- name,
4214
- pointer: parsed.pointer
4215
- } : base;
4216
- const node = isAliasCycle(name) ? createCycleNode(name, parsed.pointer) : resolved;
4217
- schemaNodes.push(promotedEnums ? refPromotedEnums(node, promotedEnums) : node);
4218
- }
4219
- const operations = promotedEnums ? operationNodes.map((node) => refPromotedEnums(node, promotedEnums)) : operationNodes;
4220
- const authSchemes = toAuthSchemes(document.components?.securitySchemes, refs);
4221
- return _kubb_kit.ast.factory.createInput({
4222
- schemas: schemaNodes,
4223
- operations,
4224
- meta: {
4225
- title: document.info?.title,
4226
- description: document.info?.description,
4227
- version: document.info?.version,
4228
- summary: document.info?.summary,
4229
- termsOfService: document.info?.termsOfService,
4230
- contact: pickStrings(document.info?.contact, [
4231
- "name",
4232
- "url",
4233
- "email"
4234
- ]),
4235
- license: typeof document.info?.license?.name === "string" ? {
4236
- ...pickStrings(document.info.license, ["identifier", "url"]),
4237
- name: document.info.license.name
4238
- } : void 0,
4239
- externalDocs: getExternalDocs(document.externalDocs),
4240
- baseURL: resolveBaseUrl({
4241
- document,
4242
- server
4243
- }),
4244
- ...server?.index !== void 0 && { serverIndex: server.index },
4245
- servers: toInputServers(document.servers ?? []),
4246
- ...document.tags?.length && { tags: toInputTags(document.tags) },
4247
- ...authSchemes.length && { auth: authSchemes },
4248
- extensions: pickExtensions(document)
4249
- }
4250
- });
4251
- }
4252
- return {
4253
- get document() {
4254
- return parsedDocument;
4255
- },
4256
- get sources() {
4257
- return sources;
4258
- },
4259
- locate,
4260
- async validate(input, options) {
4261
- const document = await parseFromConfig({
4262
- type: "path",
4263
- path: input
4264
- }, [], { fileRefs: options?.fileRefs });
4265
- assertDocument(document);
4266
- await validateDocument(document, options);
4267
- },
4268
- async settle() {
4269
- await Promise.all(pendingValidations.splice(0));
4270
- },
4271
- async parse(source, { signal, fileRefs } = {}) {
4272
- signal?.throwIfAborted();
4273
- const cached = inputCache.get(source);
4274
- if (cached) {
4275
- sources = cached.sources;
4276
- parsedDocument = cached.document;
4277
- return cached.promise;
4278
- }
4279
- const read = [];
4280
- sources = read;
4281
- const entry = {
4282
- sources: read,
4283
- document: null
4284
- };
4285
- const promise = (async () => {
4286
- const document = await parseFromConfig(source, read, {
4287
- fileRefs,
4288
- signal
4289
- });
4290
- signal?.throwIfAborted();
4291
- assertDocument(document);
4292
- if (validate) pendingValidations.push(validateDocumentInWorker(document));
4293
- entry.document = document;
4294
- parsedDocument = document;
4295
- const refs = createRefs(document);
4296
- const { schemas, renames, pointers } = getSchemas(document, { contentType }, refs);
4297
- const parseSchema = createSchemaParser({
4298
- document,
4299
- refs,
4300
- renames,
4301
- options: parserOptions
4302
- });
4303
- return groupUnsupportedFormats(() => parseInput({
4304
- document,
4305
- refs,
4306
- schemas,
4307
- pointers,
4308
- parseSchema
4309
- }));
4310
- })();
4311
- inputCache.set(source, Object.assign(entry, { promise }));
4312
- return promise.catch((error) => {
4313
- if (signal?.aborted) inputCache.delete(source);
4314
- throw error;
4315
- });
4316
- }
4317
- };
4318
- }
4476
+ build: (options) => new Adapter(options)
4319
4477
  });
4320
4478
  exports.adapterOas = adapterOas;
4321
4479
  exports.adapterOasName = adapterOasName;