@amritk/resolve-refs 0.2.3 → 0.4.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
@@ -3,21 +3,38 @@
3
3
  Resolve and inline JSON Schema / OpenAPI `$ref`s — internal pointers, cross-file
4
4
  refs, and remote (http/https) documents — into a single dereferenced document.
5
5
 
6
- - **One-pass, cached.** Every unique ref is resolved once; cycles are broken with
7
- an empty object so the result is always finite.
6
+ - **One-pass, cached.** Every unique ref is resolved once; the result is always
7
+ finite. At a reference **cycle** the recursive branch is *kept*, not lost: the
8
+ cycle point stays a `$ref` that resolves within the output document (a
9
+ cross-file cycle target is hoisted into the root's `$defs`), so recursive
10
+ schemas survive dereferencing intact.
11
+ - **Anchors + dynamic refs, `$id`-scoped.** Beyond JSON-pointer `$ref`s,
12
+ plain-name `$anchor` references (`#node`), `$dynamicRef`/`$dynamicAnchor`
13
+ (2020-12), and `$recursiveRef`/`$recursiveAnchor` (2019-09) are dereferenced
14
+ too. `$id` base-URI scoping is modelled for the bundled-document case: a ref
15
+ whose URI matches an embedded resource's `$id` resolves to it without
16
+ fetching, and anchors bind within the resource that declares them (falling
17
+ back to a document-global search). See *`$id` scoping* below for the exact
18
+ subset.
8
19
  - **Cross-file + remote.** Relative refs resolve against the document they appear
9
20
  in (a ref inside a remote doc stays remote, one inside a local file stays
10
21
  local). Fetched remote documents are cached for the lifetime of the process.
11
22
  - **Default-deny SSRF guard.** Remote refs to loopback, private, link-local, and
12
23
  cloud-metadata (`169.254.169.254`) hosts are refused unless you opt in.
24
+ - **OpenAPI Reference Objects.** A `$ref` whose only siblings are `summary` /
25
+ `description` inlines the target with those annotations overriding — matching
26
+ OpenAPI 3.1 Reference Object semantics, where an `allOf` wrapper would be
27
+ invalid. Any other sibling keyword keeps the spec-correct `allOf` combination.
13
28
 
14
29
  ## Usage
15
30
 
16
31
  ```ts
17
32
  import { resolveRefs, resolveRefsFromFile } from '@amritk/resolve-refs'
18
33
 
19
- // In-memory, internal (#/...) refs only:
20
- const { resolved } = resolveRefs(myDocument)
34
+ // In-memory, internal (#/...) refs only. External refs (another file or an
35
+ // http(s) URL) are left in place and reported on `errors`, since this resolver
36
+ // can't load other documents — use resolveRefsFromFile for those:
37
+ const { resolved, errors } = resolveRefs(myDocument)
21
38
 
22
39
  // From disk or a URL, including cross-file and remote refs:
23
40
  const result = await resolveRefsFromFile('./schema.json')
@@ -33,6 +50,14 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
33
50
  | `remote` | `true` | Whether http(s) refs may be fetched at all. |
34
51
  | `allowedHosts` | `[]` | If non-empty, only these hosts may be fetched. An explicit entry bypasses the private-host guard. |
35
52
  | `allowPrivateHosts` | `false` | Allow loopback/private/link-local targets. Left off, these are refused as an SSRF guard. |
53
+ | `headers` | — | Extra headers for remote requests (record, or `(url) => headers` for per-host credentials). Never sent across a cross-origin redirect. |
54
+ | `fetch` | global `fetch` | Custom fetch implementation. The SSRF guard still evaluates every hop before it is called. |
55
+ | `timeoutMs` | `30_000` | Abort an unresponsive remote fetch after this many milliseconds. |
56
+ | `maxRedirects` | `5` | Redirect hops to follow per remote document (each hop re-runs the SSRF guard). |
57
+ | `maxBytes` | `16` MiB | Refuse to buffer a remote document larger than this. |
58
+ | `cache` | `true` | Pass `false` to bypass the process-wide session cache for this call — everything is re-fetched, nothing is stored. |
59
+ | `parse` | `JSON.parse` | Custom content parser (e.g. YAML-aware). |
60
+ | `trackOrigins` | `false` | Record a per-node origin map on the result. |
36
61
 
37
62
  Errors (a missing file, a refused host, a bad URL) are collected on
38
63
  `result.errors` rather than thrown; the corresponding ref resolves to `{}` so the
@@ -41,8 +66,58 @@ rest of the document still resolves.
41
66
  `clearRemoteCache()` drops every cached remote document — useful in tests or
42
67
  long-lived sessions where remote schemas may change.
43
68
 
69
+ ## `$id` scoping
70
+
71
+ The supported subset, chosen for the bundled-document reality rather than the
72
+ full spec:
73
+
74
+ - A subschema with `$id` is an **embedded resource**: its `$id` (resolved
75
+ against the enclosing base) becomes the base URI for everything inside it.
76
+ - A ref whose URI — resolved against the enclosing base — **matches an embedded
77
+ resource's `$id`** resolves to that resource without fetching. A pointer or
78
+ anchor fragment on such a ref applies *within* that resource.
79
+ - **Anchors** bind within the resource that declares them first; an anchor not
80
+ found in scope falls back to a document-global search (compatibility with
81
+ documents that reference across sibling resources).
82
+ - A plain `#/pointer` fragment stays **document-root-relative** — the behavior
83
+ bundled real-world documents rely on — even inside an embedded resource.
84
+ - `$dynamicRef` prefers a `$dynamicAnchor` in scope, then degrades to `$ref`
85
+ semantics. The full dynamic-scope algorithm (outermost anchor along the
86
+ runtime reference chain) is not modelled.
87
+ - Document **retrieval is unaffected**: which file/URL an external ref loads
88
+ from is derived from the referencing document's *location*, never its `$id` —
89
+ a root `$id` naming a remote URL cannot turn a local sibling-file ref into a
90
+ network fetch.
91
+
44
92
  ## Documents
45
93
 
46
94
  Every document — local file or remote — is parsed as **JSON**. mjst works with
47
95
  JSON Schema documents only, so this resolver stays JSON-only and dependency-free.
48
96
  (The Loupe linter's sibling resolver additionally accepts YAML.)
97
+
98
+ ## Benchmarks
99
+
100
+ `resolveRefs` is single-pass: every unique `$ref` string is resolved exactly
101
+ once and memoized, with a sentinel that breaks cycles. The `bench/` suite isolates
102
+ what that memoization buys by pitting it against a naive inliner that re-resolves
103
+ each ref every time it is encountered — same inlined output, the cache is the only
104
+ difference. Representative numbers (Bun 1.3, Linux x64 — your hardware will
105
+ differ, run `bun run bench` yourself):
106
+
107
+ | schema | cached | naive | speedup |
108
+ |:---|---:|---:|---:|
109
+ | reuse-heavy (50 refs → 1 def) | ~35k ops/s | ~6k ops/s | **~5.8×** |
110
+ | chain (40 `$ref` → `$ref` links) | ~5k ops/s | ~0.6k ops/s | **~8.2×** |
111
+ | cyclic tree | ~122k ops/s | ~117k ops/s | ~1.05× |
112
+ | wide-distinct (60 defs, each used once) | ~3.3k ops/s | ~6.1k ops/s | ~0.54× |
113
+
114
+ The cache earns its keep exactly where you'd expect: a `$def` referenced from
115
+ many sites, or a long indirection chain, is resolved once instead of re-walked
116
+ every time. On a document where every ref is distinct — so the cache never hits —
117
+ its bookkeeping is pure overhead and the naive walk is faster; that `wide-distinct`
118
+ row is kept in the table precisely to show the trade honestly. Real API schemas
119
+ lean heavily on shared `$def`s, which is the case the resolver is tuned for.
120
+
121
+ Opting into `trackOrigins` (which records where each inlined value came from) adds
122
+ roughly **5–20%** on top. Both strategies are asserted to produce byte-identical
123
+ output before either is timed.
@@ -68,7 +68,13 @@ const ipv4Octets = (host) => {
68
68
  return [(value >>> 24) & 0xff, (value >>> 16) & 0xff];
69
69
  };
70
70
  export const isPrivateHost = (hostname) => {
71
- const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
71
+ // Strip IPv6 brackets and any trailing dot(s): `localhost.` is the FQDN-root
72
+ // form of `localhost` and resolves to the same loopback address, so it must
73
+ // not slip past the by-name checks below.
74
+ const host = hostname
75
+ .replace(/^\[|\]$/g, '')
76
+ .replace(/\.+$/, '')
77
+ .toLowerCase();
72
78
  if (host === 'localhost' || host.endsWith('.localhost'))
73
79
  return true;
74
80
  if (host.includes(':')) {
@@ -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. This is the *fallback* path —
38
+ * the resolvers first try `$id`-scoped resolution via `resource-registry.ts`,
39
+ * which binds duplicate anchor names to the resource they are declared in, and
40
+ * only land here for anchors declared outside any registered scope.
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. This is the *fallback* path —
63
+ * the resolvers first try `$id`-scoped resolution via `resource-registry.ts`,
64
+ * which binds duplicate anchor names to the resource they are declared in, and
65
+ * only land here for anchors declared outside any registered scope.
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
+ };
@@ -4,6 +4,8 @@ export declare const clearRemoteCache: () => void;
4
4
  /**
5
5
  * Resolves `$ref`s in a document on disk (or at a URL), including cross-file
6
6
  * and remote refs. Remote documents are fetched on the fly and cached in memory
7
- * for the session; `options` governs whether/which remote hosts are allowed.
7
+ * for the session; `options` governs whether/which remote hosts are allowed,
8
+ * how they are fetched (`headers`, `fetch`, `timeoutMs`, `maxRedirects`,
9
+ * `maxBytes`), and whether the session cache is used (`cache`).
8
10
  */
9
11
  export declare const resolveRefsFromFile: (filename: string, options?: ResolveOptions) => Promise<ResolveResult>;