@amritk/resolve-refs 0.2.3 → 0.3.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/README.md CHANGED
@@ -5,6 +5,11 @@ refs, and remote (http/https) documents — into a single dereferenced document.
5
5
 
6
6
  - **One-pass, cached.** Every unique ref is resolved once; cycles are broken with
7
7
  an empty object so the result is always finite.
8
+ - **Anchors + dynamic refs.** Beyond JSON-pointer `$ref`s, plain-name `$anchor`
9
+ references (`#node`), `$dynamicRef`/`$dynamicAnchor` (2020-12), and
10
+ `$recursiveRef`/`$recursiveAnchor` (2019-09) are dereferenced too. The dynamic
11
+ forms bind to their document-global anchor — the single-bundle case; nested
12
+ `$id` base-URI re-scoping is not modelled.
8
13
  - **Cross-file + remote.** Relative refs resolve against the document they appear
9
14
  in (a ref inside a remote doc stays remote, one inside a local file stays
10
15
  local). Fetched remote documents are cached for the lifetime of the process.
@@ -0,0 +1,42 @@
1
+ import type { JsonPath } from './types.js';
2
+ /**
3
+ * The reference keywords JSON Schema uses to point at another schema. `$ref`
4
+ * (all drafts) is a static pointer; `$dynamicRef` (2020-12) and `$recursiveRef`
5
+ * (2019-09) late-bind to an anchor so a recursive/extensible schema can refer to
6
+ * itself. We inline all three; the dynamic forms bind to their document-global
7
+ * anchor (see {@link resolveFragment}).
8
+ */
9
+ export type RefKeyword = '$ref' | '$dynamicRef' | '$recursiveRef';
10
+ /** A reference carried by an object: which keyword, and its string value. */
11
+ export type Reference = {
12
+ keyword: RefKeyword;
13
+ value: string;
14
+ };
15
+ /** Returns the reference keyword `obj` carries (if any), preferring `$ref`. */
16
+ export declare const readReference: (obj: Record<string, unknown>) => Reference | undefined;
17
+ /** The resolved target of a reference: the node and the path to it within its document. */
18
+ export type ResolvedTarget = {
19
+ value: unknown;
20
+ pointer: JsonPath;
21
+ };
22
+ /**
23
+ * Resolves a reference `fragment` (the part after `#`) within `root`, per its
24
+ * `keyword`. Returns the target node and its in-document path, or `undefined`
25
+ * when nothing matches.
26
+ *
27
+ * - **JSON Pointer** (`''`, `/a/b`) — a plain pointer lookup, for any keyword.
28
+ * - **`$anchor` name** (`node`) — searches for a `$anchor`/`$dynamicAnchor` equal
29
+ * to the name. A `$dynamicRef` prefers a `$dynamicAnchor`, then falls back to a
30
+ * plain `$anchor`, so it degrades to `$ref` semantics when nothing dynamic
31
+ * matches (2020-12).
32
+ * - **`$recursiveRef`** (always `#`) — binds to the object carrying
33
+ * `$recursiveAnchor: true`, falling back to the document root when there is
34
+ * none (2019-09).
35
+ *
36
+ * Anchor search is document-global: we bind to the single matching anchor in
37
+ * `root` rather than walking the dynamic scope. For one bundled document — what a
38
+ * linter dereferences — there is exactly one anchor per name, so this agrees with
39
+ * the full dynamic-scope algorithm. Nested `$id` base-URI re-scoping is not
40
+ * modelled (the common bundled case does not rely on it).
41
+ */
42
+ export declare const resolveFragment: (root: unknown, keyword: RefKeyword, fragment: string) => ResolvedTarget | undefined;
@@ -0,0 +1,80 @@
1
+ import { getByPointer, pointerToPath } from './get-by-pointer.js';
2
+ // `$ref` is listed first so that a node carrying several reference keywords
3
+ // resolves through the static one, matching how validators treat `$ref`.
4
+ const REF_KEYWORDS = ['$ref', '$dynamicRef', '$recursiveRef'];
5
+ /** Returns the reference keyword `obj` carries (if any), preferring `$ref`. */
6
+ export const readReference = (obj) => {
7
+ for (const keyword of REF_KEYWORDS) {
8
+ const value = obj[keyword];
9
+ if (typeof value === 'string')
10
+ return { keyword, value };
11
+ }
12
+ return undefined;
13
+ };
14
+ /** A fragment is a JSON Pointer when it is empty or begins with `/`; otherwise a plain-name anchor. */
15
+ const isPointerFragment = (fragment) => fragment === '' || fragment.startsWith('/');
16
+ /**
17
+ * Depth-first search for the first object in `root` satisfying `predicate`,
18
+ * returning it with the path to it. `seen` guards against cyclic inputs. Used to
19
+ * locate `$anchor`/`$dynamicAnchor`/`$recursiveAnchor` targets.
20
+ */
21
+ const search = (root, predicate) => {
22
+ const seen = new Set();
23
+ const walk = (node, pointer) => {
24
+ if (node === null || typeof node !== 'object' || seen.has(node))
25
+ return undefined;
26
+ seen.add(node);
27
+ if (!Array.isArray(node) && predicate(node))
28
+ return { value: node, pointer };
29
+ if (Array.isArray(node)) {
30
+ for (let i = 0; i < node.length; i++) {
31
+ const found = walk(node[i], [...pointer, i]);
32
+ if (found)
33
+ return found;
34
+ }
35
+ }
36
+ else {
37
+ for (const key of Object.keys(node)) {
38
+ const found = walk(node[key], [...pointer, key]);
39
+ if (found)
40
+ return found;
41
+ }
42
+ }
43
+ return undefined;
44
+ };
45
+ return walk(root, []);
46
+ };
47
+ /**
48
+ * Resolves a reference `fragment` (the part after `#`) within `root`, per its
49
+ * `keyword`. Returns the target node and its in-document path, or `undefined`
50
+ * when nothing matches.
51
+ *
52
+ * - **JSON Pointer** (`''`, `/a/b`) — a plain pointer lookup, for any keyword.
53
+ * - **`$anchor` name** (`node`) — searches for a `$anchor`/`$dynamicAnchor` equal
54
+ * to the name. A `$dynamicRef` prefers a `$dynamicAnchor`, then falls back to a
55
+ * plain `$anchor`, so it degrades to `$ref` semantics when nothing dynamic
56
+ * matches (2020-12).
57
+ * - **`$recursiveRef`** (always `#`) — binds to the object carrying
58
+ * `$recursiveAnchor: true`, falling back to the document root when there is
59
+ * none (2019-09).
60
+ *
61
+ * Anchor search is document-global: we bind to the single matching anchor in
62
+ * `root` rather than walking the dynamic scope. For one bundled document — what a
63
+ * linter dereferences — there is exactly one anchor per name, so this agrees with
64
+ * the full dynamic-scope algorithm. Nested `$id` base-URI re-scoping is not
65
+ * modelled (the common bundled case does not rely on it).
66
+ */
67
+ export const resolveFragment = (root, keyword, fragment) => {
68
+ if (keyword === '$recursiveRef') {
69
+ const anchored = search(root, (obj) => obj['$recursiveAnchor'] === true);
70
+ return anchored ?? { value: root, pointer: [] };
71
+ }
72
+ if (isPointerFragment(fragment)) {
73
+ const value = getByPointer(root, fragment);
74
+ return value === undefined ? undefined : { value, pointer: pointerToPath(fragment) };
75
+ }
76
+ if (keyword === '$dynamicRef') {
77
+ return (search(root, (obj) => obj['$dynamicAnchor'] === fragment) ?? search(root, (obj) => obj['$anchor'] === fragment));
78
+ }
79
+ return search(root, (obj) => obj['$anchor'] === fragment || obj['$dynamicAnchor'] === fragment);
80
+ };
@@ -1,7 +1,7 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { dirname, resolve as resolvePath } from 'node:path';
3
- import { getByPointer, pointerToPath } from './get-by-pointer.js';
4
3
  import { isPrivateHost } from './is-private-host.js';
4
+ import { readReference, resolveFragment } from './reference.js';
5
5
  import { assignKey } from './safe-assign.js';
6
6
  // A ref currently mid-resolution is marked with this sentinel; revisiting it
7
7
  // means a cycle, so we return `{}` instead of recursing forever.
@@ -21,12 +21,12 @@ const joinLocation = (base, ref) => {
21
21
  return new URL(ref, base).href;
22
22
  return resolvePath(dirname(base), ref);
23
23
  };
24
- /** Splits a `$ref` into its document part and JSON-pointer part. */
24
+ /** Splits a `$ref` into its document part and its fragment (pointer or anchor name). */
25
25
  const splitRef = (ref) => {
26
26
  const hashIdx = ref.indexOf('#');
27
27
  return {
28
28
  filePart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
29
- pointer: hashIdx === -1 ? '' : ref.slice(hashIdx + 1),
29
+ fragment: hashIdx === -1 ? '' : ref.slice(hashIdx + 1),
30
30
  };
31
31
  };
32
32
  // --- Remote document cache -------------------------------------------------
@@ -204,15 +204,16 @@ const collectRefTargets = (node, out) => {
204
204
  return out;
205
205
  }
206
206
  const obj = node;
207
- if (typeof obj['$ref'] === 'string') {
208
- const { filePart } = splitRef(obj['$ref']);
207
+ const reference = readReference(obj);
208
+ if (reference) {
209
+ const { filePart } = splitRef(reference.value);
209
210
  if (filePart !== '')
210
211
  out.add(filePart);
211
212
  }
212
- // Recurse into every key — including a `$ref` node's siblings, which apply
213
+ // Recurse into every key — including a reference node's siblings, which apply
213
214
  // alongside the referenced schema (2020-12) and may carry their own refs.
214
215
  for (const key of Object.keys(obj)) {
215
- if (key === '$ref')
216
+ if (reference && key === reference.keyword)
216
217
  continue;
217
218
  collectRefTargets(obj[key], out);
218
219
  }
@@ -255,34 +256,48 @@ const resolveAt = (node, baseLocation, docCache, refCache, origins) => {
255
256
  return node.map((item) => resolveAt(item, baseLocation, docCache, refCache, origins));
256
257
  }
257
258
  const obj = node;
258
- if (typeof obj['$ref'] === 'string') {
259
- const { filePart, pointer } = splitRef(obj['$ref']);
259
+ const reference = readReference(obj);
260
+ if (reference) {
261
+ const { keyword, value } = reference;
262
+ const { filePart, fragment } = splitRef(value);
260
263
  const targetLocation = filePart === '' ? baseLocation : joinLocation(baseLocation, filePart);
261
264
  const targetRoot = docCache.get(targetLocation) ?? {};
262
- const cacheKey = `${targetLocation}#${pointer}`;
265
+ // Cache/cycle key includes the keyword: `$ref #x` and `$dynamicRef #x` can
266
+ // bind to different targets, so they must not share a cache slot.
267
+ const cacheKey = `${keyword} ${targetLocation}#${fragment}`;
263
268
  let resolved;
264
- if (refCache.has(cacheKey)) {
265
- const cached = refCache.get(cacheKey);
266
- resolved = cached === CYCLE ? {} : cached;
269
+ let pointer;
270
+ const cached = refCache.get(cacheKey);
271
+ if (cached === CYCLE) {
272
+ resolved = {};
273
+ pointer = [];
274
+ }
275
+ else if (cached !== undefined) {
276
+ resolved = cached.value;
277
+ pointer = cached.pointer;
267
278
  }
268
279
  else {
269
280
  refCache.set(cacheKey, CYCLE);
270
- const target = pointer ? getByPointer(targetRoot, pointer) : targetRoot;
271
- resolved = resolveAt(target, targetLocation, docCache, refCache, origins);
272
- refCache.set(cacheKey, resolved);
281
+ // `$anchor`/`$dynamicAnchor`/`$recursiveAnchor` are resolved within the
282
+ // target document; a plain pointer is a direct lookup. A fragment that
283
+ // resolves to nothing inlines as `undefined` (kept as-is for parity).
284
+ const found = resolveFragment(targetRoot, keyword, fragment);
285
+ pointer = found?.pointer ?? [];
286
+ resolved = resolveAt(found?.value, targetLocation, docCache, refCache, origins);
287
+ refCache.set(cacheKey, { value: resolved, pointer });
273
288
  // Stamp the inlined node with where it was defined so a consumer can map a
274
289
  // resolved-tree node back to its source document/path. Only objects/arrays are
275
290
  // stamped (primitives can't key the map). First-write-wins: resolution recurses
276
- // to the deepest `$ref` before returning, so the *definition* site stamps first;
291
+ // to the deepest ref before returning, so the *definition* site stamps first;
277
292
  // an outer ref that merely points (transitively) at the same object must not
278
293
  // overwrite it with an intermediate location.
279
294
  if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
280
- origins.set(resolved, { location: targetLocation, pointer: pointerToPath(pointer) });
295
+ origins.set(resolved, { location: targetLocation, pointer });
281
296
  }
282
297
  }
283
- // Keywords sibling to `$ref` apply alongside the referenced schema (2020-12),
284
- // so preserve them by combining both in an `allOf` rather than dropping them.
285
- const siblingKeys = Object.keys(obj).filter((key) => key !== '$ref');
298
+ // Keywords sibling to a reference apply alongside the referenced schema
299
+ // (2020-12), so preserve them by combining both in an `allOf`.
300
+ const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
286
301
  if (siblingKeys.length === 0)
287
302
  return resolved;
288
303
  const siblings = {};
@@ -290,9 +305,9 @@ const resolveAt = (node, baseLocation, docCache, refCache, origins) => {
290
305
  assignKey(siblings, key, resolveAt(obj[key], baseLocation, docCache, refCache, origins));
291
306
  const existingAllOf = Array.isArray(siblings['allOf']) ? siblings['allOf'] : [];
292
307
  const merged = { ...siblings, allOf: [...existingAllOf, resolved] };
293
- // Stamp the wrapper too, so origin lookups resolve for a `$ref`-with-siblings node.
308
+ // Stamp the wrapper too, so origin lookups resolve for a ref-with-siblings node.
294
309
  if (origins && !origins.has(merged))
295
- origins.set(merged, { location: targetLocation, pointer: pointerToPath(pointer) });
310
+ origins.set(merged, { location: targetLocation, pointer });
296
311
  return merged;
297
312
  }
298
313
  const result = {};
@@ -1,8 +1,11 @@
1
- import { getByPointer, pointerToPath } from './get-by-pointer.js';
1
+ import { pointerToPath } from './get-by-pointer.js';
2
+ import { readReference, resolveFragment } from './reference.js';
2
3
  import { assignKey } from './safe-assign.js';
3
4
  // A ref currently mid-resolution is marked with this sentinel; revisiting it
4
5
  // means we have looped, so we return `{}` instead of recursing forever.
5
6
  const CYCLE = Symbol('cycle');
7
+ // A ref that resolved to nothing; cached so a repeated bad ref reports once.
8
+ const MISSING = Symbol('missing');
6
9
  /**
7
10
  * Single-pass internal-only `$ref` resolver. Each unique ref string is resolved
8
11
  * exactly once (the `cache`); revisiting a ref that is still mid-resolution
@@ -16,33 +19,50 @@ const resolveInternal = (node, root, cache, origins, errors) => {
16
19
  if (Array.isArray(node))
17
20
  return node.map((item) => resolveInternal(item, root, cache, origins, errors));
18
21
  const obj = node;
19
- if (typeof obj['$ref'] === 'string') {
20
- const ref = obj['$ref'];
22
+ const reference = readReference(obj);
23
+ if (reference) {
24
+ const { keyword, value: ref } = reference;
21
25
  if (!ref.startsWith('#'))
22
26
  return obj; // external ref — leave as-is
27
+ // Cache/cycle key includes the keyword: `$ref #x` and `$dynamicRef #x` can
28
+ // bind to different targets, so they must not share a cache slot.
29
+ const cacheKey = `${keyword} ${ref}`;
23
30
  let target;
24
- if (cache.has(ref)) {
25
- const cached = cache.get(ref);
26
- target = cached === CYCLE ? {} : cached;
31
+ let pointer;
32
+ const cached = cache.get(cacheKey);
33
+ if (cached === MISSING)
34
+ return obj;
35
+ if (cached === CYCLE) {
36
+ target = {};
37
+ pointer = [];
38
+ }
39
+ else if (cached !== undefined) {
40
+ target = cached.target;
41
+ pointer = cached.pointer;
27
42
  }
28
43
  else {
29
- cache.set(ref, CYCLE);
30
- const pointed = getByPointer(root, ref.slice(1));
31
- if (pointed === undefined) {
32
- // An internal pointer that resolves to nothing (a typo'd or missing
33
- // definition) was previously inlined as literal `undefined` with no trace.
34
- // Record it and keep the original `$ref` node so the failure is visible.
35
- errors.push({ message: `Cannot resolve internal $ref "${ref}"`, path: pointerToPath(ref.slice(1)) });
36
- cache.set(ref, obj);
44
+ cache.set(cacheKey, CYCLE);
45
+ const found = resolveFragment(root, keyword, ref.slice(1));
46
+ if (found === undefined) {
47
+ // A reference that resolves to nothing (a typo'd pointer or a missing
48
+ // anchor) was previously inlined as literal `undefined` with no trace.
49
+ // Record it and keep the original node so the failure is visible.
50
+ const fragment = ref.slice(1);
51
+ errors.push({
52
+ message: `Cannot resolve internal ${keyword} "${ref}"`,
53
+ path: fragment === '' || fragment.startsWith('/') ? pointerToPath(fragment) : [],
54
+ });
55
+ cache.set(cacheKey, MISSING);
37
56
  return obj;
38
57
  }
39
- target = resolveInternal(pointed, root, cache, origins, errors);
40
- cache.set(ref, target);
58
+ pointer = found.pointer;
59
+ target = resolveInternal(found.value, root, cache, origins, errors);
60
+ cache.set(cacheKey, { target, pointer });
41
61
  // Stamp the inlined node with the path it was defined at (see resolveAt).
42
62
  // First-write-wins so the deepest definition stamps before any outer ref that
43
63
  // transitively points at the same object. Primitives can't key the map.
44
64
  if (origins && target !== null && typeof target === 'object' && !origins.has(target)) {
45
- origins.set(target, { location: '', pointer: pointerToPath(ref.slice(1)) });
65
+ origins.set(target, { location: '', pointer });
46
66
  }
47
67
  }
48
68
  // Per JSON Schema 2020-12, keywords sibling to `$ref` are *not* ignored: they
@@ -50,7 +70,7 @@ const resolveInternal = (node, root, cache, origins, errors) => {
50
70
  // `allOf` (so a constraint present on both sides is never silently dropped)
51
71
  // rather than returning the bare target. The cache always stores the
52
72
  // sibling-free target so each occurrence applies its own siblings.
53
- const siblingKeys = Object.keys(obj).filter((key) => key !== '$ref');
73
+ const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
54
74
  if (siblingKeys.length === 0)
55
75
  return target;
56
76
  const siblings = {};
@@ -61,7 +81,7 @@ const resolveInternal = (node, root, cache, origins, errors) => {
61
81
  // Stamp the wrapper too, so a consumer mapping the resolved node back to its
62
82
  // origin finds one for a `$ref`-with-siblings node (not only the inner target).
63
83
  if (origins && !origins.has(merged))
64
- origins.set(merged, { location: '', pointer: pointerToPath(ref.slice(1)) });
84
+ origins.set(merged, { location: '', pointer });
65
85
  return merged;
66
86
  }
67
87
  const result = {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/resolve-refs",
3
- "version": "0.2.3",
3
+ "version": "0.3.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
  "module": "./dist/index.js",
6
6
  "type": "module",