@amritk/resolve-refs 0.6.0 → 0.7.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/AI.md CHANGED
@@ -30,6 +30,11 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
30
30
  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
+ Each error's `path` is where the offending reference was written in the
34
+ document you passed in, ending in the keyword (`['properties','p','$ref']`),
35
+ so you can point a diagnostic straight at it. It is empty when there is
36
+ nowhere to point — a budget the whole resolve overran, or a reference living
37
+ in some other document.
33
38
  3. **Default-deny SSRF guard.** Remote refs to loopback / private / link-local /
34
39
  `169.254.169.254` / metadata hosts by name (`metadata.google.internal`,
35
40
  `*.internal`) are refused unless `allowPrivateHosts: true` or an explicit
package/README.md CHANGED
@@ -75,6 +75,11 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
75
75
  Errors (a missing file, a refused host, a refused path, a bad URL, a document too
76
76
  deeply nested) are collected on `result.errors` rather than thrown; the
77
77
  corresponding ref resolves to `{}` so the rest of the document still resolves.
78
+ Each error carries the `path` to the reference that caused it — a path in the
79
+ document you named, ending in the keyword (`['properties', 'pet', '$ref']`) — so
80
+ a caller can anchor a diagnostic on the `$ref` a reader has to fix. It is empty
81
+ when there is nowhere to point: a budget the resolve as a whole overran, or a
82
+ reference written in some other document.
78
83
 
79
84
  `clearRemoteCache()` drops every cached remote document — useful in tests or
80
85
  long-lived sessions where remote schemas may change. Pass a URL
@@ -186,14 +191,14 @@ registry, no scoping, no diagnostics — and re-resolves each ref on every
186
191
  encounter, so the gap is the production resolver's *total* per-call cost against
187
192
  the cheapest thing that produces the same inlined shape. Both are asserted to
188
193
  produce byte-identical output before either is timed. Representative numbers
189
- (Bun 1.3, Linux x64 — your hardware will differ, run `bun run bench` yourself):
194
+ (Bun 1.4, Linux x64 — your hardware will differ, run `bun run bench` yourself):
190
195
 
191
196
  | schema | cached | naive | speedup |
192
197
  |:---|---:|---:|---:|
193
- | chain (40 `$ref` → `$ref` links) | ~2.7k ops/s | ~0.77k ops/s | **~3.6×** |
194
- | reuse-heavy (50 refs → 1 def) | ~4.2k ops/s | ~8.9k ops/s | ~0.47× |
195
- | cyclic tree | ~32k ops/s | ~99k ops/s | ~0.32× |
196
- | wide-distinct (60 defs, each used once) | ~2.3k ops/s | ~7.7k ops/s | ~0.29× |
198
+ | chain (40 `$ref` → `$ref` links) | ~5.4k ops/s | ~1.2k ops/s | **~4.5×** |
199
+ | reuse-heavy (50 refs → 1 def) | ~8.2k ops/s | ~12.6k ops/s | ~0.65× |
200
+ | cyclic tree | ~47k ops/s | ~210k ops/s | ~0.22× |
201
+ | wide-distinct (60 defs, each used once) | ~3.4k ops/s | ~10.2k ops/s | ~0.34× |
197
202
 
198
203
  Memoization overtakes the naive walk only on the **chain** shape, where a long
199
204
  indirection path is expensive to re-resolve and the cache collapses it to one
@@ -206,5 +211,6 @@ result rather than re-resolving. The `reuse-heavy`, `cyclic`, and `wide-distinct
206
211
  rows are kept in the table precisely to show that trade honestly rather than
207
212
  cherry-picking the one shape the cache wins.
208
213
 
209
- Opting into `trackOrigins` (which records where each inlined value came from) adds
210
- roughly **0–15%** on top, within run-to-run noise on these small schemas.
214
+ Opting into `trackOrigins` (which records where each inlined value came from)
215
+ costs nothing measurable on these small schemas: the four rows land between −24%
216
+ and +16%, straddling zero, which is run-to-run noise rather than a price.
@@ -1,4 +1,4 @@
1
- const VALUE_KEYWORDS = /* @__PURE__ */ new Set(["enum", "const", "default", "examples"]);
1
+ const VALUE_KEYWORDS = /* @__PURE__ */ new Set(["enum", "const", "default", "examples", "example"]);
2
2
  const SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([
3
3
  "properties",
4
4
  "patternProperties",
@@ -1,8 +1,9 @@
1
- import { baseAfterId, splitFragment } from "./resource-registry.js";
1
+ import { baseAfterId } from "./resource-registry.js";
2
+ import { splitRef } from "./split-ref.js";
2
3
  const bindsAtEvaluationTime = (keyword, ref, ambiguousAnchors) => {
3
4
  if (keyword !== "$dynamicRef")
4
5
  return false;
5
- const { fragment } = splitFragment(ref);
6
+ const { fragment } = splitRef(ref);
6
7
  if (fragment === "" || fragment.startsWith("/"))
7
8
  return false;
8
9
  return ambiguousAnchors.has(fragment);
@@ -9,6 +9,12 @@ import type { JsonPath } from './types.js';
9
9
  * not `obj[1]`). A bare `''` or `'/'` is the empty path.
10
10
  */
11
11
  export declare const pointerToPath: (pointer: string) => JsonPath;
12
+ /**
13
+ * Whether a reference fragment is a JSON Pointer rather than a plain-name
14
+ * anchor. RFC 6901 pointers are empty or start with `/`; anything else names an
15
+ * `$anchor`.
16
+ */
17
+ export declare const isPointerFragment: (fragment: string) => boolean;
12
18
  /**
13
19
  * Walks a JSON Pointer string (RFC 6901) to the value it points to within
14
20
  * `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
@@ -14,6 +14,7 @@ const pointerToPath = (pointer) => {
14
14
  return /^(0|[1-9]\d*)$/.test(decoded) ? Number(decoded) : decoded;
15
15
  });
16
16
  };
17
+ const isPointerFragment = (fragment) => fragment === "" || fragment.startsWith("/");
17
18
  const getByPointer = (root, pointer) => {
18
19
  if (pointer === "" || pointer === "/")
19
20
  return root;
@@ -31,5 +32,6 @@ const getByPointer = (root, pointer) => {
31
32
  };
32
33
  export {
33
34
  getByPointer,
35
+ isPointerFragment,
34
36
  pointerToPath
35
37
  };
@@ -16,6 +16,8 @@ const isPrivateIpv4 = (value) => {
16
16
  return true;
17
17
  if (a === 192 && b === 0 && c === 0)
18
18
  return true;
19
+ if (a >= 224)
20
+ return true;
19
21
  return false;
20
22
  };
21
23
  const parseIpv4Part = (s) => {
@@ -0,0 +1,22 @@
1
+ import { type RefKeyword } from './reference.js';
2
+ import type { JsonPath } from './types.js';
3
+ /**
4
+ * A lookup from a reference to where it was written in `root`, or `[]` when it
5
+ * was not written there at all.
6
+ *
7
+ * Every {@link ResolveError} carries the path to the reference that failed, and
8
+ * every one of them used to be either empty or — worse — the path to the target
9
+ * the reference *should* have found, which by definition is a node the document
10
+ * does not contain. A consumer anchoring a diagnostic on it (the CLI does) sent
11
+ * the reader to the top of the file, or to whichever node sat nearest the hole.
12
+ *
13
+ * The index is built on the first lookup and never on a resolve that has
14
+ * nothing to report, which is what keeps this off the happy path — and building
15
+ * it *once* is what keeps a document full of broken references linear rather
16
+ * than paying a fresh document walk per error.
17
+ *
18
+ * The paths are paths **in `root`**, which is what a consumer can map back to a
19
+ * position. A reference living in some other document is simply not indexed,
20
+ * and an empty path says "no position" the way it always has.
21
+ */
22
+ export declare const refPathIndex: (root: unknown, maxDepth?: number) => ((keyword: RefKeyword, ref: string) => JsonPath);
@@ -0,0 +1,53 @@
1
+ import { childRole } from "./child-role.js";
2
+ import { DEFAULT_MAX_DEPTH } from "./max-depth.js";
3
+ import { REF_KEYWORDS } from "./reference.js";
4
+ const refKey = (keyword, ref) => `${keyword} ${ref}`;
5
+ const buildIndex = (root, maxDepth) => {
6
+ const index = /* @__PURE__ */ new Map();
7
+ const seen = /* @__PURE__ */ new Set();
8
+ const stack = [{ node: root, path: [], role: "schema" }];
9
+ while (stack.length > 0) {
10
+ const frame = stack.pop();
11
+ if (frame === void 0)
12
+ break;
13
+ const { node, path, role } = frame;
14
+ if (node === null || typeof node !== "object" || role === "value")
15
+ continue;
16
+ if (path.length > maxDepth || seen.has(node))
17
+ continue;
18
+ seen.add(node);
19
+ if (Array.isArray(node)) {
20
+ for (let at = node.length - 1; at >= 0; at--) {
21
+ stack.push({ node: node[at], path: [...path, at], role: childRole(role, at) });
22
+ }
23
+ continue;
24
+ }
25
+ const obj = node;
26
+ const keys = Object.keys(obj);
27
+ if (role !== "schemaMap") {
28
+ for (const keyword of REF_KEYWORDS) {
29
+ const value = obj[keyword];
30
+ if (typeof value !== "string")
31
+ continue;
32
+ const entry = refKey(keyword, value);
33
+ if (!index.has(entry))
34
+ index.set(entry, [...path, keyword]);
35
+ }
36
+ }
37
+ for (let at = keys.length - 1; at >= 0; at--) {
38
+ const key = keys[at];
39
+ stack.push({ node: obj[key], path: [...path, key], role: childRole(role, key) });
40
+ }
41
+ }
42
+ return index;
43
+ };
44
+ const refPathIndex = (root, maxDepth = DEFAULT_MAX_DEPTH) => {
45
+ let index;
46
+ return (keyword, ref) => {
47
+ index ??= buildIndex(root, maxDepth);
48
+ return index.get(refKey(keyword, ref)) ?? [];
49
+ };
50
+ };
51
+ export {
52
+ refPathIndex
53
+ };
@@ -7,6 +7,15 @@ import type { JsonPath } from './types.js';
7
7
  * anchor (see {@link resolveFragment}).
8
8
  */
9
9
  export type RefKeyword = '$ref' | '$dynamicRef' | '$recursiveRef';
10
+ export declare const REF_KEYWORDS: readonly RefKeyword[];
11
+ /**
12
+ * OpenAPI 3.1 Reference Objects allow only these annotation keywords beside a
13
+ * `$ref`, and they *override* the target's — an `allOf` wrapper is not valid in
14
+ * those positions (Path Item, Response, Parameter references). They carry no
15
+ * validation semantics in plain JSON Schema either, so overriding is safe there
16
+ * too; every other sibling keyword keeps the spec-correct `allOf` combination.
17
+ */
18
+ export declare const ANNOTATION_ONLY_SIBLINGS: Set<string>;
10
19
  /** A reference carried by an object: which keyword, and its string value. */
11
20
  export type Reference = {
12
21
  keyword: RefKeyword;
package/dist/reference.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { childRole } from "./child-role.js";
2
- import { getByPointer, pointerToPath } from "./get-by-pointer.js";
2
+ import { getByPointer, isPointerFragment, pointerToPath } from "./get-by-pointer.js";
3
3
  import { DEFAULT_MAX_DEPTH } from "./max-depth.js";
4
4
  const REF_KEYWORDS = ["$ref", "$dynamicRef", "$recursiveRef"];
5
+ const ANNOTATION_ONLY_SIBLINGS = /* @__PURE__ */ new Set(["summary", "description"]);
5
6
  const readReference = (obj) => {
6
7
  for (const keyword of REF_KEYWORDS) {
7
8
  const value = obj[keyword];
@@ -10,7 +11,6 @@ const readReference = (obj) => {
10
11
  }
11
12
  return void 0;
12
13
  };
13
- const isPointerFragment = (fragment) => fragment === "" || fragment.startsWith("/");
14
14
  const search = (root, predicate) => {
15
15
  const seen = /* @__PURE__ */ new Set();
16
16
  const walk = (node, pointer, depth, role) => {
@@ -54,6 +54,8 @@ const resolveFragment = (root, keyword, fragment) => {
54
54
  return search(root, (obj) => obj["$anchor"] === fragment || obj["$dynamicAnchor"] === fragment);
55
55
  };
56
56
  export {
57
+ ANNOTATION_ONLY_SIBLINGS,
58
+ REF_KEYWORDS,
57
59
  readReference,
58
60
  resolveFragment
59
61
  };
@@ -1,35 +1,33 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
- import { dirname, resolve as resolvePath } from "node:path";
3
+ import { dirname, relative as relativePath, resolve as resolvePath, sep } from "node:path";
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 { pointerToPath } from "./get-by-pointer.js";
8
7
  import { isContainedPath } from "./is-contained-path.js";
9
8
  import { isPrivateHost } from "./is-private-host.js";
10
9
  import { DEFAULT_MAX_DEPTH, depthLimitError } from "./max-depth.js";
11
- import { readReference, resolveFragment } from "./reference.js";
10
+ import { refPathIndex } from "./ref-path-index.js";
11
+ import { ANNOTATION_ONLY_SIBLINGS, readReference, resolveFragment } from "./reference.js";
12
12
  import { baseOfNode, buildResourceRegistry, resolveRefInScope, SYNTHETIC_BASE } from "./resource-registry.js";
13
13
  import { roleAtPath } from "./role-at-path.js";
14
14
  import { assignKey } from "./safe-assign.js";
15
+ import { splitRef } from "./split-ref.js";
15
16
  const CYCLE = /* @__PURE__ */ Symbol("cycle");
16
17
  const MISSING = /* @__PURE__ */ Symbol("missing");
17
- const ANNOTATION_ONLY_SIBLINGS = /* @__PURE__ */ new Set(["summary", "description"]);
18
18
  const isRemote = (location) => /^https?:\/\//i.test(location);
19
19
  const joinLocation = (base, ref) => {
20
20
  if (isRemote(ref))
21
21
  return ref;
22
- if (isRemote(base))
23
- return new URL(ref, base).href;
22
+ if (isRemote(base)) {
23
+ try {
24
+ return new URL(ref, base).href;
25
+ } catch {
26
+ return void 0;
27
+ }
28
+ }
24
29
  return resolvePath(dirname(base), ref);
25
30
  };
26
- const splitRef = (ref) => {
27
- const hashIdx = ref.indexOf("#");
28
- return {
29
- filePart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
30
- fragment: hashIdx === -1 ? "" : ref.slice(hashIdx + 1)
31
- };
32
- };
33
31
  const REMOTE_CACHE_TTL_MS = 10 * 6e4;
34
32
  const REMOTE_CACHE_MAX_ENTRIES = 256;
35
33
  const remoteCache = /* @__PURE__ */ new Map();
@@ -90,6 +88,10 @@ const readCapped = async (response, maxBytes) => {
90
88
  }
91
89
  return text + decoder.decode();
92
90
  };
91
+ const parseDocument = (content, location, options) => {
92
+ const text = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
93
+ return options.parse === void 0 ? JSON.parse(text) : options.parse(text, location);
94
+ };
93
95
  const headersFor = (url, options) => {
94
96
  if (options.headers === void 0)
95
97
  return void 0;
@@ -160,8 +162,7 @@ const fetchRemote = async (location, options, deadline) => {
160
162
  }
161
163
  if (!response.ok)
162
164
  throw new Error(`HTTP ${response.status} ${response.statusText}`);
163
- const parse = options.parse ?? ((c) => JSON.parse(c));
164
- return parse(await readCapped(response, maxBytes), location);
165
+ return parseDocument(await readCapped(response, maxBytes), location, options);
165
166
  }
166
167
  throw new Error(`too many redirects (>${maxRedirects}): ${location}`);
167
168
  };
@@ -204,13 +205,13 @@ const needsDnsVerification = (options) => {
204
205
  return false;
205
206
  return true;
206
207
  };
207
- const loadDoc = async (location, docCache, options, errors, deadline) => {
208
+ const loadDoc = async (location, docCache, options, errors, deadline, refPath) => {
208
209
  if (docCache.has(location))
209
210
  return true;
210
211
  if (isRemote(location)) {
211
212
  const reason = denialReason(location, options);
212
213
  if (reason !== null) {
213
- errors.push({ message: `Refusing to resolve remote $ref (${reason}): ${location}`, path: [] });
214
+ errors.push({ message: `Refusing to resolve remote $ref (${reason}): ${location}`, path: refPath });
214
215
  docCache.set(location, {});
215
216
  return false;
216
217
  }
@@ -229,7 +230,7 @@ const loadDoc = async (location, docCache, options, errors, deadline) => {
229
230
  docCache.set(location, doc);
230
231
  return true;
231
232
  } catch (err) {
232
- errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: [] });
233
+ errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: refPath });
233
234
  docCache.set(location, {});
234
235
  return false;
235
236
  }
@@ -246,7 +247,7 @@ const loadDoc = async (location, docCache, options, errors, deadline) => {
246
247
  docCache.set(location, doc);
247
248
  return true;
248
249
  } catch (err) {
249
- errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: [] });
250
+ errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: refPath });
250
251
  docCache.set(location, {});
251
252
  return false;
252
253
  } finally {
@@ -255,11 +256,10 @@ const loadDoc = async (location, docCache, options, errors, deadline) => {
255
256
  }
256
257
  }
257
258
  try {
258
- const parse = options.parse ?? ((c) => JSON.parse(c));
259
- docCache.set(location, parse(readFileSync(location, "utf8"), location));
259
+ docCache.set(location, parseDocument(readFileSync(location, "utf8"), location, options));
260
260
  return true;
261
261
  } catch (err) {
262
- errors.push({ message: String(err), path: [] });
262
+ errors.push({ message: String(err), path: refPath });
263
263
  docCache.set(location, {});
264
264
  return false;
265
265
  }
@@ -307,6 +307,13 @@ const detach = (node) => {
307
307
  }
308
308
  continue;
309
309
  }
310
+ const prototype = Object.getPrototypeOf(src);
311
+ if (prototype !== Object.prototype && prototype !== null) {
312
+ const kept = src instanceof Date ? new Date(src.getTime()) : src;
313
+ seen.set(src, kept);
314
+ set(kept);
315
+ continue;
316
+ }
310
317
  const copy = {};
311
318
  seen.set(src, copy);
312
319
  set(copy);
@@ -321,6 +328,64 @@ const detach = (node) => {
321
328
  }
322
329
  return out.value;
323
330
  };
331
+ const rebaseKeptRef = (value, from, root) => {
332
+ if (from === root)
333
+ return value;
334
+ const { uriPart: filePart, fragment } = splitRef(value);
335
+ if (filePart === "")
336
+ return `${renderLocation(from, root)}${value}`;
337
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]+:/.test(filePart))
338
+ return value;
339
+ const target = joinLocation(from, filePart);
340
+ if (target === void 0)
341
+ return value;
342
+ const suffix = value.includes("#") ? `#${fragment}` : "";
343
+ return `${renderLocation(target, root)}${suffix}`;
344
+ };
345
+ const renderLocation = (target, root) => {
346
+ if (isRemote(target) || isRemote(root))
347
+ return target;
348
+ const relative = relativePath(dirname(root), target).split(sep).join("/");
349
+ return relative.startsWith(".") ? relative : `./${relative}`;
350
+ };
351
+ const rebaseKeptRefs = (node, from, root, role) => {
352
+ if (from === root || node === null || typeof node !== "object")
353
+ return node;
354
+ const seen = /* @__PURE__ */ new Set();
355
+ const stack = [{ value: node, role }];
356
+ while (stack.length > 0) {
357
+ const current = stack.pop();
358
+ if (current === void 0)
359
+ break;
360
+ const { value: current_, role: currentRole } = current;
361
+ if (current_ === null || typeof current_ !== "object")
362
+ continue;
363
+ if (currentRole === "value")
364
+ continue;
365
+ if (seen.has(current_))
366
+ continue;
367
+ seen.add(current_);
368
+ if (Array.isArray(current_)) {
369
+ for (let index = 0; index < current_.length; index++) {
370
+ stack.push({ value: current_[index], role: childRole(currentRole, index) });
371
+ }
372
+ continue;
373
+ }
374
+ const prototype = Object.getPrototypeOf(current_);
375
+ if (prototype !== Object.prototype && prototype !== null)
376
+ continue;
377
+ const obj = current_;
378
+ const isSchema = currentRole !== "schemaMap";
379
+ for (const [key, value] of Object.entries(obj)) {
380
+ if (isSchema && key === "$ref" && typeof value === "string") {
381
+ assignKey(obj, key, rebaseKeptRef(value, from, root));
382
+ } else {
383
+ stack.push({ value, role: childRole(currentRole, key) });
384
+ }
385
+ }
386
+ }
387
+ return node;
388
+ };
324
389
  const pathToRef = (path) => path.length === 0 ? "#" : `#/${path.map((segment) => escapeSegment(String(segment))).join("/")}`;
325
390
  const hoistName = (targetLocation, fragment, taken) => {
326
391
  const fragmentTail = fragment.split("/").filter(Boolean).pop();
@@ -354,7 +419,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
354
419
  return null;
355
420
  return `it resolves outside the allowed roots [${localRoots.join(", ")}] (set allowedRoots to permit it)`;
356
421
  };
357
- if (!await loadDoc(rootLocation, docCache, options, errors, deadline)) {
422
+ if (!await loadDoc(rootLocation, docCache, options, errors, deadline, [])) {
358
423
  return { resolved: {}, errors };
359
424
  }
360
425
  const registries = /* @__PURE__ */ new Map();
@@ -366,6 +431,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
366
431
  }
367
432
  return registry;
368
433
  };
434
+ const refPathAt = refPathIndex(docCache.get(rootLocation), maxDepth);
369
435
  let depthLimitReported = false;
370
436
  const reportDepthLimit = () => {
371
437
  if (depthLimitReported)
@@ -394,9 +460,9 @@ const resolveRefsFromFile = async (filename, options = {}) => {
394
460
  if (reference && reference.keyword !== "$recursiveRef") {
395
461
  const scoped = resolveRefInScope(registry, reference.keyword, reference.value, nodeBase);
396
462
  if (scoped === "external") {
397
- const { filePart } = splitRef(reference.value);
398
- if (filePart !== "")
399
- out.add(filePart);
463
+ const { uriPart: filePart } = splitRef(reference.value);
464
+ if (filePart !== "" && !out.has(filePart))
465
+ out.set(filePart, reference);
400
466
  }
401
467
  }
402
468
  for (const key of Object.keys(obj)) {
@@ -411,10 +477,18 @@ const resolveRefsFromFile = async (filename, options = {}) => {
411
477
  let loaded = 1;
412
478
  while (queue.length > 0) {
413
479
  const location = queue.shift();
414
- const out = /* @__PURE__ */ new Set();
480
+ const out = /* @__PURE__ */ new Map();
415
481
  collectRefTargets(docCache.get(location), location, registryFor(location).rootBase, out, 0, "schema");
416
- for (const filePart of out) {
482
+ for (const [filePart, reference] of out) {
483
+ const refPath = location === rootLocation ? refPathAt(reference.keyword, reference.value) : [];
417
484
  const target = joinLocation(location, filePart);
485
+ if (target === void 0) {
486
+ errors.push({
487
+ message: `Refusing to load $ref "${filePart}": it does not name a valid location`,
488
+ path: refPath
489
+ });
490
+ continue;
491
+ }
418
492
  if (seen.has(target))
419
493
  continue;
420
494
  seen.add(target);
@@ -435,14 +509,14 @@ const resolveRefsFromFile = async (filename, options = {}) => {
435
509
  if (!isRemote(target)) {
436
510
  const reason = localDenialReason(target);
437
511
  if (reason !== null) {
438
- errors.push({ message: `Refusing to read local $ref (${reason}): ${target}`, path: [] });
512
+ errors.push({ message: `Refusing to read local $ref (${reason}): ${target}`, path: refPath });
439
513
  docCache.set(target, {});
440
514
  unloadable.add(target);
441
515
  continue;
442
516
  }
443
517
  }
444
518
  loaded++;
445
- if (!await loadDoc(target, docCache, options, errors, deadline))
519
+ if (!await loadDoc(target, docCache, options, errors, deadline, refPath))
446
520
  unloadable.add(target);
447
521
  queue.push(target);
448
522
  }
@@ -457,6 +531,15 @@ const resolveRefsFromFile = async (filename, options = {}) => {
457
531
  const rootDoc = docCache.get(rootLocation);
458
532
  const rootDefs = rootDoc !== null && typeof rootDoc === "object" && !Array.isArray(rootDoc) ? rootDoc["$defs"] : void 0;
459
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
+ };
460
543
  const resolveAt = (node, baseLocation, base, depth, role) => {
461
544
  if (node === null || typeof node !== "object")
462
545
  return node;
@@ -464,7 +547,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
464
547
  return detach(node);
465
548
  if (depth > maxDepth) {
466
549
  reportDepthLimit();
467
- return detach(node);
550
+ return rebaseKeptRefs(detach(node), baseLocation, rootLocation, role);
468
551
  }
469
552
  if (Array.isArray(node)) {
470
553
  const items = node.map((item, index) => resolveAt(item, baseLocation, base, depth + 1, childRole(role, index)));
@@ -480,10 +563,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
480
563
  if (reference) {
481
564
  const { keyword, value } = reference;
482
565
  if (bindsAtEvaluationTime(keyword, value, ambiguousDynamicAnchors)) {
483
- const kept = {};
484
- for (const key of Object.keys(obj)) {
485
- assignKey(kept, key, key === keyword ? obj[key] : resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
486
- }
566
+ const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
487
567
  sensitive.add(kept);
488
568
  return kept;
489
569
  }
@@ -497,8 +577,11 @@ const resolveRefsFromFile = async (filename, options = {}) => {
497
577
  if (inScope === "external" || inScope === void 0) {
498
578
  const parts = splitRef(value);
499
579
  fragment = parts.fragment;
500
- if (inScope === "external" && parts.filePart !== "") {
501
- targetLocation = joinLocation(baseLocation, parts.filePart);
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;
502
585
  }
503
586
  } else {
504
587
  scoped = inScope;
@@ -511,6 +594,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
511
594
  const cached = refCache.get(cacheKey);
512
595
  if (cached === CYCLE) {
513
596
  let keptRef;
597
+ let hoisted = false;
514
598
  if (scoped !== void 0 && baseLocation === rootLocation) {
515
599
  keptRef = pathToRef(scoped.pointer);
516
600
  } else if (scoped === void 0 && targetLocation === rootLocation) {
@@ -521,6 +605,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
521
605
  name = hoistName(targetLocation, fragment, hoistTaken);
522
606
  hoists.set(cacheKey, name);
523
607
  }
608
+ hoisted = true;
524
609
  keptRef = `#/$defs/${name}`;
525
610
  }
526
611
  const kept = {};
@@ -530,20 +615,12 @@ const resolveRefsFromFile = async (filename, options = {}) => {
530
615
  assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
531
616
  }
532
617
  assignKey(kept, "$ref", keptRef);
618
+ if (hoisted)
619
+ hoistRefSites.set(kept, cacheKey);
533
620
  return kept;
534
621
  }
535
- const keepUnresolved = () => {
536
- const kept = {};
537
- for (const key of Object.keys(obj)) {
538
- if (key === keyword)
539
- continue;
540
- assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
541
- }
542
- assignKey(kept, keyword, value);
543
- return kept;
544
- };
545
622
  if (cached === MISSING)
546
- return keepUnresolved();
623
+ return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
547
624
  if (cached !== void 0) {
548
625
  resolved2 = cached.value;
549
626
  pointer = cached.pointer;
@@ -571,15 +648,23 @@ const resolveRefsFromFile = async (filename, options = {}) => {
571
648
  }
572
649
  }
573
650
  }
574
- if (found === void 0 && !unloadable.has(targetLocation)) {
575
- if (docCache.has(targetLocation)) {
651
+ const targetLoaded = docCache.has(targetLocation) && !unloadable.has(targetLocation);
652
+ if (found === void 0 || !targetLoaded) {
653
+ if (targetLoaded) {
576
654
  errors.push({
577
655
  message: `Cannot resolve ${keyword} "${value}"`,
578
- path: fragment === "" || fragment.startsWith("/") ? pointerToPath(fragment) : []
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) : []
579
664
  });
580
665
  }
581
666
  refCache.set(cacheKey, MISSING);
582
- return keepUnresolved();
667
+ return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
583
668
  }
584
669
  pointer = found?.pointer ?? [];
585
670
  resolved2 = resolveAt(found?.value, targetLocation, targetBase, depth + 1, roleAtPath(pointer));
@@ -589,10 +674,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
589
674
  }
590
675
  }
591
676
  if (isScopeSensitive(sensitive, resolved2) && !inliningKeepsScope(resolved2, nodeBase, targetBase)) {
592
- const kept = {};
593
- for (const key of Object.keys(obj)) {
594
- assignKey(kept, key, key === keyword ? obj[key] : resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
595
- }
677
+ const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
596
678
  sensitive.add(kept);
597
679
  return kept;
598
680
  }
@@ -616,6 +698,9 @@ const resolveRefsFromFile = async (filename, options = {}) => {
616
698
  }
617
699
  for (const key of Object.keys(siblings))
618
700
  assignKey(overridden, key, siblings[key]);
701
+ const hoistOf = hoistRefSites.get(resolved2);
702
+ if (hoistOf !== void 0)
703
+ hoistRefSites.set(overridden, hoistOf);
619
704
  if (origins && !origins.has(overridden))
620
705
  origins.set(overridden, { location: targetLocation, pointer });
621
706
  if (inlineIsSensitive)
@@ -649,10 +734,24 @@ const resolveRefsFromFile = async (filename, options = {}) => {
649
734
  if (resolved !== null && typeof resolved === "object" && !Array.isArray(resolved)) {
650
735
  const container = resolved;
651
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();
652
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) {
653
752
  const cached = refCache.get(cacheKey);
654
753
  const attachable = cached !== void 0 && cached !== CYCLE && cached !== MISSING;
655
- assignKey(defs, name, attachable ? cached.value ?? {} : {});
754
+ assignKey(defs, finalNames.get(cacheKey), attachable ? cached.value ?? {} : {});
656
755
  }
657
756
  assignKey(container, "$defs", defs);
658
757
  } else {
@@ -1,28 +1,25 @@
1
1
  import { childRole } from "./child-role.js";
2
2
  import { bindsAtEvaluationTime, declaresAmbiguousAnchor, inliningKeepsScope, isScopeSensitive } from "./dynamic-scope.js";
3
- import { pointerToPath } from "./get-by-pointer.js";
4
3
  import { DEFAULT_MAX_DEPTH, depthLimitError } from "./max-depth.js";
5
- import { readReference, resolveFragment } from "./reference.js";
4
+ import { refPathIndex } from "./ref-path-index.js";
5
+ import { ANNOTATION_ONLY_SIBLINGS, readReference, resolveFragment } from "./reference.js";
6
6
  import { baseOfNode, buildResourceRegistry, resolveRefInScope } from "./resource-registry.js";
7
7
  import { roleAtPath } from "./role-at-path.js";
8
8
  import { assignKey } from "./safe-assign.js";
9
9
  const CYCLE = /* @__PURE__ */ Symbol("cycle");
10
10
  const MISSING = /* @__PURE__ */ Symbol("missing");
11
- const ANNOTATION_ONLY_SIBLINGS = /* @__PURE__ */ new Set(["summary", "description"]);
12
- const resolveInternal = (node, root, registry, base, cache, origins, errors, limits, depth, role, sensitive) => {
11
+ const resolveNode = (node, base, depth, role, context) => {
12
+ const { root, registry, cache, origins, errors, sensitive, maxDepth, refPathAt, reportDepthLimit } = context;
13
13
  if (node === null || typeof node !== "object")
14
14
  return node;
15
15
  if (role === "value")
16
16
  return node;
17
- if (depth > limits.maxDepth) {
18
- if (!limits.reported) {
19
- limits.reported = true;
20
- errors.push(depthLimitError(limits.maxDepth));
21
- }
17
+ if (depth > maxDepth) {
18
+ reportDepthLimit();
22
19
  return node;
23
20
  }
24
21
  if (Array.isArray(node)) {
25
- const items = node.map((item, index) => resolveInternal(item, root, registry, base, cache, origins, errors, limits, depth + 1, childRole(role, index), sensitive));
22
+ const items = node.map((item, index) => resolveNode(item, base, depth + 1, childRole(role, index), context));
26
23
  if (items.some((item) => isScopeSensitive(sensitive, item)))
27
24
  sensitive.add(items);
28
25
  return items;
@@ -36,7 +33,7 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
36
33
  const keepReference = () => {
37
34
  const kept = {};
38
35
  for (const key of Object.keys(obj)) {
39
- assignKey(kept, key, key === keyword ? obj[key] : resolveInternal(obj[key], root, registry, nodeBase, cache, origins, errors, limits, depth + 1, childRole(role, key), sensitive));
36
+ assignKey(kept, key, key === keyword ? obj[key] : resolveNode(obj[key], nodeBase, depth + 1, childRole(role, key), context));
40
37
  }
41
38
  sensitive.add(kept);
42
39
  return kept;
@@ -46,7 +43,7 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
46
43
  const externalRef = () => {
47
44
  errors.push({
48
45
  message: `Cannot resolve external ${keyword} "${ref}": external ref requires resolveRefsFromFile`,
49
- path: []
46
+ path: refPathAt(keyword, ref)
50
47
  });
51
48
  return obj;
52
49
  };
@@ -84,16 +81,15 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
84
81
  } else {
85
82
  cache.set(cacheKey, CYCLE);
86
83
  if (found === void 0) {
87
- const fragment = ref.startsWith("#") ? ref.slice(1) : ref;
88
84
  errors.push({
89
85
  message: `Cannot resolve internal ${keyword} "${ref}"`,
90
- path: fragment === "" || fragment.startsWith("/") ? pointerToPath(fragment) : []
86
+ path: refPathAt(keyword, ref)
91
87
  });
92
88
  cache.set(cacheKey, MISSING);
93
89
  return obj;
94
90
  }
95
91
  pointer = found.pointer;
96
- target = resolveInternal(found.value, root, registry, targetBase, cache, origins, errors, limits, depth + 1, roleAtPath(pointer), sensitive);
92
+ target = resolveNode(found.value, targetBase, depth + 1, roleAtPath(pointer), context);
97
93
  cache.set(cacheKey, { target, pointer });
98
94
  if (origins && target !== null && typeof target === "object" && !origins.has(target)) {
99
95
  origins.set(target, { location: "", pointer });
@@ -108,7 +104,7 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
108
104
  const siblings = {};
109
105
  let siblingIsSensitive = false;
110
106
  for (const key of siblingKeys) {
111
- const child = resolveInternal(obj[key], root, registry, nodeBase, cache, origins, errors, limits, depth + 1, childRole(role, key), sensitive);
107
+ const child = resolveNode(obj[key], nodeBase, depth + 1, childRole(role, key), context);
112
108
  assignKey(siblings, key, child);
113
109
  if (isScopeSensitive(sensitive, child))
114
110
  siblingIsSensitive = true;
@@ -139,7 +135,7 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
139
135
  }
140
136
  const result = {};
141
137
  for (const key of Object.keys(obj)) {
142
- const child = resolveInternal(obj[key], root, registry, nodeBase, cache, origins, errors, limits, depth + 1, childRole(role, key), sensitive);
138
+ const child = resolveNode(obj[key], nodeBase, depth + 1, childRole(role, key), context);
143
139
  assignKey(result, key, child);
144
140
  if (isScopeSensitive(sensitive, child))
145
141
  sensitive.add(result);
@@ -151,9 +147,25 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
151
147
  const resolveRefs = (data, options = {}) => {
152
148
  const origins = options.trackOrigins ? /* @__PURE__ */ new Map() : void 0;
153
149
  const errors = [];
154
- const limits = { maxDepth: options.maxDepth ?? DEFAULT_MAX_DEPTH, reported: false };
155
- const registry = buildResourceRegistry(data, void 0, limits.maxDepth);
156
- const resolved = resolveInternal(data, data, registry, registry.rootBase, /* @__PURE__ */ new Map(), origins, errors, limits, 0, "schema", /* @__PURE__ */ new WeakSet());
150
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
151
+ let depthLimitReported = false;
152
+ const context = {
153
+ root: data,
154
+ registry: buildResourceRegistry(data, void 0, maxDepth),
155
+ cache: /* @__PURE__ */ new Map(),
156
+ origins,
157
+ errors,
158
+ sensitive: /* @__PURE__ */ new WeakSet(),
159
+ maxDepth,
160
+ refPathAt: refPathIndex(data, maxDepth),
161
+ reportDepthLimit: () => {
162
+ if (depthLimitReported)
163
+ return;
164
+ depthLimitReported = true;
165
+ errors.push(depthLimitError(maxDepth));
166
+ }
167
+ };
168
+ const resolved = resolveNode(data, context.registry.rootBase, 0, "schema", context);
157
169
  return origins ? { resolved, errors, origins } : { resolved, errors };
158
170
  };
159
171
  export {
@@ -45,6 +45,20 @@ export type ResourceRegistry = {
45
45
  value: unknown;
46
46
  pointer: JsonPath;
47
47
  }>;
48
+ /**
49
+ * Embedded-resource root → the base URI its `$id` established, by node
50
+ * identity. This is the inverse of {@link ResourceRegistry.resources}, kept
51
+ * because that is the direction the resolvers ask in: they hold a node and
52
+ * want its base. Scanning `resources` for it made every `$id` node cost a
53
+ * pass over every resource in the document, which is quadratic on exactly the
54
+ * bundled schemas that declare an `$id` per definition.
55
+ *
56
+ * It also answers for a node `resources` never took — a second `$id`
57
+ * resolving to a URI already claimed — where the scan fell back to the
58
+ * enclosing base and disagreed with the base this walk registered that node's
59
+ * own anchors under.
60
+ */
61
+ bases: Map<object, string>;
48
62
  /** `${base}#${name}` → target, for `$anchor` and `$dynamicAnchor` alike. */
49
63
  staticAnchors: Map<string, {
50
64
  value: unknown;
@@ -77,11 +91,6 @@ export type ResourceRegistry = {
77
91
  export declare const SYNTHETIC_BASE = "https://mjst-internal.invalid/document";
78
92
  /** `new URL(ref, base).href`, or `undefined` when the pair does not parse. */
79
93
  export declare const resolveUri: (ref: string, base: string) => string | undefined;
80
- /** Splits a ref string into its URI part and its fragment (pointer or anchor name). */
81
- export declare const splitFragment: (ref: string) => {
82
- uriPart: string;
83
- fragment: string;
84
- };
85
94
  /** The base URI a subschema establishes via `$id`, or the enclosing base. */
86
95
  export declare const baseAfterId: (node: Record<string, unknown>, enclosingBase: string) => string;
87
96
  /**
@@ -89,12 +98,12 @@ export declare const baseAfterId: (node: Record<string, unknown>, enclosingBase:
89
98
  * every anchor under the base URI it is scoped to. First declaration wins on
90
99
  * a duplicate URI or anchor name, matching document order.
91
100
  */
92
- export declare const buildResourceRegistry: (root: unknown, initialBase?: string, maxDepth?: number) => ResourceRegistry;
101
+ export declare const buildResourceRegistry: (root: unknown, documentBase?: string, maxDepth?: number) => ResourceRegistry;
93
102
  /**
94
103
  * The base URI `node` establishes via its `$id`, as assigned during the
95
- * registry walk (identity lookup), or `enclosing` when it declares none that
96
- * registered. Resolvers call this while walking so refs inside an embedded
97
- * resource resolve against the right base.
104
+ * registry walk, or `enclosing` when its `$id` established none (a draft-07
105
+ * `$id: "#name"`, or one that does not parse). Resolvers call this while
106
+ * walking so refs inside an embedded resource resolve against the right base.
98
107
  */
99
108
  export declare const baseOfNode: (registry: ResourceRegistry, node: Record<string, unknown>, enclosing: string) => string;
100
109
  /**
@@ -1,6 +1,7 @@
1
1
  import { childRole } from "./child-role.js";
2
- import { getByPointer, pointerToPath } from "./get-by-pointer.js";
2
+ import { getByPointer, isPointerFragment, pointerToPath } from "./get-by-pointer.js";
3
3
  import { DEFAULT_MAX_DEPTH } from "./max-depth.js";
4
+ import { splitRef } from "./split-ref.js";
4
5
  const SYNTHETIC_BASE = "https://mjst-internal.invalid/document";
5
6
  const resolveUri = (ref, base) => {
6
7
  try {
@@ -13,13 +14,6 @@ const withoutFragment = (uri) => {
13
14
  const hashIdx = uri.indexOf("#");
14
15
  return hashIdx === -1 ? uri : uri.slice(0, hashIdx);
15
16
  };
16
- const splitFragment = (ref) => {
17
- const hashIdx = ref.indexOf("#");
18
- return {
19
- uriPart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
20
- fragment: hashIdx === -1 ? "" : ref.slice(hashIdx + 1)
21
- };
22
- };
23
17
  const baseAfterId = (node, enclosingBase) => {
24
18
  const id = node["$id"];
25
19
  if (typeof id !== "string" || id === "")
@@ -30,8 +24,10 @@ const baseAfterId = (node, enclosingBase) => {
30
24
  const bare = withoutFragment(resolved);
31
25
  return bare === "" ? enclosingBase : bare;
32
26
  };
33
- const buildResourceRegistry = (root, initialBase = SYNTHETIC_BASE, maxDepth = DEFAULT_MAX_DEPTH) => {
27
+ const buildResourceRegistry = (root, documentBase = SYNTHETIC_BASE, maxDepth = DEFAULT_MAX_DEPTH) => {
28
+ const initialBase = withoutFragment(documentBase);
34
29
  const resources = /* @__PURE__ */ new Map();
30
+ const bases = /* @__PURE__ */ new Map();
35
31
  const staticAnchors = /* @__PURE__ */ new Map();
36
32
  const dynamicAnchors = /* @__PURE__ */ new Map();
37
33
  const dynamicAnchorCounts = /* @__PURE__ */ new Map();
@@ -63,8 +59,12 @@ const buildResourceRegistry = (root, initialBase = SYNTHETIC_BASE, maxDepth = DE
63
59
  }
64
60
  const record = node;
65
61
  const nodeBase = role === "schemaMap" ? base : baseAfterId(record, base);
66
- if (nodeBase !== base && !resources.has(nodeBase))
67
- resources.set(nodeBase, { value: node, pointer });
62
+ if (nodeBase !== base) {
63
+ if (!resources.has(nodeBase))
64
+ resources.set(nodeBase, { value: node, pointer });
65
+ if (!bases.has(node))
66
+ bases.set(node, nodeBase);
67
+ }
68
68
  if (role !== "schemaMap")
69
69
  registerAnchors(record, nodeBase, pointer);
70
70
  for (const key of Object.keys(record)) {
@@ -73,43 +73,38 @@ const buildResourceRegistry = (root, initialBase = SYNTHETIC_BASE, maxDepth = DE
73
73
  };
74
74
  if (rootBase !== initialBase)
75
75
  resources.set(rootBase, { value: root, pointer: [] });
76
- if (!resources.has(withoutFragment(initialBase))) {
77
- resources.set(withoutFragment(initialBase), { value: root, pointer: [] });
78
- }
76
+ if (!resources.has(initialBase))
77
+ resources.set(initialBase, { value: root, pointer: [] });
79
78
  walk(root, initialBase, [], 0, "schema");
80
79
  const ambiguousDynamicAnchors = /* @__PURE__ */ new Set();
81
80
  for (const [name, count] of dynamicAnchorCounts) {
82
81
  if (count > 1)
83
82
  ambiguousDynamicAnchors.add(name);
84
83
  }
85
- return { resources, staticAnchors, dynamicAnchors, ambiguousDynamicAnchors, rootBase, root };
84
+ return { resources, bases, staticAnchors, dynamicAnchors, ambiguousDynamicAnchors, rootBase, root };
86
85
  };
87
86
  const getByPointerWithBase = (start, startBase, startPointer, fragment) => {
88
87
  const value = getByPointer(start, fragment);
89
88
  if (value === void 0)
90
89
  return void 0;
90
+ const path = pointerToPath(fragment);
91
91
  let base = startBase;
92
92
  let current = start;
93
- for (const segment of pointerToPath(fragment)) {
93
+ for (const segment of path) {
94
94
  if (current === null || typeof current !== "object")
95
95
  break;
96
96
  if (!Array.isArray(current))
97
97
  base = baseAfterId(current, base);
98
+ if (!Object.hasOwn(current, segment))
99
+ break;
98
100
  current = current[segment];
99
101
  }
100
102
  if (current !== null && typeof current === "object" && !Array.isArray(current)) {
101
103
  base = baseAfterId(current, base);
102
104
  }
103
- return { value, pointer: [...startPointer, ...pointerToPath(fragment)], base };
104
- };
105
- const isPointerFragment = (fragment) => fragment === "" || fragment.startsWith("/");
106
- const baseOfNode = (registry, node, enclosing) => {
107
- for (const [uri, resource] of registry.resources) {
108
- if (resource.value === node)
109
- return uri;
110
- }
111
- return enclosing;
105
+ return { value, pointer: [...startPointer, ...path], base };
112
106
  };
107
+ const baseOfNode = (registry, node, enclosing) => registry.bases.get(node) ?? enclosing;
113
108
  const lookupAnchor = (registry, keyword, base, name) => {
114
109
  const key = `${base}#${name}`;
115
110
  if (keyword === "$dynamicRef")
@@ -117,7 +112,7 @@ const lookupAnchor = (registry, keyword, base, name) => {
117
112
  return registry.staticAnchors.get(key);
118
113
  };
119
114
  const resolveRefInScope = (registry, keyword, ref, currentBase) => {
120
- const { uriPart, fragment } = splitFragment(ref);
115
+ const { uriPart, fragment } = splitRef(ref);
121
116
  if (uriPart === "") {
122
117
  if (isPointerFragment(fragment)) {
123
118
  const resource2 = registry.resources.get(currentBase);
@@ -150,6 +145,5 @@ export {
150
145
  baseOfNode,
151
146
  buildResourceRegistry,
152
147
  resolveRefInScope,
153
- resolveUri,
154
- splitFragment
148
+ resolveUri
155
149
  };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Splits a reference string into the part naming a document and the fragment
3
+ * that addresses something inside it (a JSON Pointer, or a plain-name anchor).
4
+ *
5
+ * Everything before the first `#` is the document part. What that part *means*
6
+ * depends on who is asking — `resource-registry.ts` resolves it as a URI
7
+ * against the enclosing `$id` base, `resolve-refs-from-file.ts` as a file path
8
+ * or URL relative to the referencing document's location — but the split itself
9
+ * is the same one, which is why it lives here rather than in both.
10
+ */
11
+ export declare const splitRef: (ref: string) => {
12
+ uriPart: string;
13
+ fragment: string;
14
+ };
@@ -0,0 +1,10 @@
1
+ const splitRef = (ref) => {
2
+ const hashIdx = ref.indexOf("#");
3
+ return {
4
+ uriPart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
5
+ fragment: hashIdx === -1 ? "" : ref.slice(hashIdx + 1)
6
+ };
7
+ };
8
+ export {
9
+ splitRef
10
+ };
package/dist/types.d.ts CHANGED
@@ -1,11 +1,21 @@
1
1
  /**
2
- * A path into a JSON document: object keys and array indices, in order. Errors
3
- * report the location of the offending `$ref` with one of these.
2
+ * A path into a JSON document: object keys and array indices, in order.
4
3
  */
5
4
  export type JsonPath = (string | number)[];
6
5
  /** A single `$ref` resolution failure (a missing file, a bad URL, a refusal). */
7
6
  export type ResolveError = {
8
7
  message: string;
8
+ /**
9
+ * Where the reference that failed was written, as a path in the document you
10
+ * asked to resolve — ending in the reference keyword, so it points at the
11
+ * `$ref` line itself rather than at the schema around it. Anchor a diagnostic
12
+ * on it and the reader lands on the reference they have to fix.
13
+ *
14
+ * Empty when there is nowhere to point: a failure that belongs to the resolve
15
+ * as a whole (a depth or document budget), or a reference written in some
16
+ * other document rather than in the one you named. A reference used in
17
+ * several places is reported once, at the first.
18
+ */
9
19
  path: JsonPath;
10
20
  };
11
21
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/resolve-refs",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
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",
@@ -52,6 +52,6 @@
52
52
  }
53
53
  },
54
54
  "devDependencies": {
55
- "@amritk/runtime-validators": "^0.10.1"
55
+ "@amritk/runtime-validators": "^0.12.0"
56
56
  }
57
57
  }