@amritk/resolve-refs 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AI.md CHANGED
@@ -26,8 +26,8 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
26
26
  ## Gotchas — where agents fail
27
27
 
28
28
  1. **`resolveRefs` is in-memory only.** It does NOT load other files/URLs —
29
- external refs stay in place and are pushed to `errors` (the ref becomes `{}`).
30
- Use `resolveRefsFromFile` for cross-file/remote.
29
+ external refs stay in place and are pushed to `errors` (the `{ $ref }` node is
30
+ kept as written, not inlined). Use `resolveRefsFromFile` for cross-file/remote.
31
31
  2. **Errors are collected, never thrown.** A missing file, refused host, or bad
32
32
  URL lands on `result.errors` while the rest still resolves. Always check it.
33
33
  Each error's `path` is where the offending reference was written in the
@@ -45,7 +45,9 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
45
45
  `allowedRoots: ['./specs']` (or whatever contains both files) to allow it.
46
46
  `localRefs: false` refuses cross-file reads entirely.
47
47
  5. **JSON-only by default** (`JSON.parse`). For YAML pass a custom
48
- `parse: (content, location) => …` (e.g. wrapping `@amritk/yaml`).
48
+ `parse: (content, location) => …` (e.g. wrapping `@amritk/yaml`). Already
49
+ parsed the root? Pass it as `rootDocument` and the file is not read or
50
+ parsed again (its path still anchors relative refs and `allowedRoots`).
49
51
  6. **`origins` exists only with `trackOrigins: true`.** Cycles are preserved (the
50
52
  cycle point stays a `$ref`), so output is not always fully flat. The remote
51
53
  cache is process-wide but credential-scoped and bounded (10 min TTL, 256
package/README.md CHANGED
@@ -70,7 +70,9 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
70
70
  | `maxDepth` | `512` | How deep to walk before leaving a subtree unresolved and recording an error. |
71
71
  | `cache` | `true` | Pass `false` to bypass the process-wide session cache for this call — everything is re-fetched, nothing is stored. |
72
72
  | `parse` | `JSON.parse` | Custom content parser (e.g. YAML-aware). |
73
+ | `rootDocument` | — | The root's already-parsed value. The named file is then neither read nor parsed; its location still anchors relative refs, `allowedRoots`, and `origins`. The value is only read, never written or aliased into the result. |
73
74
  | `trackOrigins` | `false` | Record a per-node origin map on the result. |
75
+ | `bundle` | `false` | Bundle instead of inlining: hoist each target from another document into the root's `$defs` once and point its refs there, keeping refs into the root as written. The output is one document with only internal refs — what a code generator wants, since a shared schema stays one definition instead of a copy at every use. A document with an absolute `$id` is embedded whole with its `$id`, and refs to anything in an embedded resource name it by that URI; a document with a relative `$id` is inlined. |
74
76
 
75
77
  Errors (a missing file, a refused host, a refused path, a bad URL, a document too
76
78
  deeply nested) are collected on `result.errors` rather than thrown; the
@@ -100,7 +102,8 @@ The remote path has always been default-deny; the local path now matches it.
100
102
  planted in the tree cannot be used to escape it. The root document itself is
101
103
  exempt: it is the file you explicitly named.
102
104
  - **The session cache is credential-scoped.** Its key covers the request headers,
103
- the `fetch`/`parse` callbacks, and the transfer limits, so a document fetched
105
+ the `fetch`/`parse` callbacks, the transfer limits, and the host guards
106
+ (`allowPrivateHosts`, `allowedHosts`, `verifyDns`), so a document fetched
104
107
  with one tenant's token is invisible to a call carrying different (or no)
105
108
  credentials — and no caller inherits another's `fetch`. In-flight coalescing
106
109
  uses the same key.
@@ -191,20 +194,12 @@ recursive cycles intact, and records a diagnostic for every external ref. The
191
194
  registry, no scoping, no diagnostics — and re-resolves each ref on every
192
195
  encounter, so the gap is the production resolver's *total* per-call cost against
193
196
  the cheapest thing that produces the same inlined shape. Both are asserted to
194
- produce byte-identical output before either is timed. Medians of three runs on each runtime, one machine (Linux x64, a 4-vCPU cloud
195
- box, Bun 1.4.0 and Node 26.8.1 — your hardware will differ, run `bun run bench`
196
- or `bun run bench:node` yourself):
197
-
198
- | schema | Bun: cached | Bun: naive | Bun speedup | Node: cached | Node: naive | Node speedup |
199
- |:---|---:|---:|---:|---:|---:|---:|
200
- | chain (40 `$ref` → `$ref` links) | ~4.6k ops/s | ~1.1k ops/s | **~4.1×** | ~4.7k ops/s | ~1.1k ops/s | **~4.1×** |
201
- | reuse-heavy (50 refs → 1 def) | ~6.9k ops/s | ~11k ops/s | ~0.62× | ~6.6k ops/s | ~10k ops/s | ~0.66× |
202
- | cyclic tree | ~50k ops/s | ~183k ops/s | ~0.27× | ~58k ops/s | ~184k ops/s | ~0.31× |
203
- | wide-distinct (60 defs, each used once) | ~3.7k ops/s | ~9.5k ops/s | ~0.39× | ~3.4k ops/s | ~9.0k ops/s | ~0.38× |
204
-
205
- The two engines agree on every row to within a few percent, which is what you
206
- would expect from a resolver whose cost is one document walk rather than a hot
207
- inner loop.
197
+ produce byte-identical output before either is timed. Run it with `bun run bench`
198
+ (Bun) or `bun run bench:node` (Node); the shapes are a long `$ref` → `$ref`
199
+ chain, many refs reusing one definition, a cyclic tree, and many distinct
200
+ definitions each used once. Bun and Node land close together on every shape,
201
+ which is what you would expect from a resolver whose cost is one document walk
202
+ rather than a hot inner loop.
208
203
 
209
204
  Memoization overtakes the naive walk only on the **chain** shape, where a long
210
205
  indirection path is expensive to re-resolve and the cache collapses it to one
@@ -214,10 +209,9 @@ the bare inliner is faster — these are small schemas where that one document w
214
209
  dominates. The takeaway is practical: the resolver's per-call floor is a full
215
210
  document traversal, so in a hot loop resolve a document **once** and reuse the
216
211
  result rather than re-resolving. The `reuse-heavy`, `cyclic`, and `wide-distinct`
217
- rows are kept in the table precisely to show that trade honestly rather than
212
+ shapes are kept in the bench precisely to show that trade honestly rather than
218
213
  cherry-picking the one shape the cache wins.
219
214
 
220
215
  Opting into `trackOrigins` (which records where each inlined value came from)
221
- costs nothing measurable on these small schemas, on either runtime: the four
222
- rows land between −9% and +7% on Bun and between −3% and +1% on Node, straddling
223
- zero in both cases, which is run-to-run noise rather than a price.
216
+ costs nothing measurable on these small schemas, on either runtime: the
217
+ differences straddle zero, which is run-to-run noise rather than a price.
@@ -4,6 +4,7 @@ import { dirname, relative as relativePath, resolve as resolvePath, sep } from "
4
4
  import { assertPublicHost } from "./assert-public-host.js";
5
5
  import { childRole } from "./child-role.js";
6
6
  import { bindsAtEvaluationTime, declaresAmbiguousAnchor, inliningKeepsScope, isScopeSensitive } from "./dynamic-scope.js";
7
+ import { getByPointer } from "./get-by-pointer.js";
7
8
  import { isContainedPath } from "./is-contained-path.js";
8
9
  import { isPrivateHost } from "./is-private-host.js";
9
10
  import { DEFAULT_MAX_DEPTH, depthLimitError } from "./max-depth.js";
@@ -387,15 +388,72 @@ const rebaseKeptRefs = (node, from, root, role) => {
387
388
  return node;
388
389
  };
389
390
  const pathToRef = (path) => path.length === 0 ? "#" : `#/${path.map((segment) => escapeSegment(String(segment))).join("/")}`;
390
- const hoistName = (targetLocation, fragment, taken) => {
391
+ const DEFINITION_CONTAINERS = [["$defs"], ["definitions"], ["components", "schemas"]];
392
+ const enclosingDefinitionLength = (pointer) => {
393
+ for (const container of DEFINITION_CONTAINERS) {
394
+ const length = container.length + 1;
395
+ if (pointer.length > length && container.every((key, index) => pointer[index] === key))
396
+ return length;
397
+ }
398
+ return 0;
399
+ };
400
+ const asWritten = (name) => name;
401
+ const asFilename = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
402
+ const NAME_CONTAINERS = ["$defs", "definitions"];
403
+ const POINTER_NAME_CONTAINERS = /* @__PURE__ */ new Set(["$defs", "definitions", "properties"]);
404
+ const generatedName = (pointer) => {
405
+ const segments = pointer.split("/").filter((segment) => segment !== "");
406
+ const named = segments.map((segment, index) => ({
407
+ segment,
408
+ nested: index > 0 && POINTER_NAME_CONTAINERS.has(segments[index - 1])
409
+ })).filter(({ segment }) => !POINTER_NAME_CONTAINERS.has(segment));
410
+ return named.filter((part, index) => part.nested || index === named.length - 1).map(({ segment }) => segment).join("-");
411
+ };
412
+ const internalPointers = (root) => {
413
+ const pointers = /* @__PURE__ */ new Set();
414
+ const seen = /* @__PURE__ */ new WeakSet();
415
+ const stack = [{ value: root, depth: 0 }];
416
+ while (stack.length > 0) {
417
+ const { value, depth } = stack.pop();
418
+ if (value === null || typeof value !== "object" || seen.has(value) || depth > DEFAULT_MAX_DEPTH)
419
+ continue;
420
+ seen.add(value);
421
+ const ref = value.$ref;
422
+ if (typeof ref === "string" && ref.startsWith("#/"))
423
+ pointers.add(ref.slice(1));
424
+ for (const member of Object.values(value))
425
+ stack.push({ value: member, depth: depth + 1 });
426
+ }
427
+ return pointers;
428
+ };
429
+ const nestedDefinitionNames = (map) => {
430
+ const names = [];
431
+ const seen = /* @__PURE__ */ new WeakSet();
432
+ const stack = [{ prefix: "", map, depth: 0 }];
433
+ while (stack.length > 0) {
434
+ const { prefix: parent, map: current, depth } = stack.pop();
435
+ if (seen.has(current) || depth > DEFAULT_MAX_DEPTH)
436
+ continue;
437
+ seen.add(current);
438
+ for (const [key, value] of Object.entries(current)) {
439
+ const name = parent === "" ? key : `${parent}-${key}`;
440
+ names.push(name);
441
+ for (const nested of containedNameMaps(value))
442
+ stack.push({ prefix: name, map: nested, depth: depth + 1 });
443
+ }
444
+ }
445
+ return names;
446
+ };
447
+ const containedNameMaps = (schema) => schema === null || typeof schema !== "object" || Array.isArray(schema) ? [] : NAME_CONTAINERS.map((container) => schema[container]).filter((map) => map !== null && typeof map === "object" && !Array.isArray(map));
448
+ const hoistName = (targetLocation, fragment, taken, keyOf = asWritten) => {
391
449
  const fragmentTail = fragment.split("/").filter(Boolean).pop();
392
450
  const locationTail = targetLocation.split("/").filter(Boolean).pop()?.replace(/\.[a-z0-9]+$/i, "");
393
451
  const raw = fragmentTail || locationTail || "cycle";
394
452
  const sanitized = raw.replace(/[^A-Za-z0-9_.-]/g, "-") || "cycle";
395
453
  let name = sanitized;
396
- for (let n = 2; taken.has(name); n++)
454
+ for (let n = 2; taken.has(keyOf(name)); n++)
397
455
  name = `${sanitized}-${n}`;
398
- taken.add(name);
456
+ taken.add(keyOf(name));
399
457
  return name;
400
458
  };
401
459
  const MAX_DOCUMENTS = 500;
@@ -419,7 +477,9 @@ const resolveRefsFromFile = async (filename, options = {}) => {
419
477
  return null;
420
478
  return `it resolves outside the allowed roots [${localRoots.join(", ")}] (set allowedRoots to permit it)`;
421
479
  };
422
- if (!await loadDoc(rootLocation, docCache, options, errors, deadline, [])) {
480
+ if (options.rootDocument !== void 0) {
481
+ docCache.set(rootLocation, options.rootDocument);
482
+ } else if (!await loadDoc(rootLocation, docCache, options, errors, deadline, [])) {
423
483
  return { resolved: {}, errors };
424
484
  }
425
485
  const registries = /* @__PURE__ */ new Map();
@@ -523,245 +583,452 @@ const resolveRefsFromFile = async (filename, options = {}) => {
523
583
  }
524
584
  };
525
585
  await prefetch();
526
- const origins = options.trackOrigins ? /* @__PURE__ */ new Map() : void 0;
527
- const refCache = /* @__PURE__ */ new Map();
528
- const sensitive = /* @__PURE__ */ new WeakSet();
529
- const ambiguousDynamicAnchors = docCache.size === 1 ? registryFor(rootLocation).ambiguousDynamicAnchors : /* @__PURE__ */ new Set();
530
- const hoists = /* @__PURE__ */ new Map();
531
- const rootDoc = docCache.get(rootLocation);
532
- const rootDefs = rootDoc !== null && typeof rootDoc === "object" && !Array.isArray(rootDoc) ? rootDoc["$defs"] : void 0;
533
- const hoistTaken = new Set(rootDefs !== null && typeof rootDefs === "object" && !Array.isArray(rootDefs) ? Object.keys(rootDefs) : []);
534
- const hoistRefSites = /* @__PURE__ */ new Map();
535
- const keepScopedReference = (obj, keyword, baseLocation, nodeBase, depth, role) => {
536
- const kept = {};
537
- for (const key of Object.keys(obj)) {
538
- const value = obj[key];
539
- assignKey(kept, key, key !== keyword ? resolveAt(value, baseLocation, nodeBase, depth + 1, childRole(role, key)) : keyword === "$ref" && typeof value === "string" ? rebaseKeptRef(value, baseLocation, rootLocation) : value);
540
- }
541
- return kept;
542
- };
543
- const resolveAt = (node, baseLocation, base, depth, role) => {
544
- if (node === null || typeof node !== "object")
545
- return node;
546
- if (role === "value")
547
- return detach(node);
548
- if (depth > maxDepth) {
549
- reportDepthLimit();
550
- return rebaseKeptRefs(detach(node), baseLocation, rootLocation, role);
551
- }
552
- if (Array.isArray(node)) {
553
- const items = node.map((item, index) => resolveAt(item, baseLocation, base, depth + 1, childRole(role, index)));
554
- if (items.some((item) => isScopeSensitive(sensitive, item)))
555
- sensitive.add(items);
556
- return items;
557
- }
558
- const obj = node;
559
- const registry = registryFor(baseLocation);
560
- const isSchema = role !== "schemaMap";
561
- const nodeBase = isSchema && typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
562
- const reference = isSchema ? readReference(obj) : void 0;
563
- if (reference) {
564
- const { keyword, value } = reference;
565
- if (bindsAtEvaluationTime(keyword, value, ambiguousDynamicAnchors)) {
566
- const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
567
- sensitive.add(kept);
568
- return kept;
586
+ const errorsBeforeResolve = errors.length;
587
+ const depthReportedBeforeResolve = depthLimitReported;
588
+ const resolvePass = (inlineOnly) => {
589
+ const unplaceable = /* @__PURE__ */ new Set();
590
+ const origins = options.trackOrigins ? /* @__PURE__ */ new Map() : void 0;
591
+ const refCache = /* @__PURE__ */ new Map();
592
+ const sensitive = /* @__PURE__ */ new WeakSet();
593
+ const ambiguousDynamicAnchors = docCache.size === 1 ? registryFor(rootLocation).ambiguousDynamicAnchors : /* @__PURE__ */ new Set();
594
+ const hoists = /* @__PURE__ */ new Map();
595
+ const rootDoc = docCache.get(rootLocation);
596
+ const nameKey = options.bundle === true ? asFilename : asWritten;
597
+ const definitionNames = (root) => (options.bundle === true ? DEFINITION_CONTAINERS : [["$defs"]]).flatMap((container) => {
598
+ const map = getByPointer(root, `/${container.join("/")}`);
599
+ if (map === null || typeof map !== "object" || Array.isArray(map))
600
+ return [];
601
+ return options.bundle === true ? nestedDefinitionNames(map) : Object.keys(map);
602
+ });
603
+ const rootRefNames = (root) => options.bundle === true ? [...internalPointers(root)].map(generatedName) : [];
604
+ const rootNames = [...definitionNames(rootDoc), ...rootRefNames(rootDoc)];
605
+ const hoistTaken = new Set(rootNames.map(nameKey));
606
+ const hoistRefSites = /* @__PURE__ */ new Map();
607
+ const hoistRefSuffixes = /* @__PURE__ */ new Map();
608
+ const keepScopedReference = (obj, keyword, baseLocation, nodeBase, depth, role) => {
609
+ const kept = {};
610
+ for (const key of Object.keys(obj)) {
611
+ const value = obj[key];
612
+ assignKey(kept, key, key !== keyword ? resolveAt(value, baseLocation, nodeBase, depth + 1, childRole(role, key)) : keyword === "$ref" && typeof value === "string" ? rebaseKeptRef(value, baseLocation, rootLocation) : value);
569
613
  }
570
- let scoped;
571
- let targetLocation = baseLocation;
572
- let fragment = "";
614
+ return kept;
615
+ };
616
+ const lookupTarget = (scoped, keyword, targetLocation, fragment) => {
617
+ if (scoped !== void 0)
618
+ return { found: scoped, base: scoped.base };
619
+ const targetRegistry = registryFor(targetLocation);
620
+ const targetRoot = docCache.get(targetLocation) ?? {};
573
621
  if (keyword === "$recursiveRef") {
574
- fragment = value.startsWith("#") ? value.slice(1) : value;
575
- } else {
576
- const inScope = resolveRefInScope(registry, keyword, value, nodeBase);
577
- if (inScope === "external" || inScope === void 0) {
578
- const parts = splitRef(value);
579
- fragment = parts.fragment;
580
- if (inScope === "external" && parts.uriPart !== "") {
581
- const target = joinLocation(baseLocation, parts.uriPart);
582
- if (target === void 0)
583
- return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
584
- targetLocation = target;
585
- }
586
- } else {
587
- scoped = inScope;
622
+ return { found: resolveFragment(targetRoot, keyword, fragment), base: targetRegistry.rootBase };
623
+ }
624
+ const scopedFragment = resolveRefInScope(targetRegistry, keyword, `#${fragment}`, targetRegistry.rootBase);
625
+ if (scopedFragment !== "external" && scopedFragment !== void 0) {
626
+ return { found: scopedFragment, base: scopedFragment.base };
627
+ }
628
+ return { found: resolveFragment(targetRoot, keyword, fragment), base: targetRegistry.rootBase };
629
+ };
630
+ const placements = [];
631
+ const embeddedIds = /* @__PURE__ */ new Map();
632
+ const contestedIds = /* @__PURE__ */ new Set();
633
+ const uriRefSites = /* @__PURE__ */ new Map();
634
+ const hoistTargets = /* @__PURE__ */ new Map();
635
+ const declaresRootId = (location) => {
636
+ const root = docCache.get(location);
637
+ return root !== null && typeof root === "object" && !Array.isArray(root) && typeof root.$id === "string";
638
+ };
639
+ const absoluteRootId = (location) => {
640
+ const root = docCache.get(location);
641
+ if (root === null || typeof root !== "object" || Array.isArray(root))
642
+ return void 0;
643
+ const id = root["$id"];
644
+ if (typeof id !== "string" || !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(id))
645
+ return void 0;
646
+ return registryFor(location).rootBase;
647
+ };
648
+ const uriFor = (location, base, pointer) => {
649
+ if (base.startsWith(SYNTHETIC_BASE))
650
+ return void 0;
651
+ const registry = registryFor(location);
652
+ const declared = base === registry.rootBase ? absoluteRootId(location) === base : registry.resources.has(base);
653
+ if (!declared)
654
+ return void 0;
655
+ const resourcePointer = base === registry.rootBase ? [] : registry.resources.get(base)?.pointer;
656
+ if (resourcePointer === void 0 || resourcePointer.some((segment, index) => pointer[index] !== segment)) {
657
+ return void 0;
658
+ }
659
+ const inner = pointer.slice(resourcePointer.length);
660
+ return inner.length === 0 ? base : `${base}${pathToRef(inner)}`;
661
+ };
662
+ const cycleTargetUri = (scoped, keyword, targetLocation, fragment) => {
663
+ const { found, base } = lookupTarget(scoped, keyword, targetLocation, fragment);
664
+ return found === void 0 ? void 0 : uriFor(targetLocation, base, found.pointer);
665
+ };
666
+ const hoistFor = (targetLocation, found, targetBase, plain, depth) => {
667
+ const wholeHoisted = plain && hoists.has(`$ref ${targetLocation}#`);
668
+ const split = plain && !wholeHoisted ? enclosingDefinitionLength(found.pointer) : 0;
669
+ const pointer = plain && !wholeHoisted ? split > 0 ? found.pointer.slice(0, split) : found.pointer : [];
670
+ const key = `$ref ${targetLocation}${pathToRef(pointer)}`;
671
+ const name = hoists.get(key) ?? hoistName(targetLocation, pathToRef(pointer).slice(1), hoistTaken, nameKey);
672
+ hoists.set(key, name);
673
+ hoistTargets.set(key, { location: targetLocation, pointer });
674
+ if (!refCache.has(key)) {
675
+ refCache.set(key, CYCLE);
676
+ const whole = pointer.length === found.pointer.length;
677
+ const value = whole ? found.value : getByPointer(docCache.get(targetLocation), pathToRef(pointer).slice(1));
678
+ const base = whole ? targetBase : registryFor(targetLocation).rootBase;
679
+ const resolved2 = resolveAt(value, targetLocation, base, depth + 1, roleAtPath(pointer));
680
+ refCache.set(key, { value: resolved2, pointer, base });
681
+ if (origins && resolved2 !== null && typeof resolved2 === "object" && !origins.has(resolved2)) {
682
+ origins.set(resolved2, { location: targetLocation, pointer });
588
683
  }
589
684
  }
590
- const cacheKey = scoped !== void 0 ? `${keyword} ${baseLocation} ${nodeBase} ${value}` : `${keyword} ${targetLocation}#${fragment}`;
591
- let resolved2;
592
- let pointer;
593
- let targetBase = nodeBase;
594
- const cached = refCache.get(cacheKey);
595
- if (cached === CYCLE) {
596
- let keptRef;
597
- let hoisted = false;
598
- if (scoped !== void 0 && baseLocation === rootLocation) {
599
- keptRef = pathToRef(scoped.pointer);
600
- } else if (scoped === void 0 && targetLocation === rootLocation) {
601
- keptRef = `#${fragment}`;
602
- } else {
603
- let name = hoists.get(cacheKey);
604
- if (name === void 0) {
605
- name = hoistName(targetLocation, fragment, hoistTaken);
606
- hoists.set(cacheKey, name);
607
- }
608
- hoisted = true;
609
- keptRef = `#/$defs/${name}`;
685
+ return { key, name, pointer };
686
+ };
687
+ const bundleReference = (obj, value, scoped, targetLocation, fragment, cacheKey, refKey, baseLocation, nodeBase, depth, role) => {
688
+ const placedIn = placements.at(-1);
689
+ const siteInRoot = placedIn === void 0 && nodeBase === registryFor(baseLocation).rootBase;
690
+ const intoRoot = scoped !== void 0 ? baseLocation === rootLocation : targetLocation === rootLocation;
691
+ const plain = !intoRoot && registryFor(targetLocation).bases.size === 0 && !declaresRootId(targetLocation);
692
+ const embeddedId = intoRoot || plain ? void 0 : absoluteRootId(targetLocation);
693
+ if (!intoRoot && !plain) {
694
+ if (embeddedId === void 0 || inlineOnly.has(targetLocation))
695
+ return void 0;
696
+ const claimedBy = embeddedIds.get(embeddedId);
697
+ if (registryFor(rootLocation).resources.has(embeddedId) || (claimedBy ?? targetLocation) !== targetLocation) {
698
+ if (claimedBy !== void 0 && claimedBy !== targetLocation)
699
+ contestedIds.add(embeddedId);
700
+ return void 0;
610
701
  }
611
- const kept = {};
612
- for (const key of Object.keys(obj)) {
613
- if (key === keyword)
614
- continue;
615
- assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
702
+ }
703
+ if (plain && !siteInRoot)
704
+ return void 0;
705
+ if (refCache.get(cacheKey) === MISSING || refCache.get(refKey) === MISSING)
706
+ return keepScopedReference(obj, "$ref", baseLocation, nodeBase, depth, role);
707
+ const { found, base: targetBase } = lookupTarget(scoped, "$ref", targetLocation, fragment);
708
+ const targetLoaded = docCache.has(targetLocation) && !unloadable.has(targetLocation);
709
+ if (found === void 0 || !targetLoaded) {
710
+ if (targetLoaded) {
711
+ errors.push({
712
+ message: `Cannot resolve $ref "${value}"`,
713
+ path: baseLocation === rootLocation ? refPathAt("$ref", value) : []
714
+ });
616
715
  }
617
- assignKey(kept, "$ref", keptRef);
618
- if (hoisted)
619
- hoistRefSites.set(kept, cacheKey);
620
- return kept;
716
+ refCache.set(cacheKey, MISSING);
717
+ refCache.set(refKey, MISSING);
718
+ return keepScopedReference(obj, "$ref", baseLocation, nodeBase, depth, role);
621
719
  }
622
- if (cached === MISSING)
623
- return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
624
- if (cached !== void 0) {
625
- resolved2 = cached.value;
626
- pointer = cached.pointer;
627
- targetBase = cached.base;
628
- } else {
629
- refCache.set(cacheKey, CYCLE);
630
- let found;
631
- if (scoped !== void 0) {
632
- found = scoped;
633
- targetBase = scoped.base;
720
+ const sameResource = placedIn !== void 0 && placedIn === nodeBase && nodeBase === targetBase && baseLocation === targetLocation && (scoped !== void 0 || splitRef(value).uriPart === "");
721
+ const byUri = !sameResource && (!siteInRoot || embeddedId !== void 0);
722
+ const uri = byUri ? uriFor(targetLocation, targetBase, found.pointer) : void 0;
723
+ if (byUri && uri === void 0)
724
+ return void 0;
725
+ if (embeddedId !== void 0)
726
+ embeddedIds.set(embeddedId, targetLocation);
727
+ const hoist = intoRoot ? void 0 : hoistFor(targetLocation, found, targetBase, plain, depth);
728
+ const named = hoist !== void 0 && plain && siteInRoot;
729
+ const suffix = named ? pathToRef(found.pointer.slice(hoist.pointer.length)).slice(1) : "";
730
+ const target = uri ?? (sameResource ? value : named ? `#/$defs/${hoist.name}${suffix}` : scoped !== void 0 || value.startsWith("#") ? value : pathToRef(found.pointer));
731
+ const kept = {};
732
+ for (const key of Object.keys(obj)) {
733
+ assignKey(kept, key, key === "$ref" ? target : resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
734
+ }
735
+ if (named) {
736
+ hoistRefSites.set(kept, hoist.key);
737
+ if (suffix !== "")
738
+ hoistRefSuffixes.set(kept, suffix);
739
+ }
740
+ if (siteInRoot && hoist !== void 0 && embeddedId !== void 0) {
741
+ uriRefSites.set(kept, { key: hoist.key, id: embeddedId, suffix: pathToRef(found.pointer).slice(1) });
742
+ }
743
+ if (Object.values(kept).some((child) => isScopeSensitive(sensitive, child)) || declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors)) {
744
+ sensitive.add(kept);
745
+ }
746
+ return kept;
747
+ };
748
+ const resolveAt = (node, baseLocation, base, depth, role) => {
749
+ const entersResource = options.bundle === true && role !== "value" && role !== "schemaMap" && node !== null && typeof node === "object" && !Array.isArray(node) && typeof node["$id"] === "string" && // Draft-07's `#Foo` names a location, not a resource, wherever it lands.
750
+ splitRef(node["$id"]).uriPart !== "" && !(depth === 0 && baseLocation === rootLocation);
751
+ const nodeBase = entersResource ? baseOfNode(registryFor(baseLocation), node, base) : base;
752
+ if (!entersResource || nodeBase === (placements.at(-1) ?? registryFor(rootLocation).rootBase)) {
753
+ return resolveNode(node, baseLocation, base, depth, role);
754
+ }
755
+ placements.push(nodeBase);
756
+ try {
757
+ return resolveNode(node, baseLocation, base, depth, role);
758
+ } finally {
759
+ placements.pop();
760
+ }
761
+ };
762
+ const resolveNode = (node, baseLocation, base, depth, role) => {
763
+ if (node === null || typeof node !== "object")
764
+ return node;
765
+ if (role === "value")
766
+ return detach(node);
767
+ if (depth > maxDepth) {
768
+ reportDepthLimit();
769
+ return rebaseKeptRefs(detach(node), baseLocation, rootLocation, role);
770
+ }
771
+ if (Array.isArray(node)) {
772
+ const items = node.map((item, index) => resolveAt(item, baseLocation, base, depth + 1, childRole(role, index)));
773
+ if (items.some((item) => isScopeSensitive(sensitive, item)))
774
+ sensitive.add(items);
775
+ return items;
776
+ }
777
+ const obj = node;
778
+ const registry = registryFor(baseLocation);
779
+ const isSchema = role !== "schemaMap";
780
+ const nodeBase = isSchema && typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
781
+ const reference = isSchema ? readReference(obj) : void 0;
782
+ if (reference) {
783
+ const { keyword, value } = reference;
784
+ if (bindsAtEvaluationTime(keyword, value, ambiguousDynamicAnchors)) {
785
+ const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
786
+ sensitive.add(kept);
787
+ return kept;
788
+ }
789
+ let scoped;
790
+ let targetLocation = baseLocation;
791
+ let fragment = "";
792
+ if (keyword === "$recursiveRef") {
793
+ fragment = value.startsWith("#") ? value.slice(1) : value;
634
794
  } else {
635
- const targetRegistry = registryFor(targetLocation);
636
- const targetRoot = docCache.get(targetLocation) ?? {};
637
- if (keyword === "$recursiveRef") {
638
- found = resolveFragment(targetRoot, keyword, fragment);
639
- targetBase = targetRegistry.rootBase;
640
- } else {
641
- const scopedFragment = resolveRefInScope(targetRegistry, keyword, `#${fragment}`, targetRegistry.rootBase);
642
- if (scopedFragment !== "external" && scopedFragment !== void 0) {
643
- found = scopedFragment;
644
- targetBase = scopedFragment.base;
645
- } else {
646
- found = resolveFragment(targetRoot, keyword, fragment);
647
- targetBase = targetRegistry.rootBase;
795
+ const inScope = resolveRefInScope(registry, keyword, value, nodeBase);
796
+ if (inScope === "external" || inScope === void 0) {
797
+ const parts = splitRef(value);
798
+ fragment = parts.fragment;
799
+ if (inScope === "external" && parts.uriPart !== "") {
800
+ const target = joinLocation(baseLocation, parts.uriPart);
801
+ if (target === void 0)
802
+ return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
803
+ targetLocation = target;
648
804
  }
805
+ } else {
806
+ scoped = inScope;
649
807
  }
650
808
  }
651
- const targetLoaded = docCache.has(targetLocation) && !unloadable.has(targetLocation);
652
- if (found === void 0 || !targetLoaded) {
653
- if (targetLoaded) {
654
- errors.push({
655
- message: `Cannot resolve ${keyword} "${value}"`,
656
- // `refPathAt` indexes the *root* document only, so it can only
657
- // speak for a ref that lives there. Called unguarded it answered
658
- // for a ref in a sub-document by handing back the position of an
659
- // identical ref in the root — pointing a diagnostic at a line
660
- // that is not the offending one. The prefetch loop above already
661
- // guards this the same way; an empty path means "no position to
662
- // give", which is honest.
663
- path: baseLocation === rootLocation ? refPathAt(keyword, value) : []
664
- });
809
+ const refKey = scoped !== void 0 ? `${keyword} ${baseLocation} ${nodeBase} ${value}` : `${keyword} ${targetLocation}#${fragment}`;
810
+ const placedIn = options.bundle === true ? placements.at(-1) : void 0;
811
+ const cacheKey = placedIn === void 0 ? refKey : `${refKey} (in ${placedIn})`;
812
+ if (options.bundle === true && keyword === "$ref") {
813
+ const bundled = bundleReference(obj, value, scoped, targetLocation, fragment, cacheKey, refKey, baseLocation, nodeBase, depth, role);
814
+ if (bundled !== void 0)
815
+ return bundled;
816
+ }
817
+ let resolved2;
818
+ let pointer;
819
+ let targetBase = nodeBase;
820
+ const cached = refCache.get(cacheKey) ?? (refCache.get(refKey) === MISSING ? MISSING : void 0);
821
+ if (cached === CYCLE) {
822
+ const cycleUri = placedIn === void 0 ? void 0 : cycleTargetUri(scoped, keyword, targetLocation, fragment);
823
+ if (placedIn !== void 0 && cycleUri === void 0) {
824
+ const innermost = placements.findLast((base2) => embeddedIds.has(base2));
825
+ if (innermost !== void 0)
826
+ unplaceable.add(embeddedIds.get(innermost));
827
+ }
828
+ let keptRef;
829
+ let hoisted = false;
830
+ if (cycleUri !== void 0) {
831
+ keptRef = cycleUri;
832
+ } else if (scoped !== void 0 && baseLocation === rootLocation) {
833
+ keptRef = pathToRef(scoped.pointer);
834
+ } else if (scoped === void 0 && targetLocation === rootLocation) {
835
+ keptRef = `#${fragment}`;
836
+ } else {
837
+ let name = hoists.get(cacheKey);
838
+ if (name === void 0) {
839
+ name = hoistName(targetLocation, fragment, hoistTaken, nameKey);
840
+ hoists.set(cacheKey, name);
841
+ }
842
+ hoisted = true;
843
+ keptRef = `#/$defs/${name}`;
844
+ }
845
+ const kept = {};
846
+ for (const key of Object.keys(obj)) {
847
+ if (key === keyword)
848
+ continue;
849
+ assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
665
850
  }
666
- refCache.set(cacheKey, MISSING);
851
+ assignKey(kept, "$ref", keptRef);
852
+ if (hoisted)
853
+ hoistRefSites.set(kept, cacheKey);
854
+ return kept;
855
+ }
856
+ if (cached === MISSING)
667
857
  return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
858
+ if (cached !== void 0) {
859
+ resolved2 = cached.value;
860
+ pointer = cached.pointer;
861
+ targetBase = cached.base;
862
+ } else {
863
+ refCache.set(cacheKey, CYCLE);
864
+ const lookup = lookupTarget(scoped, keyword, targetLocation, fragment);
865
+ const found = lookup.found;
866
+ targetBase = lookup.base;
867
+ const targetLoaded = docCache.has(targetLocation) && !unloadable.has(targetLocation);
868
+ if (found === void 0 || !targetLoaded) {
869
+ if (targetLoaded) {
870
+ errors.push({
871
+ message: `Cannot resolve ${keyword} "${value}"`,
872
+ // `refPathAt` indexes the *root* document only, so it can only
873
+ // speak for a ref that lives there. Called unguarded it answered
874
+ // for a ref in a sub-document by handing back the position of an
875
+ // identical ref in the root — pointing a diagnostic at a line
876
+ // that is not the offending one. The prefetch loop above already
877
+ // guards this the same way; an empty path means "no position to
878
+ // give", which is honest.
879
+ path: baseLocation === rootLocation ? refPathAt(keyword, value) : []
880
+ });
881
+ }
882
+ refCache.set(cacheKey, MISSING);
883
+ refCache.set(refKey, MISSING);
884
+ return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
885
+ }
886
+ pointer = found?.pointer ?? [];
887
+ resolved2 = resolveAt(found?.value, targetLocation, targetBase, depth + 1, roleAtPath(pointer));
888
+ refCache.set(cacheKey, { value: resolved2, pointer, base: targetBase });
889
+ if (origins && resolved2 !== null && typeof resolved2 === "object" && !origins.has(resolved2)) {
890
+ origins.set(resolved2, { location: targetLocation, pointer });
891
+ }
668
892
  }
669
- pointer = found?.pointer ?? [];
670
- resolved2 = resolveAt(found?.value, targetLocation, targetBase, depth + 1, roleAtPath(pointer));
671
- refCache.set(cacheKey, { value: resolved2, pointer, base: targetBase });
672
- if (origins && resolved2 !== null && typeof resolved2 === "object" && !origins.has(resolved2)) {
673
- origins.set(resolved2, { location: targetLocation, pointer });
893
+ if (isScopeSensitive(sensitive, resolved2) && !inliningKeepsScope(resolved2, nodeBase, targetBase)) {
894
+ const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
895
+ sensitive.add(kept);
896
+ return kept;
674
897
  }
898
+ const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
899
+ if (siblingKeys.length === 0)
900
+ return resolved2;
901
+ const siblings = {};
902
+ let siblingIsSensitive = false;
903
+ for (const key of siblingKeys) {
904
+ const child = resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key));
905
+ assignKey(siblings, key, child);
906
+ if (isScopeSensitive(sensitive, child))
907
+ siblingIsSensitive = true;
908
+ }
909
+ const inlineIsSensitive = siblingIsSensitive || isScopeSensitive(sensitive, resolved2) || declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors);
910
+ if (siblingKeys.every((key) => ANNOTATION_ONLY_SIBLINGS.has(key))) {
911
+ if (resolved2 !== null && typeof resolved2 === "object" && !Array.isArray(resolved2)) {
912
+ const overridden = {};
913
+ for (const key of Object.keys(resolved2)) {
914
+ assignKey(overridden, key, resolved2[key]);
915
+ }
916
+ for (const key of Object.keys(siblings))
917
+ assignKey(overridden, key, siblings[key]);
918
+ const hoistOf = hoistRefSites.get(resolved2);
919
+ if (hoistOf !== void 0)
920
+ hoistRefSites.set(overridden, hoistOf);
921
+ const suffixOf = hoistRefSuffixes.get(resolved2);
922
+ if (suffixOf !== void 0)
923
+ hoistRefSuffixes.set(overridden, suffixOf);
924
+ const uriSite = uriRefSites.get(resolved2);
925
+ if (uriSite !== void 0)
926
+ uriRefSites.set(overridden, uriSite);
927
+ if (origins && !origins.has(overridden))
928
+ origins.set(overridden, { location: targetLocation, pointer });
929
+ if (inlineIsSensitive)
930
+ sensitive.add(overridden);
931
+ return overridden;
932
+ }
933
+ return resolved2;
934
+ }
935
+ const existingAllOf = Array.isArray(siblings["allOf"]) ? siblings["allOf"] : [];
936
+ const merged = { ...siblings, allOf: [...existingAllOf, resolved2] };
937
+ if (origins && !origins.has(merged))
938
+ origins.set(merged, { location: targetLocation, pointer });
939
+ if (inlineIsSensitive)
940
+ sensitive.add(merged);
941
+ return merged;
675
942
  }
676
- if (isScopeSensitive(sensitive, resolved2) && !inliningKeepsScope(resolved2, nodeBase, targetBase)) {
677
- const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
678
- sensitive.add(kept);
679
- return kept;
680
- }
681
- const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
682
- if (siblingKeys.length === 0)
683
- return resolved2;
684
- const siblings = {};
685
- let siblingIsSensitive = false;
686
- for (const key of siblingKeys) {
943
+ const result = {};
944
+ for (const key of Object.keys(obj)) {
687
945
  const child = resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key));
688
- assignKey(siblings, key, child);
946
+ assignKey(result, key, child);
689
947
  if (isScopeSensitive(sensitive, child))
690
- siblingIsSensitive = true;
948
+ sensitive.add(result);
691
949
  }
692
- const inlineIsSensitive = siblingIsSensitive || isScopeSensitive(sensitive, resolved2) || declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors);
693
- if (siblingKeys.every((key) => ANNOTATION_ONLY_SIBLINGS.has(key))) {
694
- if (resolved2 !== null && typeof resolved2 === "object" && !Array.isArray(resolved2)) {
695
- const overridden = {};
696
- for (const key of Object.keys(resolved2)) {
697
- assignKey(overridden, key, resolved2[key]);
698
- }
699
- for (const key of Object.keys(siblings))
700
- assignKey(overridden, key, siblings[key]);
701
- const hoistOf = hoistRefSites.get(resolved2);
702
- if (hoistOf !== void 0)
703
- hoistRefSites.set(overridden, hoistOf);
704
- if (origins && !origins.has(overridden))
705
- origins.set(overridden, { location: targetLocation, pointer });
706
- if (inlineIsSensitive)
707
- sensitive.add(overridden);
708
- return overridden;
950
+ if (isSchema && declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors))
951
+ sensitive.add(result);
952
+ return result;
953
+ };
954
+ const rootRegistry = registryFor(rootLocation);
955
+ const resolved = resolveAt(docCache.get(rootLocation), rootLocation, rootRegistry.rootBase, 0, "schema");
956
+ if (hoists.size > 0) {
957
+ if (resolved !== null && typeof resolved === "object" && !Array.isArray(resolved)) {
958
+ const container = resolved;
959
+ const defs = container["$defs"] !== null && typeof container["$defs"] === "object" && !Array.isArray(container["$defs"]) ? container["$defs"] : {};
960
+ const insideWhole = /* @__PURE__ */ new Map();
961
+ for (const [key, { location, pointer }] of hoistTargets) {
962
+ const whole = `$ref ${location}#`;
963
+ if (pointer.length > 0 && hoists.has(whole))
964
+ insideWhole.set(key, { whole, suffix: pathToRef(pointer).slice(1) });
965
+ }
966
+ const taken = new Set([...Object.keys(defs), ...definitionNames(container), ...rootNames].map(nameKey));
967
+ const usedSuffixes = /* @__PURE__ */ new Map();
968
+ for (const [node, cacheKey] of hoistRefSites) {
969
+ const redirect = insideWhole.get(cacheKey);
970
+ const key = redirect?.whole ?? cacheKey;
971
+ const suffix = `${redirect?.suffix ?? ""}${hoistRefSuffixes.get(node) ?? ""}`;
972
+ if (suffix !== "")
973
+ usedSuffixes.set(key, (usedSuffixes.get(key) ?? /* @__PURE__ */ new Set()).add(suffix));
974
+ }
975
+ const finalNames = /* @__PURE__ */ new Map();
976
+ for (const [cacheKey, name] of hoists) {
977
+ if (insideWhole.has(cacheKey))
978
+ continue;
979
+ const cached = refCache.get(cacheKey);
980
+ const value = cached !== void 0 && cached !== CYCLE && cached !== MISSING ? cached.value : void 0;
981
+ const nested = options.bundle === true ? containedNameMaps(value).flatMap((map) => nestedDefinitionNames(map)) : [];
982
+ const claims = (candidate) => [
983
+ candidate,
984
+ ...options.bundle === true ? [
985
+ ...nested.map((name2) => `${candidate}-${name2}`),
986
+ ...[...usedSuffixes.get(cacheKey) ?? []].map((suffix) => generatedName(`/$defs/${candidate}${suffix}`))
987
+ ] : []
988
+ ].map(nameKey);
989
+ let unique = name;
990
+ for (let n = 2; claims(unique).some((claim) => taken.has(claim)); n++)
991
+ unique = `${name}-${n}`;
992
+ for (const claim of claims(unique))
993
+ taken.add(claim);
994
+ finalNames.set(cacheKey, unique);
995
+ }
996
+ for (const [node, { key, id, suffix }] of uriRefSites) {
997
+ if (contestedIds.has(id))
998
+ assignKey(node, "$ref", `#/$defs/${finalNames.get(key)}${suffix}`);
999
+ }
1000
+ for (const [node, cacheKey] of hoistRefSites) {
1001
+ const redirect = insideWhole.get(cacheKey);
1002
+ const name = finalNames.get(redirect?.whole ?? cacheKey);
1003
+ assignKey(node, "$ref", `#/$defs/${name}${redirect?.suffix ?? ""}${hoistRefSuffixes.get(node) ?? ""}`);
709
1004
  }
710
- return resolved2;
1005
+ for (const [cacheKey] of hoists) {
1006
+ if (insideWhole.has(cacheKey))
1007
+ continue;
1008
+ const cached = refCache.get(cacheKey);
1009
+ const attachable = cached !== void 0 && cached !== CYCLE && cached !== MISSING;
1010
+ assignKey(defs, finalNames.get(cacheKey), attachable ? cached.value ?? {} : {});
1011
+ }
1012
+ assignKey(container, "$defs", defs);
1013
+ } else {
1014
+ errors.push({
1015
+ message: "Cannot attach hoisted cycle definitions: the resolved root document is not an object",
1016
+ path: []
1017
+ });
711
1018
  }
712
- const existingAllOf = Array.isArray(siblings["allOf"]) ? siblings["allOf"] : [];
713
- const merged = { ...siblings, allOf: [...existingAllOf, resolved2] };
714
- if (origins && !origins.has(merged))
715
- origins.set(merged, { location: targetLocation, pointer });
716
- if (inlineIsSensitive)
717
- sensitive.add(merged);
718
- return merged;
719
- }
720
- const result = {};
721
- for (const key of Object.keys(obj)) {
722
- const child = resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key));
723
- assignKey(result, key, child);
724
- if (isScopeSensitive(sensitive, child))
725
- sensitive.add(result);
726
1019
  }
727
- if (isSchema && declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors))
728
- sensitive.add(result);
729
- return result;
1020
+ return { result: origins ? { resolved, errors, origins } : { resolved, errors }, unplaceable };
730
1021
  };
731
- const rootRegistry = registryFor(rootLocation);
732
- const resolved = resolveAt(docCache.get(rootLocation), rootLocation, rootRegistry.rootBase, 0, "schema");
733
- if (hoists.size > 0) {
734
- if (resolved !== null && typeof resolved === "object" && !Array.isArray(resolved)) {
735
- const container = resolved;
736
- const defs = container["$defs"] !== null && typeof container["$defs"] === "object" && !Array.isArray(container["$defs"]) ? container["$defs"] : {};
737
- const taken = new Set(Object.keys(defs));
738
- const finalNames = /* @__PURE__ */ new Map();
739
- for (const [cacheKey, name] of hoists) {
740
- let unique = name;
741
- for (let n = 2; taken.has(unique); n++)
742
- unique = `${name}-${n}`;
743
- taken.add(unique);
744
- finalNames.set(cacheKey, unique);
745
- }
746
- for (const [node, cacheKey] of hoistRefSites) {
747
- const name = finalNames.get(cacheKey);
748
- if (name !== void 0)
749
- assignKey(node, "$ref", `#/$defs/${name}`);
750
- }
751
- for (const [cacheKey] of hoists) {
752
- const cached = refCache.get(cacheKey);
753
- const attachable = cached !== void 0 && cached !== CYCLE && cached !== MISSING;
754
- assignKey(defs, finalNames.get(cacheKey), attachable ? cached.value ?? {} : {});
755
- }
756
- assignKey(container, "$defs", defs);
757
- } else {
758
- errors.push({
759
- message: "Cannot attach hoisted cycle definitions: the resolved root document is not an object",
760
- path: []
761
- });
762
- }
763
- }
764
- return origins ? { resolved, errors, origins } : { resolved, errors };
1022
+ const settle = (inlineOnly) => {
1023
+ const { result, unplaceable } = resolvePass(inlineOnly);
1024
+ const more = [...unplaceable].filter((location) => !inlineOnly.has(location));
1025
+ if (more.length === 0)
1026
+ return result;
1027
+ errors.length = errorsBeforeResolve;
1028
+ depthLimitReported = depthReportedBeforeResolve;
1029
+ return settle(/* @__PURE__ */ new Set([...inlineOnly, ...more]));
1030
+ };
1031
+ return settle(/* @__PURE__ */ new Set());
765
1032
  };
766
1033
  export {
767
1034
  clearRemoteCache,
package/dist/types.d.ts CHANGED
@@ -128,6 +128,23 @@ export type ResolveOptions = {
128
128
  * ```
129
129
  */
130
130
  parse?: (content: string, location: string) => unknown;
131
+ /**
132
+ * The root document's already-parsed content. When set, the file you named
133
+ * is neither read nor handed to `parse` — this value stands in for it — but
134
+ * its location still anchors everything else: relative `$ref`s resolve
135
+ * against it, the default `allowedRoots` is its folder, and `origins` name it.
136
+ *
137
+ * For callers that have parsed the root already (a linter, a code generator)
138
+ * and would otherwise pay to read and parse a large document twice. It is
139
+ * only read, never written, so the caller keeps ownership of the tree; the
140
+ * resolved result never shares an object with it.
141
+ *
142
+ * ```ts
143
+ * const document = parseYaml(await readFile(path, 'utf8'))
144
+ * resolveRefsFromFile(path, { rootDocument: document, parse: parseYamlOrJson })
145
+ * ```
146
+ */
147
+ rootDocument?: unknown;
131
148
  /**
132
149
  * Record a per-node origin map on the result (`origins`). For every object or
133
150
  * array inlined in place of a `$ref`, the map records the document and in-file
@@ -135,6 +152,36 @@ export type ResolveOptions = {
135
152
  * to their source without re-walking the `$ref` chain. Defaults to `false`.
136
153
  */
137
154
  trackOrigins?: boolean;
155
+ /**
156
+ * Bundle instead of inlining: pull every other document a `$ref` reaches into
157
+ * the root's `$defs` and point the ref there, so the output is one
158
+ * self-contained document whose `$ref`s are all internal. A ref into the root
159
+ * document is kept as written, and each target is hoisted once however many
160
+ * refs name it. A code generator wants this: a shared schema stays one named
161
+ * definition rather than an inline copy at every use, which on schemas that
162
+ * reference each other in layers is exponential in the output's size.
163
+ *
164
+ * A document that declares an absolute `$id` at its root is embedded whole
165
+ * under the root's `$defs` with that `$id` kept — how JSON Schema bundles a
166
+ * resource — so the `#/...` pointers written inside it still read against it,
167
+ * and every ref to something in it names it by that URI: a `#/...` pointer from
168
+ * the root into a resource with its own `$id` is one JSON Schema does not
169
+ * promise to resolve. (When a second document claims the same `$id`, refs from
170
+ * the root's own resource fall back to the hoist's pointer, which names one.)
171
+ * Inside any embedded resource `#` names that resource, so a ref there is kept
172
+ * as written when it is a `#...` pointer (or resolves by `$id`) to a target in
173
+ * the same resource, names its target by absolute URI otherwise, and is
174
+ * inlined when the target has no URI (a document without an `$id`). A target
175
+ * with no URI that is part of a cycle cannot be inlined, and has no name that
176
+ * reads the same from inside the resource, so a document whose resource meets
177
+ * one is inlined instead, as without this option. (A resource nested in the
178
+ * root document cannot be inlined; there the ref is the root-relative pointer
179
+ * inlining has always written.) A document whose `$id` is relative, or whose
180
+ * `$id` another bundled document already claims, is inlined.
181
+ * `$dynamicRef` and `$recursiveRef` are resolved as without this option.
182
+ * Defaults to `false`.
183
+ */
184
+ bundle?: boolean;
138
185
  /**
139
186
  * Extra HTTP headers sent with remote `$ref` requests (e.g. an `Authorization`
140
187
  * token for a private schema registry) — a static record, or a function
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/resolve-refs",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "Resolve and inline JSON Schema / OpenAPI $refs — internal, cross-file, and remote — with session caching and a default-deny SSRF guard.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -55,6 +55,6 @@
55
55
  }
56
56
  },
57
57
  "devDependencies": {
58
- "@amritk/runtime-validators": "^0.15.1"
58
+ "@amritk/runtime-validators": "^0.15.2"
59
59
  }
60
60
  }