@amritk/resolve-refs 0.7.0 → 0.8.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 +5 -0
- package/README.md +25 -12
- package/dist/dynamic-scope.js +3 -2
- package/dist/get-by-pointer.d.ts +6 -0
- package/dist/get-by-pointer.js +8 -1
- package/dist/is-private-host.js +2 -0
- package/dist/ref-path-index.d.ts +22 -0
- package/dist/ref-path-index.js +53 -0
- package/dist/reference.d.ts +9 -0
- package/dist/reference.js +14 -7
- package/dist/resolve-refs-from-file.js +56 -45
- package/dist/resolve-refs.js +54 -40
- package/dist/resource-registry.d.ts +18 -9
- package/dist/resource-registry.js +37 -37
- package/dist/split-ref.d.ts +14 -0
- package/dist/split-ref.js +10 -0
- package/dist/types.d.ts +12 -2
- package/package.json +6 -3
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
|
@@ -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. |
|
|
@@ -74,7 +74,13 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
|
|
|
74
74
|
|
|
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
|
+
referencing node is left in place as its `$ref` (nothing is inlined) so the rest
|
|
78
|
+
of the document still resolves.
|
|
79
|
+
Each error carries the `path` to the reference that caused it — a path in the
|
|
80
|
+
document you named, ending in the keyword (`['properties', 'pet', '$ref']`) — so
|
|
81
|
+
a caller can anchor a diagnostic on the `$ref` a reader has to fix. It is empty
|
|
82
|
+
when there is nowhere to point: a budget the resolve as a whole overran, or a
|
|
83
|
+
reference written in some other document.
|
|
78
84
|
|
|
79
85
|
`clearRemoteCache()` drops every cached remote document — useful in tests or
|
|
80
86
|
long-lived sessions where remote schemas may change. Pass a URL
|
|
@@ -185,15 +191,20 @@ recursive cycles intact, and records a diagnostic for every external ref. The
|
|
|
185
191
|
registry, no scoping, no diagnostics — and re-resolves each ref on every
|
|
186
192
|
encounter, so the gap is the production resolver's *total* per-call cost against
|
|
187
193
|
the cheapest thing that produces the same inlined shape. Both are asserted to
|
|
188
|
-
produce byte-identical output before either is timed.
|
|
189
|
-
|
|
194
|
+
produce byte-identical output before either is timed. Medians of three runs on each runtime, one machine (Linux x64, a 4-vCPU cloud
|
|
195
|
+
box, Bun 1.4.0 and Node 26.8.1 — your hardware will differ, run `bun run bench`
|
|
196
|
+
or `bun run bench:node` yourself):
|
|
190
197
|
|
|
191
|
-
| schema | cached | naive | speedup |
|
|
192
|
-
|
|
193
|
-
| chain (40 `$ref` → `$ref` links) | ~
|
|
194
|
-
| reuse-heavy (50 refs → 1 def) | ~
|
|
195
|
-
| cyclic tree | ~
|
|
196
|
-
| wide-distinct (60 defs, each used once) | ~
|
|
198
|
+
| schema | Bun: cached | Bun: naive | Bun speedup | Node: cached | Node: naive | Node speedup |
|
|
199
|
+
|:---|---:|---:|---:|---:|---:|---:|
|
|
200
|
+
| chain (40 `$ref` → `$ref` links) | ~4.6k ops/s | ~1.1k ops/s | **~4.1×** | ~4.7k ops/s | ~1.1k ops/s | **~4.1×** |
|
|
201
|
+
| reuse-heavy (50 refs → 1 def) | ~6.9k ops/s | ~11k ops/s | ~0.62× | ~6.6k ops/s | ~10k ops/s | ~0.66× |
|
|
202
|
+
| cyclic tree | ~50k ops/s | ~183k ops/s | ~0.27× | ~58k ops/s | ~184k ops/s | ~0.31× |
|
|
203
|
+
| wide-distinct (60 defs, each used once) | ~3.7k ops/s | ~9.5k ops/s | ~0.39× | ~3.4k ops/s | ~9.0k ops/s | ~0.38× |
|
|
204
|
+
|
|
205
|
+
The two engines agree on every row to within a few percent, which is what you
|
|
206
|
+
would expect from a resolver whose cost is one document walk rather than a hot
|
|
207
|
+
inner loop.
|
|
197
208
|
|
|
198
209
|
Memoization overtakes the naive walk only on the **chain** shape, where a long
|
|
199
210
|
indirection path is expensive to re-resolve and the cache collapses it to one
|
|
@@ -206,5 +217,7 @@ result rather than re-resolving. The `reuse-heavy`, `cyclic`, and `wide-distinct
|
|
|
206
217
|
rows are kept in the table precisely to show that trade honestly rather than
|
|
207
218
|
cherry-picking the one shape the cache wins.
|
|
208
219
|
|
|
209
|
-
Opting into `trackOrigins` (which records where each inlined value came from)
|
|
210
|
-
|
|
220
|
+
Opting into `trackOrigins` (which records where each inlined value came from)
|
|
221
|
+
costs nothing measurable on these small schemas, on either runtime: the four
|
|
222
|
+
rows land between −9% and +7% on Bun and between −3% and +1% on Node, straddling
|
|
223
|
+
zero in both cases, which is run-to-run noise rather than a price.
|
package/dist/dynamic-scope.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { baseAfterId
|
|
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 } =
|
|
6
|
+
const { fragment } = splitRef(ref);
|
|
6
7
|
if (fragment === "" || fragment.startsWith("/"))
|
|
7
8
|
return false;
|
|
8
9
|
return ambiguousAnchors.has(fragment);
|
package/dist/get-by-pointer.d.ts
CHANGED
|
@@ -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
|
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,11 @@ 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*)$/;
|
|
20
|
+
const isPointerFragment = (fragment) => fragment === "" || fragment.startsWith("/");
|
|
17
21
|
const getByPointer = (root, pointer) => {
|
|
18
22
|
if (pointer === "" || pointer === "/")
|
|
19
23
|
return root;
|
|
@@ -22,6 +26,8 @@ const getByPointer = (root, pointer) => {
|
|
|
22
26
|
for (const segment of segments) {
|
|
23
27
|
if (current === null || typeof current !== "object")
|
|
24
28
|
return void 0;
|
|
29
|
+
if (Array.isArray(current) && !ARRAY_INDEX.test(segment))
|
|
30
|
+
return void 0;
|
|
25
31
|
const key = Array.isArray(current) ? Number(segment) : segment;
|
|
26
32
|
if (!Object.hasOwn(current, key))
|
|
27
33
|
return void 0;
|
|
@@ -31,5 +37,6 @@ const getByPointer = (root, pointer) => {
|
|
|
31
37
|
};
|
|
32
38
|
export {
|
|
33
39
|
getByPointer,
|
|
40
|
+
isPointerFragment,
|
|
34
41
|
pointerToPath
|
|
35
42
|
};
|
package/dist/is-private-host.js
CHANGED
|
@@ -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
|
+
};
|
package/dist/reference.d.ts
CHANGED
|
@@ -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,34 +11,38 @@ 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
|
-
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") {
|
|
@@ -54,6 +59,8 @@ const resolveFragment = (root, keyword, fragment) => {
|
|
|
54
59
|
return search(root, (obj) => obj["$anchor"] === fragment || obj["$dynamicAnchor"] === fragment);
|
|
55
60
|
};
|
|
56
61
|
export {
|
|
62
|
+
ANNOTATION_ONLY_SIBLINGS,
|
|
63
|
+
REF_KEYWORDS,
|
|
57
64
|
readReference,
|
|
58
65
|
resolveFragment
|
|
59
66
|
};
|
|
@@ -4,32 +4,30 @@ import { dirname, relative as relativePath, resolve as resolvePath, sep } from "
|
|
|
4
4
|
import { assertPublicHost } from "./assert-public-host.js";
|
|
5
5
|
import { childRole } from "./child-role.js";
|
|
6
6
|
import { bindsAtEvaluationTime, declaresAmbiguousAnchor, inliningKeepsScope, isScopeSensitive } from "./dynamic-scope.js";
|
|
7
|
-
import { 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 {
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
}
|
|
@@ -331,12 +331,14 @@ const detach = (node) => {
|
|
|
331
331
|
const rebaseKeptRef = (value, from, root) => {
|
|
332
332
|
if (from === root)
|
|
333
333
|
return value;
|
|
334
|
-
const { filePart, fragment } = splitRef(value);
|
|
334
|
+
const { uriPart: filePart, fragment } = splitRef(value);
|
|
335
335
|
if (filePart === "")
|
|
336
336
|
return `${renderLocation(from, root)}${value}`;
|
|
337
337
|
if (/^[a-zA-Z][a-zA-Z0-9+.-]+:/.test(filePart))
|
|
338
338
|
return value;
|
|
339
339
|
const target = joinLocation(from, filePart);
|
|
340
|
+
if (target === void 0)
|
|
341
|
+
return value;
|
|
340
342
|
const suffix = value.includes("#") ? `#${fragment}` : "";
|
|
341
343
|
return `${renderLocation(target, root)}${suffix}`;
|
|
342
344
|
};
|
|
@@ -417,7 +419,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
417
419
|
return null;
|
|
418
420
|
return `it resolves outside the allowed roots [${localRoots.join(", ")}] (set allowedRoots to permit it)`;
|
|
419
421
|
};
|
|
420
|
-
if (!await loadDoc(rootLocation, docCache, options, errors, deadline)) {
|
|
422
|
+
if (!await loadDoc(rootLocation, docCache, options, errors, deadline, [])) {
|
|
421
423
|
return { resolved: {}, errors };
|
|
422
424
|
}
|
|
423
425
|
const registries = /* @__PURE__ */ new Map();
|
|
@@ -429,6 +431,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
429
431
|
}
|
|
430
432
|
return registry;
|
|
431
433
|
};
|
|
434
|
+
const refPathAt = refPathIndex(docCache.get(rootLocation), maxDepth);
|
|
432
435
|
let depthLimitReported = false;
|
|
433
436
|
const reportDepthLimit = () => {
|
|
434
437
|
if (depthLimitReported)
|
|
@@ -457,9 +460,9 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
457
460
|
if (reference && reference.keyword !== "$recursiveRef") {
|
|
458
461
|
const scoped = resolveRefInScope(registry, reference.keyword, reference.value, nodeBase);
|
|
459
462
|
if (scoped === "external") {
|
|
460
|
-
const { filePart } = splitRef(reference.value);
|
|
461
|
-
if (filePart !== "")
|
|
462
|
-
out.
|
|
463
|
+
const { uriPart: filePart } = splitRef(reference.value);
|
|
464
|
+
if (filePart !== "" && !out.has(filePart))
|
|
465
|
+
out.set(filePart, reference);
|
|
463
466
|
}
|
|
464
467
|
}
|
|
465
468
|
for (const key of Object.keys(obj)) {
|
|
@@ -474,10 +477,18 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
474
477
|
let loaded = 1;
|
|
475
478
|
while (queue.length > 0) {
|
|
476
479
|
const location = queue.shift();
|
|
477
|
-
const out = /* @__PURE__ */ new
|
|
480
|
+
const out = /* @__PURE__ */ new Map();
|
|
478
481
|
collectRefTargets(docCache.get(location), location, registryFor(location).rootBase, out, 0, "schema");
|
|
479
|
-
for (const filePart of out) {
|
|
482
|
+
for (const [filePart, reference] of out) {
|
|
483
|
+
const refPath = location === rootLocation ? refPathAt(reference.keyword, reference.value) : [];
|
|
480
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
|
+
}
|
|
481
492
|
if (seen.has(target))
|
|
482
493
|
continue;
|
|
483
494
|
seen.add(target);
|
|
@@ -498,14 +509,14 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
498
509
|
if (!isRemote(target)) {
|
|
499
510
|
const reason = localDenialReason(target);
|
|
500
511
|
if (reason !== null) {
|
|
501
|
-
errors.push({ message: `Refusing to read local $ref (${reason}): ${target}`, path:
|
|
512
|
+
errors.push({ message: `Refusing to read local $ref (${reason}): ${target}`, path: refPath });
|
|
502
513
|
docCache.set(target, {});
|
|
503
514
|
unloadable.add(target);
|
|
504
515
|
continue;
|
|
505
516
|
}
|
|
506
517
|
}
|
|
507
518
|
loaded++;
|
|
508
|
-
if (!await loadDoc(target, docCache, options, errors, deadline))
|
|
519
|
+
if (!await loadDoc(target, docCache, options, errors, deadline, refPath))
|
|
509
520
|
unloadable.add(target);
|
|
510
521
|
queue.push(target);
|
|
511
522
|
}
|
|
@@ -566,8 +577,11 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
566
577
|
if (inScope === "external" || inScope === void 0) {
|
|
567
578
|
const parts = splitRef(value);
|
|
568
579
|
fragment = parts.fragment;
|
|
569
|
-
if (inScope === "external" && parts.
|
|
570
|
-
|
|
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;
|
|
571
585
|
}
|
|
572
586
|
} else {
|
|
573
587
|
scoped = inScope;
|
|
@@ -605,18 +619,8 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
605
619
|
hoistRefSites.set(kept, cacheKey);
|
|
606
620
|
return kept;
|
|
607
621
|
}
|
|
608
|
-
const keepUnresolved = () => {
|
|
609
|
-
const kept = {};
|
|
610
|
-
for (const key of Object.keys(obj)) {
|
|
611
|
-
if (key === keyword)
|
|
612
|
-
continue;
|
|
613
|
-
assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
|
|
614
|
-
}
|
|
615
|
-
assignKey(kept, keyword, keyword === "$ref" ? rebaseKeptRef(value, baseLocation, rootLocation) : value);
|
|
616
|
-
return kept;
|
|
617
|
-
};
|
|
618
622
|
if (cached === MISSING)
|
|
619
|
-
return
|
|
623
|
+
return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
|
|
620
624
|
if (cached !== void 0) {
|
|
621
625
|
resolved2 = cached.value;
|
|
622
626
|
pointer = cached.pointer;
|
|
@@ -649,11 +653,18 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
649
653
|
if (targetLoaded) {
|
|
650
654
|
errors.push({
|
|
651
655
|
message: `Cannot resolve ${keyword} "${value}"`,
|
|
652
|
-
|
|
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) : []
|
|
653
664
|
});
|
|
654
665
|
}
|
|
655
666
|
refCache.set(cacheKey, MISSING);
|
|
656
|
-
return
|
|
667
|
+
return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
|
|
657
668
|
}
|
|
658
669
|
pointer = found?.pointer ?? [];
|
|
659
670
|
resolved2 = resolveAt(found?.value, targetLocation, targetBase, depth + 1, roleAtPath(pointer));
|
package/dist/resolve-refs.js
CHANGED
|
@@ -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 {
|
|
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
|
|
12
|
-
const
|
|
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 >
|
|
18
|
-
|
|
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) =>
|
|
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] :
|
|
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,32 +43,14 @@ 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
|
};
|
|
53
|
-
let found;
|
|
54
|
-
let targetBase = nodeBase;
|
|
55
|
-
if (keyword === "$recursiveRef") {
|
|
56
|
-
found = resolveFragment(root, keyword, ref.startsWith("#") ? ref.slice(1) : ref);
|
|
57
|
-
targetBase = registry.rootBase;
|
|
58
|
-
} else {
|
|
59
|
-
const scoped = resolveRefInScope(registry, keyword, ref, nodeBase);
|
|
60
|
-
if (scoped === "external")
|
|
61
|
-
return externalRef();
|
|
62
|
-
if (scoped !== void 0) {
|
|
63
|
-
found = scoped;
|
|
64
|
-
targetBase = scoped.base;
|
|
65
|
-
} else if (ref.startsWith("#")) {
|
|
66
|
-
found = resolveFragment(root, keyword, ref.slice(1));
|
|
67
|
-
targetBase = registry.rootBase;
|
|
68
|
-
} else {
|
|
69
|
-
return externalRef();
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
50
|
const cacheKey = `${keyword} ${nodeBase} ${ref}`;
|
|
73
51
|
let target;
|
|
74
52
|
let pointer;
|
|
53
|
+
let targetBase;
|
|
75
54
|
const cached = cache.get(cacheKey);
|
|
76
55
|
if (cached === MISSING)
|
|
77
56
|
return obj;
|
|
@@ -81,20 +60,39 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
|
|
|
81
60
|
if (cached !== void 0) {
|
|
82
61
|
target = cached.target;
|
|
83
62
|
pointer = cached.pointer;
|
|
63
|
+
targetBase = cached.base;
|
|
84
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
|
+
}
|
|
85
84
|
cache.set(cacheKey, CYCLE);
|
|
86
85
|
if (found === void 0) {
|
|
87
|
-
const fragment = ref.startsWith("#") ? ref.slice(1) : ref;
|
|
88
86
|
errors.push({
|
|
89
87
|
message: `Cannot resolve internal ${keyword} "${ref}"`,
|
|
90
|
-
path:
|
|
88
|
+
path: refPathAt(keyword, ref)
|
|
91
89
|
});
|
|
92
90
|
cache.set(cacheKey, MISSING);
|
|
93
91
|
return obj;
|
|
94
92
|
}
|
|
95
93
|
pointer = found.pointer;
|
|
96
|
-
target =
|
|
97
|
-
cache.set(cacheKey, { target, pointer });
|
|
94
|
+
target = resolveNode(found.value, targetBase, depth + 1, roleAtPath(pointer), context);
|
|
95
|
+
cache.set(cacheKey, { target, pointer, base: targetBase });
|
|
98
96
|
if (origins && target !== null && typeof target === "object" && !origins.has(target)) {
|
|
99
97
|
origins.set(target, { location: "", pointer });
|
|
100
98
|
}
|
|
@@ -108,7 +106,7 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
|
|
|
108
106
|
const siblings = {};
|
|
109
107
|
let siblingIsSensitive = false;
|
|
110
108
|
for (const key of siblingKeys) {
|
|
111
|
-
const child =
|
|
109
|
+
const child = resolveNode(obj[key], nodeBase, depth + 1, childRole(role, key), context);
|
|
112
110
|
assignKey(siblings, key, child);
|
|
113
111
|
if (isScopeSensitive(sensitive, child))
|
|
114
112
|
siblingIsSensitive = true;
|
|
@@ -139,7 +137,7 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
|
|
|
139
137
|
}
|
|
140
138
|
const result = {};
|
|
141
139
|
for (const key of Object.keys(obj)) {
|
|
142
|
-
const child =
|
|
140
|
+
const child = resolveNode(obj[key], nodeBase, depth + 1, childRole(role, key), context);
|
|
143
141
|
assignKey(result, key, child);
|
|
144
142
|
if (isScopeSensitive(sensitive, child))
|
|
145
143
|
sensitive.add(result);
|
|
@@ -151,9 +149,25 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
|
|
|
151
149
|
const resolveRefs = (data, options = {}) => {
|
|
152
150
|
const origins = options.trackOrigins ? /* @__PURE__ */ new Map() : void 0;
|
|
153
151
|
const errors = [];
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
const
|
|
152
|
+
const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
|
|
153
|
+
let depthLimitReported = false;
|
|
154
|
+
const context = {
|
|
155
|
+
root: data,
|
|
156
|
+
registry: buildResourceRegistry(data, void 0, maxDepth),
|
|
157
|
+
cache: /* @__PURE__ */ new Map(),
|
|
158
|
+
origins,
|
|
159
|
+
errors,
|
|
160
|
+
sensitive: /* @__PURE__ */ new WeakSet(),
|
|
161
|
+
maxDepth,
|
|
162
|
+
refPathAt: refPathIndex(data, maxDepth),
|
|
163
|
+
reportDepthLimit: () => {
|
|
164
|
+
if (depthLimitReported)
|
|
165
|
+
return;
|
|
166
|
+
depthLimitReported = true;
|
|
167
|
+
errors.push(depthLimitError(maxDepth));
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
const resolved = resolveNode(data, context.registry.rootBase, 0, "schema", context);
|
|
157
171
|
return origins ? { resolved, errors, origins } : { resolved, errors };
|
|
158
172
|
};
|
|
159
173
|
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,
|
|
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
|
|
96
|
-
*
|
|
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,
|
|
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();
|
|
@@ -41,75 +37,80 @@ const buildResourceRegistry = (root, initialBase = SYNTHETIC_BASE, maxDepth = DE
|
|
|
41
37
|
if (typeof anchor === "string") {
|
|
42
38
|
const key = `${base}#${anchor}`;
|
|
43
39
|
if (!staticAnchors.has(key))
|
|
44
|
-
staticAnchors.set(key, { value: node, pointer });
|
|
40
|
+
staticAnchors.set(key, { value: node, pointer: pointer.slice() });
|
|
45
41
|
}
|
|
46
42
|
const dynamicAnchor = node["$dynamicAnchor"];
|
|
47
43
|
if (typeof dynamicAnchor === "string") {
|
|
48
44
|
dynamicAnchorCounts.set(dynamicAnchor, (dynamicAnchorCounts.get(dynamicAnchor) ?? 0) + 1);
|
|
49
45
|
const key = `${base}#${dynamicAnchor}`;
|
|
50
46
|
if (!dynamicAnchors.has(key))
|
|
51
|
-
dynamicAnchors.set(key, { value: node, pointer });
|
|
47
|
+
dynamicAnchors.set(key, { value: node, pointer: pointer.slice() });
|
|
52
48
|
if (!staticAnchors.has(key))
|
|
53
|
-
staticAnchors.set(key, { value: node, pointer });
|
|
49
|
+
staticAnchors.set(key, { value: node, pointer: pointer.slice() });
|
|
54
50
|
}
|
|
55
51
|
};
|
|
56
|
-
const
|
|
52
|
+
const path = [];
|
|
53
|
+
const walk = (node, base, depth, role) => {
|
|
57
54
|
if (node === null || typeof node !== "object" || depth > maxDepth || role === "value")
|
|
58
55
|
return;
|
|
59
56
|
if (Array.isArray(node)) {
|
|
60
|
-
for (let i = 0; i < node.length; i++)
|
|
61
|
-
|
|
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
|
+
}
|
|
62
62
|
return;
|
|
63
63
|
}
|
|
64
64
|
const record = node;
|
|
65
65
|
const nodeBase = role === "schemaMap" ? base : baseAfterId(record, base);
|
|
66
|
-
if (nodeBase !== base
|
|
67
|
-
resources.
|
|
66
|
+
if (nodeBase !== base) {
|
|
67
|
+
if (!resources.has(nodeBase))
|
|
68
|
+
resources.set(nodeBase, { value: node, pointer: path.slice() });
|
|
69
|
+
if (!bases.has(node))
|
|
70
|
+
bases.set(node, nodeBase);
|
|
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
|
-
if (!resources.has(
|
|
77
|
-
resources.set(
|
|
78
|
-
|
|
79
|
-
walk(root, initialBase, [], 0, "schema");
|
|
82
|
+
if (!resources.has(initialBase))
|
|
83
|
+
resources.set(initialBase, { value: root, pointer: [] });
|
|
84
|
+
walk(root, initialBase, 0, "schema");
|
|
80
85
|
const ambiguousDynamicAnchors = /* @__PURE__ */ new Set();
|
|
81
86
|
for (const [name, count] of dynamicAnchorCounts) {
|
|
82
87
|
if (count > 1)
|
|
83
88
|
ambiguousDynamicAnchors.add(name);
|
|
84
89
|
}
|
|
85
|
-
return { resources, staticAnchors, dynamicAnchors, ambiguousDynamicAnchors, rootBase, root };
|
|
90
|
+
return { resources, bases, staticAnchors, dynamicAnchors, ambiguousDynamicAnchors, rootBase, root };
|
|
86
91
|
};
|
|
87
92
|
const getByPointerWithBase = (start, startBase, startPointer, fragment) => {
|
|
88
93
|
const value = getByPointer(start, fragment);
|
|
89
94
|
if (value === void 0)
|
|
90
95
|
return void 0;
|
|
96
|
+
const path = pointerToPath(fragment);
|
|
91
97
|
let base = startBase;
|
|
92
98
|
let current = start;
|
|
93
|
-
for (const segment of
|
|
99
|
+
for (const segment of path) {
|
|
94
100
|
if (current === null || typeof current !== "object")
|
|
95
101
|
break;
|
|
96
102
|
if (!Array.isArray(current))
|
|
97
103
|
base = baseAfterId(current, base);
|
|
104
|
+
if (!Object.hasOwn(current, segment))
|
|
105
|
+
break;
|
|
98
106
|
current = current[segment];
|
|
99
107
|
}
|
|
100
108
|
if (current !== null && typeof current === "object" && !Array.isArray(current)) {
|
|
101
109
|
base = baseAfterId(current, base);
|
|
102
110
|
}
|
|
103
|
-
return { value, pointer: [...startPointer, ...
|
|
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;
|
|
111
|
+
return { value, pointer: [...startPointer, ...path], base };
|
|
112
112
|
};
|
|
113
|
+
const baseOfNode = (registry, node, enclosing) => registry.bases.get(node) ?? enclosing;
|
|
113
114
|
const lookupAnchor = (registry, keyword, base, name) => {
|
|
114
115
|
const key = `${base}#${name}`;
|
|
115
116
|
if (keyword === "$dynamicRef")
|
|
@@ -117,7 +118,7 @@ const lookupAnchor = (registry, keyword, base, name) => {
|
|
|
117
118
|
return registry.staticAnchors.get(key);
|
|
118
119
|
};
|
|
119
120
|
const resolveRefInScope = (registry, keyword, ref, currentBase) => {
|
|
120
|
-
const { uriPart, fragment } =
|
|
121
|
+
const { uriPart, fragment } = splitRef(ref);
|
|
121
122
|
if (uriPart === "") {
|
|
122
123
|
if (isPointerFragment(fragment)) {
|
|
123
124
|
const resource2 = registry.resources.get(currentBase);
|
|
@@ -150,6 +151,5 @@ export {
|
|
|
150
151
|
baseOfNode,
|
|
151
152
|
buildResourceRegistry,
|
|
152
153
|
resolveRefInScope,
|
|
153
|
-
resolveUri
|
|
154
|
-
splitFragment
|
|
154
|
+
resolveUri
|
|
155
155
|
};
|
|
@@ -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
|
+
};
|
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.
|
|
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.
|
|
3
|
+
"version": "0.8.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
|
}
|