@amritk/resolve-refs 0.7.1 → 0.9.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 +3 -1
- package/README.md +20 -12
- package/dist/get-by-pointer.js +6 -1
- package/dist/reference.js +10 -5
- package/dist/resolve-refs-from-file.js +3 -1
- package/dist/resolve-refs.js +22 -20
- package/dist/resource-registry.js +16 -10
- package/dist/types.d.ts +17 -0
- package/package.json +6 -3
package/AI.md
CHANGED
|
@@ -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
|
@@ -56,7 +56,7 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
|
|
|
56
56
|
|:---|:---|:---|
|
|
57
57
|
| `remote` | `true` | Whether http(s) refs may be fetched at all. |
|
|
58
58
|
| `localRefs` | `true` | Whether `$ref`s to other files on disk may be read. `false` still reads the root document you named — it refuses everything a ref reaches out to. |
|
|
59
|
-
| `allowedRoots` | `[dirname(root)]` | Directories a local `$ref` must resolve inside. The default confines a ref to the folder holding the root document. |
|
|
59
|
+
| `allowedRoots` | `[dirname(root)]` | Directories a local `$ref` must resolve inside. The default confines a ref to the folder holding the root document; for a root loaded from a URL the default is `[]`, so no local file is read at all. |
|
|
60
60
|
| `allowedHosts` | `[]` | If non-empty, only these hosts may be fetched. Matched case-insensitively; an entry without a port matches any port, one with a port must match it (a URL that omits the port counts as its protocol default). An explicit entry bypasses the private-host and DNS guards. |
|
|
61
61
|
| `allowPrivateHosts` | `false` | Allow loopback/private/link-local targets. Left off, these are refused as an SSRF guard. |
|
|
62
62
|
| `verifyDns` | `true` | Resolve each remote host and refuse it when any address it resolves to is non-public. Pass `false` where names resolve at an egress proxy rather than locally. |
|
|
@@ -70,11 +70,13 @@ 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. |
|
|
74
75
|
|
|
75
76
|
Errors (a missing file, a refused host, a refused path, a bad URL, a document too
|
|
76
77
|
deeply nested) are collected on `result.errors` rather than thrown; the
|
|
77
|
-
|
|
78
|
+
referencing node is left in place as its `$ref` (nothing is inlined) so the rest
|
|
79
|
+
of the document still resolves.
|
|
78
80
|
Each error carries the `path` to the reference that caused it — a path in the
|
|
79
81
|
document you named, ending in the keyword (`['properties', 'pet', '$ref']`) — so
|
|
80
82
|
a caller can anchor a diagnostic on the `$ref` a reader has to fix. It is empty
|
|
@@ -190,15 +192,20 @@ recursive cycles intact, and records a diagnostic for every external ref. The
|
|
|
190
192
|
registry, no scoping, no diagnostics — and re-resolves each ref on every
|
|
191
193
|
encounter, so the gap is the production resolver's *total* per-call cost against
|
|
192
194
|
the cheapest thing that produces the same inlined shape. Both are asserted to
|
|
193
|
-
produce byte-identical output before either is timed.
|
|
194
|
-
|
|
195
|
+
produce byte-identical output before either is timed. Medians of three runs on each runtime, one machine (Linux x64, a 4-vCPU cloud
|
|
196
|
+
box, Bun 1.4.0 and Node 26.8.1 — your hardware will differ, run `bun run bench`
|
|
197
|
+
or `bun run bench:node` yourself):
|
|
195
198
|
|
|
196
|
-
| schema | cached | naive | speedup |
|
|
197
|
-
|
|
198
|
-
| chain (40 `$ref` → `$ref` links) | ~
|
|
199
|
-
| reuse-heavy (50 refs → 1 def) | ~
|
|
200
|
-
| cyclic tree | ~
|
|
201
|
-
| wide-distinct (60 defs, each used once) | ~3.4k ops/s | ~
|
|
199
|
+
| schema | Bun: cached | Bun: naive | Bun speedup | Node: cached | Node: naive | Node speedup |
|
|
200
|
+
|:---|---:|---:|---:|---:|---:|---:|
|
|
201
|
+
| 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×** |
|
|
202
|
+
| reuse-heavy (50 refs → 1 def) | ~6.9k ops/s | ~11k ops/s | ~0.62× | ~6.6k ops/s | ~10k ops/s | ~0.66× |
|
|
203
|
+
| cyclic tree | ~50k ops/s | ~183k ops/s | ~0.27× | ~58k ops/s | ~184k ops/s | ~0.31× |
|
|
204
|
+
| 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× |
|
|
205
|
+
|
|
206
|
+
The two engines agree on every row to within a few percent, which is what you
|
|
207
|
+
would expect from a resolver whose cost is one document walk rather than a hot
|
|
208
|
+
inner loop.
|
|
202
209
|
|
|
203
210
|
Memoization overtakes the naive walk only on the **chain** shape, where a long
|
|
204
211
|
indirection path is expensive to re-resolve and the cache collapses it to one
|
|
@@ -212,5 +219,6 @@ rows are kept in the table precisely to show that trade honestly rather than
|
|
|
212
219
|
cherry-picking the one shape the cache wins.
|
|
213
220
|
|
|
214
221
|
Opting into `trackOrigins` (which records where each inlined value came from)
|
|
215
|
-
costs nothing measurable on these small schemas: the four
|
|
216
|
-
and +
|
|
222
|
+
costs nothing measurable on these small schemas, on either runtime: the four
|
|
223
|
+
rows land between −9% and +7% on Bun and between −3% and +1% on Node, straddling
|
|
224
|
+
zero in both cases, which is run-to-run noise rather than a price.
|
package/dist/get-by-pointer.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
const decodeSegment = (segment) => {
|
|
2
|
+
if (!segment.includes("%") && !segment.includes("~"))
|
|
3
|
+
return segment;
|
|
2
4
|
let decoded = segment;
|
|
3
5
|
try {
|
|
4
6
|
decoded = decodeURIComponent(segment);
|
|
@@ -11,9 +13,10 @@ const pointerToPath = (pointer) => {
|
|
|
11
13
|
return [];
|
|
12
14
|
return pointer.replace(/^\//, "").split("/").map((segment) => {
|
|
13
15
|
const decoded = decodeSegment(segment);
|
|
14
|
-
return
|
|
16
|
+
return ARRAY_INDEX.test(decoded) ? Number(decoded) : decoded;
|
|
15
17
|
});
|
|
16
18
|
};
|
|
19
|
+
const ARRAY_INDEX = /^(0|[1-9]\d*)$/;
|
|
17
20
|
const isPointerFragment = (fragment) => fragment === "" || fragment.startsWith("/");
|
|
18
21
|
const getByPointer = (root, pointer) => {
|
|
19
22
|
if (pointer === "" || pointer === "/")
|
|
@@ -23,6 +26,8 @@ const getByPointer = (root, pointer) => {
|
|
|
23
26
|
for (const segment of segments) {
|
|
24
27
|
if (current === null || typeof current !== "object")
|
|
25
28
|
return void 0;
|
|
29
|
+
if (Array.isArray(current) && !ARRAY_INDEX.test(segment))
|
|
30
|
+
return void 0;
|
|
26
31
|
const key = Array.isArray(current) ? Number(segment) : segment;
|
|
27
32
|
if (!Object.hasOwn(current, key))
|
|
28
33
|
return void 0;
|
package/dist/reference.js
CHANGED
|
@@ -13,31 +13,36 @@ const readReference = (obj) => {
|
|
|
13
13
|
};
|
|
14
14
|
const search = (root, predicate) => {
|
|
15
15
|
const seen = /* @__PURE__ */ new Set();
|
|
16
|
-
const
|
|
16
|
+
const path = [];
|
|
17
|
+
const walk = (node, depth, role) => {
|
|
17
18
|
if (node === null || typeof node !== "object" || seen.has(node) || depth > DEFAULT_MAX_DEPTH)
|
|
18
19
|
return void 0;
|
|
19
20
|
if (role === "value")
|
|
20
21
|
return void 0;
|
|
21
22
|
seen.add(node);
|
|
22
23
|
if (!Array.isArray(node) && role !== "schemaMap" && predicate(node)) {
|
|
23
|
-
return { value: node, pointer };
|
|
24
|
+
return { value: node, pointer: path.slice() };
|
|
24
25
|
}
|
|
25
26
|
if (Array.isArray(node)) {
|
|
26
27
|
for (let i = 0; i < node.length; i++) {
|
|
27
|
-
|
|
28
|
+
path.push(i);
|
|
29
|
+
const found = walk(node[i], depth + 1, childRole(role, i));
|
|
30
|
+
path.pop();
|
|
28
31
|
if (found)
|
|
29
32
|
return found;
|
|
30
33
|
}
|
|
31
34
|
} else {
|
|
32
35
|
for (const key of Object.keys(node)) {
|
|
33
|
-
|
|
36
|
+
path.push(key);
|
|
37
|
+
const found = walk(node[key], depth + 1, childRole(role, key));
|
|
38
|
+
path.pop();
|
|
34
39
|
if (found)
|
|
35
40
|
return found;
|
|
36
41
|
}
|
|
37
42
|
}
|
|
38
43
|
return void 0;
|
|
39
44
|
};
|
|
40
|
-
return walk(root,
|
|
45
|
+
return walk(root, 0, "schema");
|
|
41
46
|
};
|
|
42
47
|
const resolveFragment = (root, keyword, fragment) => {
|
|
43
48
|
if (keyword === "$recursiveRef") {
|
|
@@ -419,7 +419,9 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
419
419
|
return null;
|
|
420
420
|
return `it resolves outside the allowed roots [${localRoots.join(", ")}] (set allowedRoots to permit it)`;
|
|
421
421
|
};
|
|
422
|
-
if (
|
|
422
|
+
if (options.rootDocument !== void 0) {
|
|
423
|
+
docCache.set(rootLocation, options.rootDocument);
|
|
424
|
+
} else if (!await loadDoc(rootLocation, docCache, options, errors, deadline, [])) {
|
|
423
425
|
return { resolved: {}, errors };
|
|
424
426
|
}
|
|
425
427
|
const registries = /* @__PURE__ */ new Map();
|
package/dist/resolve-refs.js
CHANGED
|
@@ -47,28 +47,10 @@ const resolveNode = (node, base, depth, role, context) => {
|
|
|
47
47
|
});
|
|
48
48
|
return obj;
|
|
49
49
|
};
|
|
50
|
-
let found;
|
|
51
|
-
let targetBase = nodeBase;
|
|
52
|
-
if (keyword === "$recursiveRef") {
|
|
53
|
-
found = resolveFragment(root, keyword, ref.startsWith("#") ? ref.slice(1) : ref);
|
|
54
|
-
targetBase = registry.rootBase;
|
|
55
|
-
} else {
|
|
56
|
-
const scoped = resolveRefInScope(registry, keyword, ref, nodeBase);
|
|
57
|
-
if (scoped === "external")
|
|
58
|
-
return externalRef();
|
|
59
|
-
if (scoped !== void 0) {
|
|
60
|
-
found = scoped;
|
|
61
|
-
targetBase = scoped.base;
|
|
62
|
-
} else if (ref.startsWith("#")) {
|
|
63
|
-
found = resolveFragment(root, keyword, ref.slice(1));
|
|
64
|
-
targetBase = registry.rootBase;
|
|
65
|
-
} else {
|
|
66
|
-
return externalRef();
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
50
|
const cacheKey = `${keyword} ${nodeBase} ${ref}`;
|
|
70
51
|
let target;
|
|
71
52
|
let pointer;
|
|
53
|
+
let targetBase;
|
|
72
54
|
const cached = cache.get(cacheKey);
|
|
73
55
|
if (cached === MISSING)
|
|
74
56
|
return obj;
|
|
@@ -78,7 +60,27 @@ const resolveNode = (node, base, depth, role, context) => {
|
|
|
78
60
|
if (cached !== void 0) {
|
|
79
61
|
target = cached.target;
|
|
80
62
|
pointer = cached.pointer;
|
|
63
|
+
targetBase = cached.base;
|
|
81
64
|
} else {
|
|
65
|
+
let found;
|
|
66
|
+
targetBase = nodeBase;
|
|
67
|
+
if (keyword === "$recursiveRef") {
|
|
68
|
+
found = resolveFragment(root, keyword, ref.startsWith("#") ? ref.slice(1) : ref);
|
|
69
|
+
targetBase = registry.rootBase;
|
|
70
|
+
} else {
|
|
71
|
+
const scoped = resolveRefInScope(registry, keyword, ref, nodeBase);
|
|
72
|
+
if (scoped === "external")
|
|
73
|
+
return externalRef();
|
|
74
|
+
if (scoped !== void 0) {
|
|
75
|
+
found = scoped;
|
|
76
|
+
targetBase = scoped.base;
|
|
77
|
+
} else if (ref.startsWith("#")) {
|
|
78
|
+
found = resolveFragment(root, keyword, ref.slice(1));
|
|
79
|
+
targetBase = registry.rootBase;
|
|
80
|
+
} else {
|
|
81
|
+
return externalRef();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
82
84
|
cache.set(cacheKey, CYCLE);
|
|
83
85
|
if (found === void 0) {
|
|
84
86
|
errors.push({
|
|
@@ -90,7 +92,7 @@ const resolveNode = (node, base, depth, role, context) => {
|
|
|
90
92
|
}
|
|
91
93
|
pointer = found.pointer;
|
|
92
94
|
target = resolveNode(found.value, targetBase, depth + 1, roleAtPath(pointer), context);
|
|
93
|
-
cache.set(cacheKey, { target, pointer });
|
|
95
|
+
cache.set(cacheKey, { target, pointer, base: targetBase });
|
|
94
96
|
if (origins && target !== null && typeof target === "object" && !origins.has(target)) {
|
|
95
97
|
origins.set(target, { location: "", pointer });
|
|
96
98
|
}
|
|
@@ -37,45 +37,51 @@ const buildResourceRegistry = (root, documentBase = SYNTHETIC_BASE, maxDepth = D
|
|
|
37
37
|
if (typeof anchor === "string") {
|
|
38
38
|
const key = `${base}#${anchor}`;
|
|
39
39
|
if (!staticAnchors.has(key))
|
|
40
|
-
staticAnchors.set(key, { value: node, pointer });
|
|
40
|
+
staticAnchors.set(key, { value: node, pointer: pointer.slice() });
|
|
41
41
|
}
|
|
42
42
|
const dynamicAnchor = node["$dynamicAnchor"];
|
|
43
43
|
if (typeof dynamicAnchor === "string") {
|
|
44
44
|
dynamicAnchorCounts.set(dynamicAnchor, (dynamicAnchorCounts.get(dynamicAnchor) ?? 0) + 1);
|
|
45
45
|
const key = `${base}#${dynamicAnchor}`;
|
|
46
46
|
if (!dynamicAnchors.has(key))
|
|
47
|
-
dynamicAnchors.set(key, { value: node, pointer });
|
|
47
|
+
dynamicAnchors.set(key, { value: node, pointer: pointer.slice() });
|
|
48
48
|
if (!staticAnchors.has(key))
|
|
49
|
-
staticAnchors.set(key, { value: node, pointer });
|
|
49
|
+
staticAnchors.set(key, { value: node, pointer: pointer.slice() });
|
|
50
50
|
}
|
|
51
51
|
};
|
|
52
|
-
const
|
|
52
|
+
const path = [];
|
|
53
|
+
const walk = (node, base, depth, role) => {
|
|
53
54
|
if (node === null || typeof node !== "object" || depth > maxDepth || role === "value")
|
|
54
55
|
return;
|
|
55
56
|
if (Array.isArray(node)) {
|
|
56
|
-
for (let i = 0; i < node.length; i++)
|
|
57
|
-
|
|
57
|
+
for (let i = 0; i < node.length; i++) {
|
|
58
|
+
path.push(i);
|
|
59
|
+
walk(node[i], base, depth + 1, childRole(role, i));
|
|
60
|
+
path.pop();
|
|
61
|
+
}
|
|
58
62
|
return;
|
|
59
63
|
}
|
|
60
64
|
const record = node;
|
|
61
65
|
const nodeBase = role === "schemaMap" ? base : baseAfterId(record, base);
|
|
62
66
|
if (nodeBase !== base) {
|
|
63
67
|
if (!resources.has(nodeBase))
|
|
64
|
-
resources.set(nodeBase, { value: node, pointer });
|
|
68
|
+
resources.set(nodeBase, { value: node, pointer: path.slice() });
|
|
65
69
|
if (!bases.has(node))
|
|
66
70
|
bases.set(node, nodeBase);
|
|
67
71
|
}
|
|
68
72
|
if (role !== "schemaMap")
|
|
69
|
-
registerAnchors(record, nodeBase,
|
|
73
|
+
registerAnchors(record, nodeBase, path);
|
|
70
74
|
for (const key of Object.keys(record)) {
|
|
71
|
-
|
|
75
|
+
path.push(key);
|
|
76
|
+
walk(record[key], nodeBase, depth + 1, childRole(role, key));
|
|
77
|
+
path.pop();
|
|
72
78
|
}
|
|
73
79
|
};
|
|
74
80
|
if (rootBase !== initialBase)
|
|
75
81
|
resources.set(rootBase, { value: root, pointer: [] });
|
|
76
82
|
if (!resources.has(initialBase))
|
|
77
83
|
resources.set(initialBase, { value: root, pointer: [] });
|
|
78
|
-
walk(root, initialBase,
|
|
84
|
+
walk(root, initialBase, 0, "schema");
|
|
79
85
|
const ambiguousDynamicAnchors = /* @__PURE__ */ new Set();
|
|
80
86
|
for (const [name, count] of dynamicAnchorCounts) {
|
|
81
87
|
if (count > 1)
|
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
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amritk/resolve-refs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.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",
|
|
@@ -43,7 +43,10 @@
|
|
|
43
43
|
"prepublishOnly": "node ../../scripts/check-publishable.mjs",
|
|
44
44
|
"types:check": "tsgo -p . --noEmit",
|
|
45
45
|
"test": "NODE_ENV=production vitest run --root ../.. resolve-refs",
|
|
46
|
-
"
|
|
46
|
+
"prebench": "bun run build",
|
|
47
|
+
"bench": "bun run ./bench/run.ts",
|
|
48
|
+
"prebench:node": "bun run build",
|
|
49
|
+
"bench:node": "node ./bench/run.ts"
|
|
47
50
|
},
|
|
48
51
|
"exports": {
|
|
49
52
|
".": {
|
|
@@ -52,6 +55,6 @@
|
|
|
52
55
|
}
|
|
53
56
|
},
|
|
54
57
|
"devDependencies": {
|
|
55
|
-
"@amritk/runtime-validators": "^0.
|
|
58
|
+
"@amritk/runtime-validators": "^0.15.1"
|
|
56
59
|
}
|
|
57
60
|
}
|