@kubb/adapter-oas 5.18.6 → 5.18.8

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.d.cts CHANGED
@@ -1318,5 +1318,4 @@ type Operation = {
1318
1318
  schema: OperationObject$1;
1319
1319
  pathItem: PathItemObject$1;
1320
1320
  };
1321
- export type { AdapterOas, AdapterOasOptions, AdapterOasResolvedOptions, ContentType, DiscriminatorObject$1 as DiscriminatorObject, Document, MediaTypeObject$1 as MediaTypeObject, Operation, ReferenceObject$1 as ReferenceObject, ResponseObject$1 as ResponseObject, SchemaObject$1 as SchemaObject };
1322
- //# sourceMappingURL=index.d.cts.map
1321
+ export type { AdapterOas, AdapterOasOptions, AdapterOasResolvedOptions, ContentType, DiscriminatorObject$1 as DiscriminatorObject, Document, MediaTypeObject$1 as MediaTypeObject, Operation, ReferenceObject$1 as ReferenceObject, ResponseObject$1 as ResponseObject, SchemaObject$1 as SchemaObject };
package/dist/index.d.ts CHANGED
@@ -1318,5 +1318,4 @@ type Operation = {
1318
1318
  schema: OperationObject$1;
1319
1319
  pathItem: PathItemObject$1;
1320
1320
  };
1321
- export type { AdapterOas, AdapterOasOptions, AdapterOasResolvedOptions, ContentType, DiscriminatorObject$1 as DiscriminatorObject, Document, MediaTypeObject$1 as MediaTypeObject, Operation, ReferenceObject$1 as ReferenceObject, ResponseObject$1 as ResponseObject, SchemaObject$1 as SchemaObject };
1322
- //# sourceMappingURL=index.d.ts.map
1321
+ export type { AdapterOas, AdapterOasOptions, AdapterOasResolvedOptions, ContentType, DiscriminatorObject$1 as DiscriminatorObject, Document, MediaTypeObject$1 as MediaTypeObject, Operation, ReferenceObject$1 as ReferenceObject, ResponseObject$1 as ResponseObject, SchemaObject$1 as SchemaObject };
package/dist/index.js CHANGED
@@ -2,25 +2,19 @@ import { defineExtension } from "@kubb/core";
2
2
  import { Diagnostics, ast, childName, enumPrimitive, enumPropName, macroDedupeUnion, macroDiscriminatorEnum, macroEnumName, mergeAdjacentObjectsLazy } from "@kubb/kit";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import { access, readFile } from "node:fs/promises";
5
+ import { readFile } from "node:fs";
6
+ import { access } from "node:fs/promises";
6
7
  import { upgrade } from "@scalar/openapi-upgrader";
7
8
  import { bundle } from "api-ref-bundler";
8
- import { CORE_SCHEMA, load } from "js-yaml";
9
- import * as yaml from "yaml";
10
- import { parse } from "yaml";
11
- // \0rolldown/runtime.js
12
- var __defProp = Object.defineProperty;
13
- var __name = (target, value) => __defProp(target, "name", {
14
- value,
15
- configurable: true
16
- });
9
+ import { COLLECTION_STYLE, CORE_SCHEMA, EVENT_ID, SCALAR_STYLE, constructFromEvents, load, parseEvents } from "js-yaml";
10
+ import { parse as parse$1 } from "yaml";
17
11
  // kubb-extension.json
18
12
  var compatibility = {
19
13
  "kubb": ">=5.8.3",
20
14
  "node": ">=22.22"
21
15
  };
22
16
  // package.json
23
- var version = "5.18.6";
17
+ var version = "5.18.8";
24
18
  // src/constants.ts
25
19
  /**
26
20
  * Default parser options applied when no explicit options are provided.
@@ -367,8 +361,44 @@ async function exists(path) {
367
361
  */
368
362
  async function read(path) {
369
363
  if (runtime.isBun) return Bun.file(path).text();
370
- return readFile(path, { encoding: "utf8" });
364
+ return new Promise((resolvePromise, reject) => readFile(path, { encoding: "utf8" }, (error, data) => error ? reject(error) : resolvePromise(data)));
365
+ }
366
+ // ../../internals/utils/src/promise.ts
367
+ /**
368
+ * Returns the value cached under `key` in `store`, computing and storing it on the first call.
369
+ * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive
370
+ * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.
371
+ *
372
+ * @example
373
+ * `const refs = memo(refCache, node, () => collectRefs(node))`
374
+ */
375
+ function memo(store, key, compute) {
376
+ const cached = store.get(key);
377
+ if (cached !== void 0 || store.has(key)) return cached;
378
+ const value = compute();
379
+ store.set(key, value);
380
+ return value;
381
+ }
382
+ function createStore({ type }) {
383
+ if (type === "weak") return /* @__PURE__ */ new WeakMap();
384
+ const entry = /* @__PURE__ */ new Map();
385
+ if (type === "map") return entry;
386
+ const set = (key, value) => {
387
+ entry.clear();
388
+ entry.set(key, value);
389
+ };
390
+ const touch = (key) => {
391
+ if (!entry.has(key)) return false;
392
+ set(key, entry.get(key));
393
+ return true;
394
+ };
395
+ return {
396
+ has: touch,
397
+ get: (key) => touch(key) ? entry.get(key) : void 0,
398
+ set
399
+ };
371
400
  }
401
+ memo.create = createStore;
372
402
  // src/oas.ts
373
403
  /**
374
404
  * Returns `true` when a schema should be treated as nullable.
@@ -614,6 +644,11 @@ const NAMED_ENTRY_KEYS = /* @__PURE__ */ new Set([
614
644
  "schemas",
615
645
  "dependentSchemas"
616
646
  ]);
647
+ const TARGET_KEYS = [
648
+ "$id",
649
+ "$anchor",
650
+ "$dynamicAnchor"
651
+ ];
617
652
  function walk(node, pointer, visit, parentKey) {
618
653
  if (!node || typeof node !== "object") return;
619
654
  if (!Array.isArray(node)) visit(node, pointer);
@@ -623,6 +658,37 @@ function walk(node, pointer, visit, parentKey) {
623
658
  walk(value, `${pointer}/${escapePointerToken(key)}`, visit, Array.isArray(node) ? parentKey : key);
624
659
  }
625
660
  }
661
+ /** Answers, in one walk and without building JSON pointers, what the loading steps after it need to know. */
662
+ function scanDocument(document) {
663
+ const scan = {
664
+ externalRef: false,
665
+ schemaIds: false,
666
+ pathRefs: false
667
+ };
668
+ const visit = ({ node, readsIds, parentKey }) => {
669
+ if (!node || typeof node !== "object") return;
670
+ const isArray = Array.isArray(node);
671
+ const record = node;
672
+ const ref = record["$ref"];
673
+ if (typeof ref === "string" && !ref.startsWith("#")) scan.externalRef = true;
674
+ if (typeof ref === "string" && ref.startsWith("#/paths/")) scan.pathRefs = true;
675
+ if (readsIds && !isArray && TARGET_KEYS.some((key) => typeof record[key] === "string")) scan.schemaIds = true;
676
+ const named = parentKey !== void 0 && NAMED_ENTRY_KEYS.has(parentKey);
677
+ for (const key in record) {
678
+ const childReadsIds = readsIds && (named || !(DATA_KEYS.has(key) || key.startsWith("x-")));
679
+ visit({
680
+ node: record[key],
681
+ readsIds: childReadsIds,
682
+ parentKey: isArray ? parentKey : key
683
+ });
684
+ }
685
+ };
686
+ visit({
687
+ node: document,
688
+ readsIds: true
689
+ });
690
+ return scan;
691
+ }
626
692
  /**
627
693
  * The declaration in the nearest enclosing schema, else the only one, else `undefined`.
628
694
  */
@@ -657,6 +723,182 @@ function resolveSchemaIds(document) {
657
723
  }
658
724
  });
659
725
  }
726
+ // src/sourceLocator.ts
727
+ const flowGap = /(?:[\s,]|#[^\n]*)*/y;
728
+ const indexes = memo.create({ type: "last" });
729
+ function toKeyText(text) {
730
+ if (!/^[-+.~\d]|^(?:null|true|false)$/i.test(text)) return text;
731
+ try {
732
+ const value = load(text, { schema: CORE_SCHEMA });
733
+ return value === null || typeof value === "number" || typeof value === "boolean" ? String(value) : text;
734
+ } catch {
735
+ return text;
736
+ }
737
+ }
738
+ function indexEvents(events) {
739
+ const types = new Uint8Array(events.length);
740
+ const styles = new Uint8Array(events.length);
741
+ const starts = new Int32Array(events.length);
742
+ const ends = new Int32Array(events.length);
743
+ for (let at = 0, last = 0; at < events.length; last = Math.max(last, starts[at], ends[at]), at++) {
744
+ const event = events[at];
745
+ types[at] = event.type;
746
+ if (event.type === EVENT_ID.SCALAR) {
747
+ const quote = event.style === SCALAR_STYLE.SINGLE_QUOTED || event.style === SCALAR_STYLE.DOUBLE_QUOTED ? 1 : 0;
748
+ const empty = event.valueStart < 0;
749
+ styles[at] = event.style;
750
+ starts[at] = empty ? last : event.valueStart - quote;
751
+ ends[at] = empty ? last : event.valueEnd + quote;
752
+ }
753
+ if (event.type === EVENT_ID.ALIAS) {
754
+ starts[at] = event.anchorStart - 1;
755
+ ends[at] = event.anchorEnd;
756
+ }
757
+ if (event.type === EVENT_ID.MAPPING || event.type === EVENT_ID.SEQUENCE) {
758
+ styles[at] = event.style;
759
+ starts[at] = event.start;
760
+ }
761
+ }
762
+ return {
763
+ types,
764
+ styles,
765
+ starts,
766
+ ends,
767
+ collections: /* @__PURE__ */ new Map()
768
+ };
769
+ }
770
+ function createLocator({ index, source }) {
771
+ const { types, styles, starts, ends, collections } = index;
772
+ const isCollection = (at) => types[at] === EVENT_ID.MAPPING || types[at] === EVENT_ID.SEQUENCE;
773
+ const readText = (at) => {
774
+ const text = source.slice(starts[at], ends[at]);
775
+ if (styles[at] === SCALAR_STYLE.SINGLE_QUOTED) return text.slice(1, -1).replaceAll("''", "'");
776
+ if (styles[at] !== SCALAR_STYLE.DOUBLE_QUOTED) return text;
777
+ try {
778
+ return JSON.parse(text);
779
+ } catch {
780
+ return String(load(text, { schema: CORE_SCHEMA }));
781
+ }
782
+ };
783
+ const readNode = (at) => {
784
+ if (!isCollection(at)) return {
785
+ start: starts[at],
786
+ end: ends[at],
787
+ next: at + 1
788
+ };
789
+ let next = at + 1;
790
+ let end = starts[at];
791
+ while (types[next] !== EVENT_ID.POP) ({end, next} = readNode(next));
792
+ if (styles[at] === COLLECTION_STYLE.FLOW) {
793
+ flowGap.lastIndex = end;
794
+ flowGap.exec(source);
795
+ end = flowGap.lastIndex + 1;
796
+ }
797
+ return {
798
+ start: starts[at],
799
+ end,
800
+ next: next + 1
801
+ };
802
+ };
803
+ const readChildren = (collection) => {
804
+ const keys = /* @__PURE__ */ new Map();
805
+ const items = [];
806
+ const isMapping = types[collection] === EVENT_ID.MAPPING;
807
+ for (let at = collection + 1; types[at] !== EVENT_ID.POP;) {
808
+ const key = isMapping ? at : void 0;
809
+ if (key !== void 0) at = readNode(at).next;
810
+ const { start, end, next } = readNode(at);
811
+ if (key === void 0) items.push({
812
+ index: at,
813
+ range: {
814
+ start,
815
+ end
816
+ }
817
+ });
818
+ const raw = key !== void 0 && types[key] === EVENT_ID.SCALAR ? readText(key) : void 0;
819
+ const text = raw !== void 0 && styles[key] === SCALAR_STYLE.PLAIN ? toKeyText(raw) : raw;
820
+ if (text !== void 0 && !keys.has(text)) keys.set(text, {
821
+ index: at,
822
+ range: {
823
+ start: starts[key],
824
+ end: ends[key]
825
+ }
826
+ });
827
+ at = next;
828
+ }
829
+ return {
830
+ keys,
831
+ items
832
+ };
833
+ };
834
+ const walk = ({ at, tokens: [token, ...rest], range }) => {
835
+ if (token === void 0) return range;
836
+ if (!isCollection(at)) return void 0;
837
+ const { keys, items } = memo(collections, at, () => readChildren(at));
838
+ const child = keys.get(token) ?? items[Number(token)];
839
+ return child ? walk({
840
+ at: child.index,
841
+ tokens: rest,
842
+ range: child.range
843
+ }) : void 0;
844
+ };
845
+ return {
846
+ find(pointer) {
847
+ return walk({
848
+ at: 1,
849
+ tokens: pointer.replace(/^#/, "").split("/").slice(1).map(unescapePointerToken),
850
+ range: void 0
851
+ });
852
+ },
853
+ findRef(ref) {
854
+ if (!index.refs) {
855
+ index.refs = /* @__PURE__ */ new Map();
856
+ const frames = [];
857
+ for (let at = 1; at + 1 < types.length; at++) {
858
+ if (types[at] === EVENT_ID.POP) {
859
+ frames.pop();
860
+ continue;
861
+ }
862
+ const top = frames.length - 1;
863
+ const isKey = frames[top] === 0;
864
+ if (frames[top] >= 0) frames[top] = 1 - frames[top];
865
+ if (isCollection(at)) frames.push(types[at] === EVENT_ID.MAPPING ? 0 : -1);
866
+ if (!isKey || types[at] !== EVENT_ID.SCALAR || types[at + 1] !== EVENT_ID.SCALAR || readText(at) !== "$ref") continue;
867
+ const text = readText(at + 1);
868
+ if (!index.refs.has(text)) index.refs.set(text, {
869
+ start: starts[at + 1],
870
+ end: ends[at + 1]
871
+ });
872
+ }
873
+ }
874
+ return index.refs.get(ref);
875
+ }
876
+ };
877
+ }
878
+ function parse(source) {
879
+ try {
880
+ return indexEvents(parseEvents(source, { maxDepth: Number.POSITIVE_INFINITY }));
881
+ } catch {
882
+ return;
883
+ }
884
+ }
885
+ function rememberEvents({ source, events }) {
886
+ indexes.set(source, indexEvents(events));
887
+ }
888
+ /**
889
+ * Maps OpenAPI JSON pointers and unresolved references to ranges in YAML or JSON source.
890
+ */
891
+ const locate = (source, location) => {
892
+ if (!("pointer" in location)) return void 0;
893
+ const index = memo(indexes, source, () => parse(source));
894
+ if (!index) return void 0;
895
+ const { find, findRef } = createLocator({
896
+ index,
897
+ source
898
+ });
899
+ const ref = "ref" in location ? location.ref : void 0;
900
+ return find(location.pointer) ?? (ref ? findRef(ref) : void 0);
901
+ };
660
902
  // src/load/source.ts
661
903
  const urlRegExp = /^https?:\/+/i;
662
904
  /**
@@ -711,14 +953,15 @@ async function readSource(sourcePath) {
711
953
  * Reads and parses one source file or URL referenced during bundling: YAML/JSON is parsed into an
712
954
  * object, Markdown is returned as-is (bundled inline rather than dereferenced).
713
955
  */
714
- async function resolveSource(sourcePath) {
956
+ async function resolveSource(sourcePath, { remember } = {}) {
715
957
  const data = await readSource(sourcePath);
716
958
  if (sourcePath.toLowerCase().endsWith(".md")) return data;
717
959
  const pathname = urlRegExp.test(sourcePath) ? new URL(sourcePath).pathname : sourcePath;
718
960
  return parseYaml(data, {
719
961
  origin: sourcePath,
720
962
  json: !/\.ya?ml$/i.test(pathname),
721
- help: "Fix the syntax at the reported line, or check that `input` points at the spec and not an HTML page."
963
+ help: "Fix the syntax at the reported line, or check that `input` points at the spec and not an HTML page.",
964
+ remember
722
965
  });
723
966
  }
724
967
  /**
@@ -734,16 +977,26 @@ async function resolveSource(sourcePath) {
734
977
  * keeping the last one. Its core schema keeps timestamps as strings and `<<` as a plain key, as
735
978
  * `yaml` does for YAML 1.2.
736
979
  */
737
- function parseYaml(data, { origin, help, json = true }) {
980
+ function parseYaml(data, { origin, help, json = true, remember = false }) {
738
981
  if (json && /^\s*[[{]/.test(data)) try {
739
982
  return JSON.parse(data);
740
983
  } catch {}
741
984
  try {
742
- const document = load(data, { schema: CORE_SCHEMA });
743
- if (document !== void 0) return document;
985
+ const events = parseEvents(data, {});
986
+ const documents = constructFromEvents(events, {
987
+ source: data,
988
+ schema: CORE_SCHEMA
989
+ });
990
+ if (documents.length === 1 && documents[0] !== void 0) {
991
+ if (remember) rememberEvents({
992
+ source: data,
993
+ events
994
+ });
995
+ return documents[0];
996
+ }
744
997
  } catch {}
745
998
  try {
746
- return parse(data);
999
+ return parse$1(data);
747
1000
  } catch (error) {
748
1001
  throw new Diagnostics.Error({
749
1002
  code: Diagnostics.code.invalidDocument,
@@ -772,18 +1025,15 @@ async function assertInputExists(input) {
772
1025
  });
773
1026
  }
774
1027
  // src/load/normalize.ts
1028
+ const scans = /* @__PURE__ */ new WeakMap();
775
1029
  /**
776
- * True when `node` contains a `$ref` pointing outside the current document (a relative path,
777
- * absolute path, or URL). An internal `#/...` fragment does not count.
778
- *
779
- * `Object.values` reads array elements and object property values alike, so the same recursion
780
- * walks both without a separate array branch.
1030
+ * Rewrites `$id` and `$anchor` refs in place, then returns the scan of the result.
781
1031
  */
782
- function hasExternalRef(node) {
783
- if (!node || typeof node !== "object") return false;
784
- const ref = node.$ref;
785
- if (typeof ref === "string" && !ref.startsWith("#")) return true;
786
- return Object.values(node).some(hasExternalRef);
1032
+ function resolveTargets(document) {
1033
+ const scan = scanDocument(document);
1034
+ if (!scan.schemaIds) return scan;
1035
+ resolveSchemaIds(document);
1036
+ return scanDocument(document);
787
1037
  }
788
1038
  /**
789
1039
  * Replaces each `$ref` into `#/paths/...` with a copy of its target, in place.
@@ -875,13 +1125,16 @@ async function bundleDocument(pathOrUrl, { document, sources = [] } = {}) {
875
1125
  const cached = cache.get(key);
876
1126
  if (cached) return cached;
877
1127
  sources.push(key);
878
- const result = resolveSource(sourcePath);
1128
+ const result = resolveSource(sourcePath, { remember: key === toKey(pathOrUrl) });
879
1129
  cache.set(key, result);
880
1130
  return result;
881
1131
  };
882
1132
  const root = await resolver(pathOrUrl);
883
- resolveSchemaIds(root);
884
- if (typeof root === "object" && root !== null && !hasExternalRef(root)) return root;
1133
+ const scan = resolveTargets(root);
1134
+ if (typeof root === "object" && root !== null && !scan.externalRef) {
1135
+ scans.set(root, scan);
1136
+ return root;
1137
+ }
885
1138
  entry = getBaseUri(pathOrUrl, root);
886
1139
  entryDocument = root;
887
1140
  return await bundle(entry, resolver, { hooks: { onError: (message, { path, state }) => {
@@ -924,11 +1177,13 @@ async function parseFromConfig(source, sources = []) {
924
1177
  origin: "the inline `input` string",
925
1178
  help: "Fix the syntax at the reported line. Kubb reads `input` as an inline spec, not a file path, because it starts with `{`, `[`, `openapi:`, or `swagger:`, or spans several lines."
926
1179
  }) : structuredClone(source.data);
927
- if (source.root && hasExternalRef(data)) return bundleDocument(join(source.root, inlineInputName), {
1180
+ const isObject = Boolean(data) && typeof data === "object";
1181
+ if (source.root && isObject) return bundleDocument(join(source.root, inlineInputName), {
928
1182
  document: data,
929
1183
  sources
930
1184
  });
931
- resolveSchemaIds(data);
1185
+ const scan = resolveTargets(data);
1186
+ if (isObject) scans.set(data, scan);
932
1187
  return data;
933
1188
  }
934
1189
  await assertInputExists(source.path);
@@ -941,7 +1196,7 @@ async function parseFromConfig(source, sources = []) {
941
1196
  if (typeof version === "number") document[key] = Number.isInteger(version) ? version.toFixed(1) : String(version);
942
1197
  }
943
1198
  }
944
- if (raw && typeof raw === "object" && "swagger" in raw) {
1199
+ if (raw && typeof raw === "object" && "swagger" in raw && (scans.get(raw)?.pathRefs ?? true)) {
945
1200
  const refs = createRefs(raw);
946
1201
  inlinePathRefs(raw, (ref) => refs.resolve(ref, { report: false }));
947
1202
  }
@@ -3608,163 +3863,6 @@ function refPromotedEnums(node, promoted) {
3608
3863
  });
3609
3864
  } });
3610
3865
  }
3611
- // src/sourceLocator.ts
3612
- let cached;
3613
- const toRange = ([start, end]) => ({
3614
- start,
3615
- end
3616
- });
3617
- /** Walks a JSON pointer through maps and sequences; the range is the last key or item it reached. */
3618
- function findPointer(document, pointer) {
3619
- return pointer.replace(/^#/, "").split("/").slice(1).map(unescapePointerToken).reduce((at, token) => {
3620
- if (yaml.isMap(at?.node)) {
3621
- const pair = at.node.items.find((item) => yaml.isScalar(item.key) && String(item.key.value) === token);
3622
- return pair && yaml.isScalar(pair.key) && pair.key.range ? {
3623
- node: pair.value,
3624
- range: toRange(pair.key.range)
3625
- } : void 0;
3626
- }
3627
- if (yaml.isSeq(at?.node)) {
3628
- const item = at.node.items[Number(token)];
3629
- return yaml.isNode(item) && item.range ? {
3630
- node: item,
3631
- range: toRange(item.range)
3632
- } : void 0;
3633
- }
3634
- }, {
3635
- node: document.contents,
3636
- range: void 0
3637
- })?.range;
3638
- }
3639
- /** The first `$ref` whose value is `ref`. */
3640
- function findRefUsage(document, ref) {
3641
- const found = [];
3642
- yaml.visit(document, { Pair(_, { key, value }) {
3643
- if (!yaml.isScalar(key) || key.value !== "$ref" || !yaml.isScalar(value) || value.value !== ref || !value.range) return;
3644
- found.push(toRange(value.range));
3645
- return yaml.visit.BREAK;
3646
- } });
3647
- return found[0];
3648
- }
3649
- /**
3650
- * One pass over JSON text, so a located diagnostic in a large JSON spec skips `yaml.parseDocument`.
3651
- * Holds the range of every key and array item by pointer, and the first usage of every `$ref`, as
3652
- * `findPointer` and `findRefUsage` return them. Throws where the text breaks JSON syntax, such as a
3653
- * comment, an unquoted key, or an unquoted `$ref` value. Other bare values, such as `object`, pass.
3654
- */
3655
- function indexJson(source) {
3656
- const pointers = /* @__PURE__ */ new Map();
3657
- const refs = /* @__PURE__ */ new Map();
3658
- let at = source.indexOf("{");
3659
- const fail = () => {
3660
- throw new SyntaxError(`Unexpected character at ${at}`);
3661
- };
3662
- const skipSpace = () => {
3663
- for (let code = source.charCodeAt(at); code === 32 || code === 9 || code === 10 || code === 13; code = source.charCodeAt(++at));
3664
- };
3665
- const readString = () => {
3666
- if (source[at] !== "\"") fail();
3667
- const start = at;
3668
- for (at++; source.charCodeAt(at) !== 34; at++) {
3669
- if (at >= source.length) fail();
3670
- if (source.charCodeAt(at) === 92) at++;
3671
- }
3672
- const raw = source.slice(start + 1, at++);
3673
- return {
3674
- text: raw.includes("\\") ? JSON.parse(source.slice(start, at)) : raw,
3675
- start,
3676
- end: at
3677
- };
3678
- };
3679
- const expect = (char) => {
3680
- skipSpace();
3681
- if (source[at++] !== char) fail();
3682
- skipSpace();
3683
- };
3684
- const walk = (pointer) => {
3685
- const open = source[at];
3686
- if (open === "\"") {
3687
- readString();
3688
- return;
3689
- }
3690
- if (open !== "{" && open !== "[") {
3691
- const start = at;
3692
- while (at < source.length && !/[\s,\]}]/.test(source[at])) at++;
3693
- if (at === start) fail();
3694
- return;
3695
- }
3696
- const close = open === "{" ? "}" : "]";
3697
- at++;
3698
- for (let index = 0;; index++) {
3699
- skipSpace();
3700
- if (source[at] === close) break;
3701
- if (index > 0) expect(",");
3702
- if (open === "[") {
3703
- const start = at;
3704
- const next = `${pointer}/${index}`;
3705
- walk(next);
3706
- if (!pointers.has(next)) pointers.set(next, {
3707
- start,
3708
- end: at
3709
- });
3710
- continue;
3711
- }
3712
- const key = readString();
3713
- const next = `${pointer}/${escapePointerToken(key.text)}`;
3714
- if (!pointers.has(next)) pointers.set(next, {
3715
- start: key.start,
3716
- end: key.end
3717
- });
3718
- expect(":");
3719
- if (key.text !== "$ref" || source[at] === "{" || source[at] === "[") {
3720
- walk(next);
3721
- continue;
3722
- }
3723
- const value = readString();
3724
- if (!refs.has(value.text)) refs.set(value.text, {
3725
- start: value.start,
3726
- end: value.end
3727
- });
3728
- }
3729
- at++;
3730
- };
3731
- walk("#");
3732
- return {
3733
- pointers,
3734
- refs
3735
- };
3736
- }
3737
- /** Indexes plain JSON text; anything else goes to the YAML parser. */
3738
- function parse$1(source) {
3739
- if (/^[ \t\n\r]*\{/.test(source)) try {
3740
- return {
3741
- source,
3742
- json: indexJson(source)
3743
- };
3744
- } catch {}
3745
- return {
3746
- source,
3747
- document: yaml.parseDocument(source)
3748
- };
3749
- }
3750
- __name(parse$1, "parse");
3751
- /**
3752
- * Maps OpenAPI JSON pointers and unresolved references to ranges in YAML or JSON source.
3753
- */
3754
- const locate = (source, location) => {
3755
- if (!("pointer" in location)) return void 0;
3756
- cached = cached?.source === source ? {
3757
- ...cached,
3758
- source
3759
- } : parse$1(source);
3760
- const ref = "ref" in location ? location.ref : void 0;
3761
- if ("json" in cached) {
3762
- const { pointers, refs } = cached.json;
3763
- return pointers.get(location.pointer) ?? (ref ? refs.get(ref) : void 0);
3764
- }
3765
- const { document } = cached;
3766
- return findPointer(document, location.pointer) ?? (ref ? findRefUsage(document, ref) : void 0);
3767
- };
3768
3866
  // src/adapter.ts
3769
3867
  /**
3770
3868
  * The `name` of `@kubb/adapter-oas`, used to identify this adapter in a Kubb config.