@amritk/resolve-refs 0.0.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 ADDED
@@ -0,0 +1,48 @@
1
+ # @amritk/resolve-refs
2
+
3
+ Resolve and inline JSON Schema / OpenAPI `$ref`s — internal pointers, cross-file
4
+ refs, and remote (http/https) documents — into a single dereferenced document.
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.
8
+ - **Cross-file + remote.** Relative refs resolve against the document they appear
9
+ in (a ref inside a remote doc stays remote, one inside a local file stays
10
+ local). Fetched remote documents are cached for the lifetime of the process.
11
+ - **Default-deny SSRF guard.** Remote refs to loopback, private, link-local, and
12
+ cloud-metadata (`169.254.169.254`) hosts are refused unless you opt in.
13
+
14
+ ## Usage
15
+
16
+ ```ts
17
+ import { resolveRefs, resolveRefsFromFile } from '@amritk/resolve-refs'
18
+
19
+ // In-memory, internal (#/...) refs only:
20
+ const { resolved } = resolveRefs(myDocument)
21
+
22
+ // From disk or a URL, including cross-file and remote refs:
23
+ const result = await resolveRefsFromFile('./schema.json')
24
+ const remote = await resolveRefsFromFile('https://api.example.com/schema.json', {
25
+ allowedHosts: ['api.example.com'],
26
+ })
27
+ ```
28
+
29
+ ### Options (`resolveRefsFromFile`)
30
+
31
+ | Option | Default | Description |
32
+ |:---|:---|:---|
33
+ | `remote` | `true` | Whether http(s) refs may be fetched at all. |
34
+ | `allowedHosts` | `[]` | If non-empty, only these hosts may be fetched. An explicit entry bypasses the private-host guard. |
35
+ | `allowPrivateHosts` | `false` | Allow loopback/private/link-local targets. Left off, these are refused as an SSRF guard. |
36
+
37
+ Errors (a missing file, a refused host, a bad URL) are collected on
38
+ `result.errors` rather than thrown; the corresponding ref resolves to `{}` so the
39
+ rest of the document still resolves.
40
+
41
+ `clearRemoteCache()` drops every cached remote document — useful in tests or
42
+ long-lived sessions where remote schemas may change.
43
+
44
+ ## Documents
45
+
46
+ Every document — local file or remote — is parsed as **JSON**. mjst works with
47
+ JSON Schema documents only, so this resolver stays JSON-only and dependency-free.
48
+ (The Loupe linter's sibling resolver additionally accepts YAML.)
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Walks a JSON Pointer string (RFC 6901) to the value it points to within
3
+ * `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
4
+ * decoded (`~1` → `/`, `~0` → `~`). Returns `undefined` when any segment along
5
+ * the path is missing or traverses a non-object.
6
+ */
7
+ export declare const getByPointer: (root: unknown, pointer: string) => unknown;
8
+ //# sourceMappingURL=get-by-pointer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-by-pointer.d.ts","sourceRoot":"","sources":["../src/get-by-pointer.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,eAAO,MAAM,YAAY,SAAU,OAAO,WAAW,MAAM,KAAG,OAe7D,CAAA"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Walks a JSON Pointer string (RFC 6901) to the value it points to within
3
+ * `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
4
+ * decoded (`~1` → `/`, `~0` → `~`). Returns `undefined` when any segment along
5
+ * the path is missing or traverses a non-object.
6
+ */
7
+ export const getByPointer = (root, pointer) => {
8
+ if (pointer === '' || pointer === '/')
9
+ return root;
10
+ const segments = pointer
11
+ .replace(/^\//, '')
12
+ .split('/')
13
+ .map((segment) => segment.replace(/~1/g, '/').replace(/~0/g, '~'));
14
+ let current = root;
15
+ for (const segment of segments) {
16
+ if (current === null || typeof current !== 'object')
17
+ return undefined;
18
+ const key = Array.isArray(current) ? Number(segment) : segment;
19
+ current = current[key];
20
+ }
21
+ return current;
22
+ };
@@ -0,0 +1,6 @@
1
+ export { getByPointer } from './get-by-pointer.js';
2
+ export { isPrivateHost } from './is-private-host.js';
3
+ export { resolveRefs } from './resolve-refs.js';
4
+ export { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file.js';
5
+ export type { JsonPath, ResolveError, ResolveOptions, ResolveResult } from './types.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC5C,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AAChF,YAAY,EAAE,QAAQ,EAAE,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { getByPointer } from './get-by-pointer.js';
2
+ export { isPrivateHost } from './is-private-host.js';
3
+ export { resolveRefs } from './resolve-refs.js';
4
+ export { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file.js';
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Best-effort check for a hostname that resolves to a non-public address —
3
+ * loopback, private (RFC 1918 / ULA), link-local (incl. the `169.254.169.254`
4
+ * cloud-metadata endpoint), or otherwise host-local. This is a syntactic guard
5
+ * on the URL only; it does not perform DNS, so a public name that resolves to a
6
+ * private IP is not caught here. It exists to stop the obvious SSRF footguns
7
+ * when resolving remote `$ref`s.
8
+ */
9
+ export declare const isPrivateHost: (hostname: string) => boolean;
10
+ //# sourceMappingURL=is-private-host.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"is-private-host.d.ts","sourceRoot":"","sources":["../src/is-private-host.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa,aAAc,MAAM,KAAG,OAyBhD,CAAA"}
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Best-effort check for a hostname that resolves to a non-public address —
3
+ * loopback, private (RFC 1918 / ULA), link-local (incl. the `169.254.169.254`
4
+ * cloud-metadata endpoint), or otherwise host-local. This is a syntactic guard
5
+ * on the URL only; it does not perform DNS, so a public name that resolves to a
6
+ * private IP is not caught here. It exists to stop the obvious SSRF footguns
7
+ * when resolving remote `$ref`s.
8
+ */
9
+ export const isPrivateHost = (hostname) => {
10
+ const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
11
+ if (host === 'localhost' || host.endsWith('.localhost'))
12
+ return true;
13
+ // IPv4 (incl. IPv4-mapped IPv6 like ::ffff:127.0.0.1)
14
+ const v4 = host.match(/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
15
+ if (v4) {
16
+ const a = Number(v4[1]);
17
+ const b = Number(v4[2]);
18
+ if (a === 10 || a === 127 || a === 0)
19
+ return true;
20
+ if (a === 169 && b === 254)
21
+ return true; // link-local + metadata
22
+ if (a === 172 && b >= 16 && b <= 31)
23
+ return true;
24
+ if (a === 192 && b === 168)
25
+ return true;
26
+ if (a === 100 && b >= 64 && b <= 127)
27
+ return true; // CGNAT
28
+ return false;
29
+ }
30
+ // IPv6
31
+ if (host.includes(':')) {
32
+ if (host === '::1' || host === '::')
33
+ return true;
34
+ if (host.startsWith('fe80:') || host.startsWith('fe80::'))
35
+ return true; // link-local
36
+ if (host.startsWith('fc') || host.startsWith('fd'))
37
+ return true; // unique-local
38
+ return false;
39
+ }
40
+ return false;
41
+ };
@@ -0,0 +1,10 @@
1
+ import type { ResolveOptions, ResolveResult } from './types.js';
2
+ /** Drops every cached remote document. Mainly useful for tests/long sessions. */
3
+ export declare const clearRemoteCache: () => void;
4
+ /**
5
+ * Resolves `$ref`s in a document on disk (or at a URL), including cross-file
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.
8
+ */
9
+ export declare const resolveRefsFromFile: (filename: string, options?: ResolveOptions) => Promise<ResolveResult>;
10
+ //# sourceMappingURL=resolve-refs-from-file.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-refs-from-file.d.ts","sourceRoot":"","sources":["../src/resolve-refs-from-file.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAgB,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AA+C1E,iFAAiF;AACjF,eAAO,MAAM,gBAAgB,QAAO,IAEnC,CAAA;AAmKD;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,aAAoB,MAAM,YAAW,cAAc,KAAQ,OAAO,CAAC,aAAa,CAW/G,CAAA"}
@@ -0,0 +1,210 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, resolve as resolvePath } from 'node:path';
3
+ import { getByPointer } from './get-by-pointer.js';
4
+ import { isPrivateHost } from './is-private-host.js';
5
+ // A ref currently mid-resolution is marked with this sentinel; revisiting it
6
+ // means a cycle, so we return `{}` instead of recursing forever.
7
+ const CYCLE = Symbol('cycle');
8
+ // --- Document location helpers ---------------------------------------------
9
+ //
10
+ // A "location" is the absolute identity of a document: either an absolute file
11
+ // path or an absolute http(s) URL. Refs are resolved relative to the location
12
+ // of the document they appear in, so a relative ref inside a remote document
13
+ // resolves to another remote URL, and one inside a local file to another path.
14
+ const isRemote = (location) => /^https?:\/\//i.test(location);
15
+ /** Resolves the location of `ref` (its file/URL part) relative to `base`. */
16
+ const joinLocation = (base, ref) => {
17
+ if (isRemote(ref))
18
+ return ref;
19
+ if (isRemote(base))
20
+ return new URL(ref, base).href;
21
+ return resolvePath(dirname(base), ref);
22
+ };
23
+ /** Splits a `$ref` into its document part and JSON-pointer part. */
24
+ const splitRef = (ref) => {
25
+ const hashIdx = ref.indexOf('#');
26
+ return {
27
+ filePart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
28
+ pointer: hashIdx === -1 ? '' : ref.slice(hashIdx + 1),
29
+ };
30
+ };
31
+ // mjst deals only in JSON Schema documents, so every document — local or
32
+ // remote — is parsed as JSON. (The Loupe linter's sibling resolver additionally
33
+ // accepts YAML; this one stays JSON-only to keep the package dependency-free.)
34
+ const parseContent = (content) => JSON.parse(content);
35
+ // --- Remote document cache -------------------------------------------------
36
+ //
37
+ // Fetched remote documents are cached in memory for the lifetime of the
38
+ // process ("the session"). Local files are intentionally NOT cached across
39
+ // resolve passes — they can change on disk during a long-lived session (e.g.
40
+ // an editor/LSP), so each pass re-reads them. Remote documents are assumed
41
+ // stable for the session; call `clearRemoteCache()` to drop them.
42
+ const remoteCache = new Map();
43
+ /** Drops every cached remote document. Mainly useful for tests/long sessions. */
44
+ export const clearRemoteCache = () => {
45
+ remoteCache.clear();
46
+ };
47
+ /** Returns why a remote location may not be fetched, or `null` if it is allowed. */
48
+ const denialReason = (location, options) => {
49
+ if (options.remote === false)
50
+ return 'remote $ref resolution is disabled';
51
+ let url;
52
+ try {
53
+ url = new URL(location);
54
+ }
55
+ catch {
56
+ return 'the URL is invalid';
57
+ }
58
+ const allow = options.allowedHosts;
59
+ // An explicit allow-list entry is an intentional opt-in and bypasses the
60
+ // private-host guard; otherwise refuse non-public targets by default.
61
+ if (allow && allow.length > 0) {
62
+ return allow.includes(url.host) ? null : 'host is not in the allow-list';
63
+ }
64
+ if (!options.allowPrivateHosts && isPrivateHost(url.hostname)) {
65
+ return 'host resolves to a private or loopback address (set allowPrivateHosts to permit)';
66
+ }
67
+ return null;
68
+ };
69
+ /**
70
+ * Loads a document into `docCache`, fetching/reading it if needed. Remote
71
+ * documents are additionally cached for the session in `remoteCache`. On
72
+ * failure an error is recorded and the location is cached as `{}` so that
73
+ * pointer lookups degrade gracefully instead of throwing. Returns whether the
74
+ * document loaded successfully.
75
+ */
76
+ const loadDoc = async (location, docCache, options, errors) => {
77
+ if (docCache.has(location))
78
+ return true;
79
+ if (isRemote(location)) {
80
+ if (remoteCache.has(location)) {
81
+ docCache.set(location, remoteCache.get(location));
82
+ return true;
83
+ }
84
+ const reason = denialReason(location, options);
85
+ if (reason !== null) {
86
+ errors.push({ message: `Refusing to resolve remote $ref (${reason}): ${location}`, path: [] });
87
+ docCache.set(location, {});
88
+ return false;
89
+ }
90
+ try {
91
+ const response = await fetch(location);
92
+ if (!response.ok)
93
+ throw new Error(`HTTP ${response.status} ${response.statusText}`);
94
+ const doc = parseContent(await response.text());
95
+ remoteCache.set(location, doc);
96
+ docCache.set(location, doc);
97
+ return true;
98
+ }
99
+ catch (err) {
100
+ errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: [] });
101
+ docCache.set(location, {});
102
+ return false;
103
+ }
104
+ }
105
+ try {
106
+ docCache.set(location, parseContent(readFileSync(location, 'utf8')));
107
+ return true;
108
+ }
109
+ catch (err) {
110
+ errors.push({ message: String(err), path: [] });
111
+ docCache.set(location, {});
112
+ return false;
113
+ }
114
+ };
115
+ /** Collects the distinct document parts of every `$ref` directly under `node`. */
116
+ const collectRefTargets = (node, out) => {
117
+ if (node === null || typeof node !== 'object')
118
+ return out;
119
+ if (Array.isArray(node)) {
120
+ for (const item of node)
121
+ collectRefTargets(item, out);
122
+ return out;
123
+ }
124
+ const obj = node;
125
+ if (typeof obj['$ref'] === 'string') {
126
+ // A `$ref` object's siblings are ignored on resolution, so we do not recurse
127
+ // into them — mirroring resolveAt's behaviour.
128
+ const { filePart } = splitRef(obj['$ref']);
129
+ if (filePart !== '')
130
+ out.add(filePart);
131
+ return out;
132
+ }
133
+ for (const key of Object.keys(obj))
134
+ collectRefTargets(obj[key], out);
135
+ return out;
136
+ };
137
+ /**
138
+ * Walks every reachable document starting from `rootLocation`, loading each one
139
+ * so the synchronous resolve pass can look them up. This is the only async part
140
+ * of resolution: remote documents are fetched here (in dependency order) and
141
+ * cached for the session.
142
+ */
143
+ const prefetch = async (rootLocation, docCache, options, errors) => {
144
+ const seen = new Set([rootLocation]);
145
+ const queue = [rootLocation];
146
+ while (queue.length > 0) {
147
+ const location = queue.shift();
148
+ for (const filePart of collectRefTargets(docCache.get(location), new Set())) {
149
+ const target = joinLocation(location, filePart);
150
+ if (seen.has(target))
151
+ continue;
152
+ seen.add(target);
153
+ await loadDoc(target, docCache, options, errors);
154
+ queue.push(target);
155
+ }
156
+ }
157
+ };
158
+ /**
159
+ * Single-pass resolver that inlines internal and external (`$ref` to other
160
+ * file/URL) references. Every reachable document has already been loaded into
161
+ * `docCache` by `prefetch`, so this stays synchronous. Refs are resolved once
162
+ * (`refCache`); the CYCLE sentinel short-circuits re-entrant resolution.
163
+ *
164
+ * `baseLocation` is the location of the document `node` belongs to, used to
165
+ * resolve relative refs and `#/...` pointers within it.
166
+ */
167
+ const resolveAt = (node, baseLocation, docCache, refCache) => {
168
+ if (node === null || typeof node !== 'object')
169
+ return node;
170
+ if (Array.isArray(node)) {
171
+ return node.map((item) => resolveAt(item, baseLocation, docCache, refCache));
172
+ }
173
+ const obj = node;
174
+ if (typeof obj['$ref'] === 'string') {
175
+ const { filePart, pointer } = splitRef(obj['$ref']);
176
+ const targetLocation = filePart === '' ? baseLocation : joinLocation(baseLocation, filePart);
177
+ const targetRoot = docCache.get(targetLocation) ?? {};
178
+ const cacheKey = `${targetLocation}#${pointer}`;
179
+ if (refCache.has(cacheKey)) {
180
+ const cached = refCache.get(cacheKey);
181
+ return cached === CYCLE ? {} : cached;
182
+ }
183
+ refCache.set(cacheKey, CYCLE);
184
+ const target = pointer ? getByPointer(targetRoot, pointer) : targetRoot;
185
+ const resolved = resolveAt(target, targetLocation, docCache, refCache);
186
+ refCache.set(cacheKey, resolved);
187
+ return resolved;
188
+ }
189
+ const result = {};
190
+ for (const key of Object.keys(obj)) {
191
+ result[key] = resolveAt(obj[key], baseLocation, docCache, refCache);
192
+ }
193
+ return result;
194
+ };
195
+ /**
196
+ * Resolves `$ref`s in a document on disk (or at a URL), including cross-file
197
+ * and remote refs. Remote documents are fetched on the fly and cached in memory
198
+ * for the session; `options` governs whether/which remote hosts are allowed.
199
+ */
200
+ export const resolveRefsFromFile = async (filename, options = {}) => {
201
+ const rootLocation = isRemote(filename) ? filename : resolvePath(filename);
202
+ const errors = [];
203
+ const docCache = new Map();
204
+ if (!(await loadDoc(rootLocation, docCache, options, errors))) {
205
+ return { resolved: {}, errors };
206
+ }
207
+ await prefetch(rootLocation, docCache, options, errors);
208
+ const resolved = resolveAt(docCache.get(rootLocation), rootLocation, docCache, new Map());
209
+ return { resolved, errors };
210
+ };
@@ -0,0 +1,8 @@
1
+ import type { ResolveResult } from './types.js';
2
+ /**
3
+ * Resolves all internal (`#/...`) `$ref`s in an in-memory document, inlining
4
+ * each target. External and remote refs are left as-is. Cycles are broken with
5
+ * an empty object so the result is always finite.
6
+ */
7
+ export declare const resolveRefs: (data: unknown) => ResolveResult;
8
+ //# sourceMappingURL=resolve-refs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-refs.d.ts","sourceRoot":"","sources":["../src/resolve-refs.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAuC5C;;;;GAIG;AACH,eAAO,MAAM,WAAW,SAAU,OAAO,KAAG,aAG3C,CAAA"}
@@ -0,0 +1,45 @@
1
+ import { getByPointer } from './get-by-pointer.js';
2
+ // A ref currently mid-resolution is marked with this sentinel; revisiting it
3
+ // means we have looped, so we return `{}` instead of recursing forever.
4
+ const CYCLE = Symbol('cycle');
5
+ /**
6
+ * Single-pass internal-only `$ref` resolver. Each unique ref string is resolved
7
+ * exactly once (the `cache`); revisiting a ref that is still mid-resolution
8
+ * means a cycle, so we return `{}` (the CYCLE sentinel). Non-`#` refs (external
9
+ * files, HTTP) are left untouched — callers that need those should use
10
+ * `resolveRefsFromFile`.
11
+ */
12
+ const resolveInternal = (node, root, cache) => {
13
+ if (node === null || typeof node !== 'object')
14
+ return node;
15
+ if (Array.isArray(node))
16
+ return node.map((item) => resolveInternal(item, root, cache));
17
+ const obj = node;
18
+ if (typeof obj['$ref'] === 'string') {
19
+ const ref = obj['$ref'];
20
+ if (!ref.startsWith('#'))
21
+ return obj; // external ref — leave as-is
22
+ if (cache.has(ref)) {
23
+ const cached = cache.get(ref);
24
+ return cached === CYCLE ? {} : cached;
25
+ }
26
+ cache.set(ref, CYCLE);
27
+ const resolved = resolveInternal(getByPointer(root, ref.slice(1)), root, cache);
28
+ cache.set(ref, resolved);
29
+ return resolved;
30
+ }
31
+ const result = {};
32
+ for (const key of Object.keys(obj)) {
33
+ result[key] = resolveInternal(obj[key], root, cache);
34
+ }
35
+ return result;
36
+ };
37
+ /**
38
+ * Resolves all internal (`#/...`) `$ref`s in an in-memory document, inlining
39
+ * each target. External and remote refs are left as-is. Cycles are broken with
40
+ * an empty object so the result is always finite.
41
+ */
42
+ export const resolveRefs = (data) => {
43
+ const resolved = resolveInternal(data, data, new Map());
44
+ return { resolved, errors: [] };
45
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * A path into a JSON document: object keys and array indices, in order. Errors
3
+ * report the location of the offending `$ref` with one of these.
4
+ */
5
+ export type JsonPath = (string | number)[];
6
+ /** A single `$ref` resolution failure (a missing file, a bad URL, a refusal). */
7
+ export type ResolveError = {
8
+ message: string;
9
+ path: JsonPath;
10
+ };
11
+ /** The outcome of a resolve pass: the dereferenced document plus any errors. */
12
+ export type ResolveResult = {
13
+ /** The dereferenced document (all resolvable `$ref`s inlined). */
14
+ resolved: unknown;
15
+ errors: ResolveError[];
16
+ };
17
+ /** Controls how external `$ref`s to other documents are loaded. */
18
+ export type ResolveOptions = {
19
+ /**
20
+ * Whether http(s) `$ref`s may be fetched. Defaults to `true`.
21
+ */
22
+ remote?: boolean;
23
+ /**
24
+ * If non-empty, only these hosts (e.g. `api.example.com`) may be fetched for
25
+ * remote `$ref`s. An empty/undefined list allows any host (subject to
26
+ * `remote`). An explicit entry here always bypasses the private-host guard.
27
+ */
28
+ allowedHosts?: string[];
29
+ /**
30
+ * Allow remote `$ref`s to loopback, private, link-local, and other
31
+ * non-public addresses. Defaults to `false`: such hosts are refused as a
32
+ * best-effort SSRF guard (notably the `169.254.169.254` cloud-metadata
33
+ * endpoint). An explicit `allowedHosts` entry always bypasses this guard.
34
+ */
35
+ allowPrivateHosts?: boolean;
36
+ };
37
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAA;AAE1C,iFAAiF;AACjF,MAAM,MAAM,YAAY,GAAG;IACzB,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,QAAQ,CAAA;CACf,CAAA;AAED,gFAAgF;AAChF,MAAM,MAAM,aAAa,GAAG;IAC1B,kEAAkE;IAClE,QAAQ,EAAE,OAAO,CAAA;IACjB,MAAM,EAAE,YAAY,EAAE,CAAA;CACvB,CAAA;AAED,mEAAmE;AACnE,MAAM,MAAM,cAAc,GAAG;IAC3B;;OAEG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAA;IACvB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAA;CAC5B,CAAA"}
package/dist/types.js ADDED
File without changes
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@amritk/resolve-refs",
3
+ "version": "0.0.0",
4
+ "description": "Resolve and inline JSON Schema / OpenAPI $refs — internal, cross-file, and remote — with session caching and a default-deny SSRF guard.",
5
+ "module": "./dist/index.js",
6
+ "type": "module",
7
+ "license": "MIT",
8
+ "author": "amritk",
9
+ "keywords": [
10
+ "json-schema",
11
+ "openapi",
12
+ "$ref",
13
+ "ref",
14
+ "resolver",
15
+ "dereference",
16
+ "typescript",
17
+ "mjst"
18
+ ],
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/amritk/mjst.git",
22
+ "directory": "packages/resolve-refs"
23
+ },
24
+ "homepage": "https://github.com/amritk/mjst/tree/main/packages/resolve-refs#readme",
25
+ "bugs": {
26
+ "url": "https://github.com/amritk/mjst/issues"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "src"
31
+ ],
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "scripts": {
36
+ "build": "tsgo -p tsconfig.build.json && tsc-alias -p tsconfig.build.json -f",
37
+ "types:check": "tsgo -p . --noEmit",
38
+ "test": "NODE_ENV=production vitest run --root ../.. resolve-refs"
39
+ },
40
+ "exports": {
41
+ ".": {
42
+ "development": "./src/index.ts",
43
+ "default": "./dist/index.js",
44
+ "types": "./dist/index.d.ts"
45
+ }
46
+ }
47
+ }
@@ -0,0 +1,35 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { getByPointer } from './get-by-pointer'
4
+
5
+ describe('get-by-pointer', () => {
6
+ const root = {
7
+ info: { title: 'API' },
8
+ paths: [{ get: { id: 1 } }, { post: { id: 2 } }],
9
+ 'weird/key': true,
10
+ 'tilde~key': false,
11
+ }
12
+
13
+ it('returns the root for an empty or bare-slash pointer', () => {
14
+ expect(getByPointer(root, '')).toBe(root)
15
+ expect(getByPointer(root, '/')).toBe(root)
16
+ })
17
+
18
+ it('navigates object keys', () => {
19
+ expect(getByPointer(root, '/info/title')).toBe('API')
20
+ })
21
+
22
+ it('navigates array indices', () => {
23
+ expect(getByPointer(root, '/paths/1/post/id')).toBe(2)
24
+ })
25
+
26
+ it('decodes ~1 and ~0 escapes', () => {
27
+ expect(getByPointer(root, '/weird~1key')).toBe(true)
28
+ expect(getByPointer(root, '/tilde~0key')).toBe(false)
29
+ })
30
+
31
+ it('returns undefined when a segment is missing', () => {
32
+ expect(getByPointer(root, '/info/nope')).toBeUndefined()
33
+ expect(getByPointer(root, '/info/title/tooDeep')).toBeUndefined()
34
+ })
35
+ })
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Walks a JSON Pointer string (RFC 6901) to the value it points to within
3
+ * `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
4
+ * decoded (`~1` → `/`, `~0` → `~`). Returns `undefined` when any segment along
5
+ * the path is missing or traverses a non-object.
6
+ */
7
+ export const getByPointer = (root: unknown, pointer: string): unknown => {
8
+ if (pointer === '' || pointer === '/') return root
9
+
10
+ const segments = pointer
11
+ .replace(/^\//, '')
12
+ .split('/')
13
+ .map((segment) => segment.replace(/~1/g, '/').replace(/~0/g, '~'))
14
+
15
+ let current: unknown = root
16
+ for (const segment of segments) {
17
+ if (current === null || typeof current !== 'object') return undefined
18
+ const key = Array.isArray(current) ? Number(segment) : segment
19
+ current = (current as Record<string, unknown>)[key]
20
+ }
21
+ return current
22
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export { getByPointer } from './get-by-pointer'
2
+ export { isPrivateHost } from './is-private-host'
3
+ export { resolveRefs } from './resolve-refs'
4
+ export { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file'
5
+ export type { JsonPath, ResolveError, ResolveOptions, ResolveResult } from './types'
@@ -0,0 +1,36 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { isPrivateHost } from './is-private-host'
4
+
5
+ describe('is-private-host', () => {
6
+ it('treats localhost and its subdomains as private', () => {
7
+ expect(isPrivateHost('localhost')).toBe(true)
8
+ expect(isPrivateHost('api.localhost')).toBe(true)
9
+ })
10
+
11
+ it('flags loopback and RFC 1918 / CGNAT IPv4 ranges', () => {
12
+ expect(isPrivateHost('127.0.0.1')).toBe(true)
13
+ expect(isPrivateHost('10.1.2.3')).toBe(true)
14
+ expect(isPrivateHost('172.16.0.1')).toBe(true)
15
+ expect(isPrivateHost('172.31.255.255')).toBe(true)
16
+ expect(isPrivateHost('192.168.0.1')).toBe(true)
17
+ expect(isPrivateHost('100.64.0.1')).toBe(true)
18
+ })
19
+
20
+ it('flags the cloud-metadata link-local endpoint', () => {
21
+ expect(isPrivateHost('169.254.169.254')).toBe(true)
22
+ })
23
+
24
+ it('flags private IPv6 (loopback, link-local, unique-local)', () => {
25
+ expect(isPrivateHost('::1')).toBe(true)
26
+ expect(isPrivateHost('[::1]')).toBe(true)
27
+ expect(isPrivateHost('fe80::1')).toBe(true)
28
+ expect(isPrivateHost('fd00::1')).toBe(true)
29
+ })
30
+
31
+ it('allows public hosts', () => {
32
+ expect(isPrivateHost('example.com')).toBe(false)
33
+ expect(isPrivateHost('8.8.8.8')).toBe(false)
34
+ expect(isPrivateHost('172.32.0.1')).toBe(false)
35
+ })
36
+ })
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Best-effort check for a hostname that resolves to a non-public address —
3
+ * loopback, private (RFC 1918 / ULA), link-local (incl. the `169.254.169.254`
4
+ * cloud-metadata endpoint), or otherwise host-local. This is a syntactic guard
5
+ * on the URL only; it does not perform DNS, so a public name that resolves to a
6
+ * private IP is not caught here. It exists to stop the obvious SSRF footguns
7
+ * when resolving remote `$ref`s.
8
+ */
9
+ export const isPrivateHost = (hostname: string): boolean => {
10
+ const host = hostname.replace(/^\[|\]$/g, '').toLowerCase()
11
+ if (host === 'localhost' || host.endsWith('.localhost')) return true
12
+
13
+ // IPv4 (incl. IPv4-mapped IPv6 like ::ffff:127.0.0.1)
14
+ const v4 = host.match(/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
15
+ if (v4) {
16
+ const a = Number(v4[1])
17
+ const b = Number(v4[2])
18
+ if (a === 10 || a === 127 || a === 0) return true
19
+ if (a === 169 && b === 254) return true // link-local + metadata
20
+ if (a === 172 && b >= 16 && b <= 31) return true
21
+ if (a === 192 && b === 168) return true
22
+ if (a === 100 && b >= 64 && b <= 127) return true // CGNAT
23
+ return false
24
+ }
25
+
26
+ // IPv6
27
+ if (host.includes(':')) {
28
+ if (host === '::1' || host === '::') return true
29
+ if (host.startsWith('fe80:') || host.startsWith('fe80::')) return true // link-local
30
+ if (host.startsWith('fc') || host.startsWith('fd')) return true // unique-local
31
+ return false
32
+ }
33
+ return false
34
+ }
@@ -0,0 +1,109 @@
1
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5
+
6
+ import { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file'
7
+
8
+ describe('resolve-refs-from-file', () => {
9
+ let dir: string
10
+
11
+ beforeEach(() => {
12
+ dir = mkdtempSync(join(tmpdir(), 'resolve-refs-'))
13
+ clearRemoteCache()
14
+ })
15
+
16
+ afterEach(() => {
17
+ rmSync(dir, { recursive: true, force: true })
18
+ vi.restoreAllMocks()
19
+ })
20
+
21
+ it('inlines a cross-file $ref between local documents', async () => {
22
+ writeFileSync(
23
+ join(dir, 'pet.json'),
24
+ JSON.stringify({ Pet: { type: 'object', properties: { name: { type: 'string' } } } }),
25
+ )
26
+ writeFileSync(
27
+ join(dir, 'api.json'),
28
+ JSON.stringify({ components: { schemas: { Pet: { $ref: './pet.json#/Pet' } } } }),
29
+ )
30
+
31
+ const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'))
32
+
33
+ expect(errors).toEqual([])
34
+ expect(resolved).toMatchObject({
35
+ components: { schemas: { Pet: { type: 'object', properties: { name: { type: 'string' } } } } },
36
+ })
37
+ })
38
+
39
+ it('inlines an internal $ref within a single document', async () => {
40
+ writeFileSync(join(dir, 'root.json'), JSON.stringify({ a: { $ref: '#/b' }, b: { value: 1 } }))
41
+
42
+ const { resolved } = await resolveRefsFromFile(join(dir, 'root.json'))
43
+
44
+ expect(resolved).toMatchObject({ a: { value: 1 }, b: { value: 1 } })
45
+ })
46
+
47
+ it('records an error and degrades to {} when a referenced file is missing', async () => {
48
+ writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: './missing.json#/Nope' } }))
49
+
50
+ const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'))
51
+
52
+ // The missing document degrades to {}, so the pointer into it misses and the
53
+ // ref resolves to undefined — the important part is that we recorded the
54
+ // failure instead of throwing.
55
+ expect((resolved as { x: unknown }).x).toBeUndefined()
56
+ expect(errors.length).toBeGreaterThan(0)
57
+ })
58
+
59
+ it('refuses a remote $ref to a private host by default (SSRF guard)', async () => {
60
+ const fetchSpy = vi.spyOn(globalThis, 'fetch')
61
+ writeFileSync(
62
+ join(dir, 'api.json'),
63
+ JSON.stringify({ x: { $ref: 'http://169.254.169.254/latest/meta-data#/foo' } }),
64
+ )
65
+
66
+ const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'))
67
+
68
+ // The refused document degrades to {}, so the pointer into it misses.
69
+ expect((resolved as { x: unknown }).x).toBeUndefined()
70
+ expect(errors[0]?.message).toMatch(/Refusing to resolve remote \$ref/)
71
+ // The guard is syntactic — we never even attempt the request.
72
+ expect(fetchSpy).not.toHaveBeenCalled()
73
+ })
74
+
75
+ it('refuses any remote $ref when remote resolution is disabled', async () => {
76
+ const fetchSpy = vi.spyOn(globalThis, 'fetch')
77
+ writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: 'https://example.com/s.json#/Foo' } }))
78
+
79
+ const { errors } = await resolveRefsFromFile(join(dir, 'api.json'), { remote: false })
80
+
81
+ expect(errors[0]?.message).toMatch(/remote \$ref resolution is disabled/)
82
+ expect(fetchSpy).not.toHaveBeenCalled()
83
+ })
84
+
85
+ it('fetches an allow-listed remote $ref and caches it for the session', async () => {
86
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
87
+ new Response(JSON.stringify({ Foo: { type: 'string' } }), {
88
+ status: 200,
89
+ headers: { 'content-type': 'application/json' },
90
+ }),
91
+ )
92
+ writeFileSync(
93
+ join(dir, 'api.json'),
94
+ JSON.stringify({
95
+ a: { $ref: 'https://api.example.com/s.json#/Foo' },
96
+ b: { $ref: 'https://api.example.com/s.json#/Foo' },
97
+ }),
98
+ )
99
+
100
+ const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'), {
101
+ allowedHosts: ['api.example.com'],
102
+ })
103
+
104
+ expect(errors).toEqual([])
105
+ expect(resolved).toMatchObject({ a: { type: 'string' }, b: { type: 'string' } })
106
+ // Both refs hit the same document, which is fetched and cached exactly once.
107
+ expect(fetchSpy).toHaveBeenCalledTimes(1)
108
+ })
109
+ })
@@ -0,0 +1,235 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { dirname, resolve as resolvePath } from 'node:path'
3
+
4
+ import { getByPointer } from './get-by-pointer'
5
+ import { isPrivateHost } from './is-private-host'
6
+ import type { ResolveError, ResolveOptions, ResolveResult } from './types'
7
+
8
+ // A ref currently mid-resolution is marked with this sentinel; revisiting it
9
+ // means a cycle, so we return `{}` instead of recursing forever.
10
+ const CYCLE = Symbol('cycle')
11
+ type CacheValue = unknown | typeof CYCLE
12
+
13
+ // --- Document location helpers ---------------------------------------------
14
+ //
15
+ // A "location" is the absolute identity of a document: either an absolute file
16
+ // path or an absolute http(s) URL. Refs are resolved relative to the location
17
+ // of the document they appear in, so a relative ref inside a remote document
18
+ // resolves to another remote URL, and one inside a local file to another path.
19
+
20
+ const isRemote = (location: string): boolean => /^https?:\/\//i.test(location)
21
+
22
+ /** Resolves the location of `ref` (its file/URL part) relative to `base`. */
23
+ const joinLocation = (base: string, ref: string): string => {
24
+ if (isRemote(ref)) return ref
25
+ if (isRemote(base)) return new URL(ref, base).href
26
+ return resolvePath(dirname(base), ref)
27
+ }
28
+
29
+ /** Splits a `$ref` into its document part and JSON-pointer part. */
30
+ const splitRef = (ref: string): { filePart: string; pointer: string } => {
31
+ const hashIdx = ref.indexOf('#')
32
+ return {
33
+ filePart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
34
+ pointer: hashIdx === -1 ? '' : ref.slice(hashIdx + 1),
35
+ }
36
+ }
37
+
38
+ // mjst deals only in JSON Schema documents, so every document — local or
39
+ // remote — is parsed as JSON. (The Loupe linter's sibling resolver additionally
40
+ // accepts YAML; this one stays JSON-only to keep the package dependency-free.)
41
+ const parseContent = (content: string): unknown => JSON.parse(content) as unknown
42
+
43
+ // --- Remote document cache -------------------------------------------------
44
+ //
45
+ // Fetched remote documents are cached in memory for the lifetime of the
46
+ // process ("the session"). Local files are intentionally NOT cached across
47
+ // resolve passes — they can change on disk during a long-lived session (e.g.
48
+ // an editor/LSP), so each pass re-reads them. Remote documents are assumed
49
+ // stable for the session; call `clearRemoteCache()` to drop them.
50
+
51
+ const remoteCache = new Map<string, unknown>()
52
+
53
+ /** Drops every cached remote document. Mainly useful for tests/long sessions. */
54
+ export const clearRemoteCache = (): void => {
55
+ remoteCache.clear()
56
+ }
57
+
58
+ /** Returns why a remote location may not be fetched, or `null` if it is allowed. */
59
+ const denialReason = (location: string, options: ResolveOptions): string | null => {
60
+ if (options.remote === false) return 'remote $ref resolution is disabled'
61
+
62
+ let url: URL
63
+ try {
64
+ url = new URL(location)
65
+ } catch {
66
+ return 'the URL is invalid'
67
+ }
68
+
69
+ const allow = options.allowedHosts
70
+ // An explicit allow-list entry is an intentional opt-in and bypasses the
71
+ // private-host guard; otherwise refuse non-public targets by default.
72
+ if (allow && allow.length > 0) {
73
+ return allow.includes(url.host) ? null : 'host is not in the allow-list'
74
+ }
75
+ if (!options.allowPrivateHosts && isPrivateHost(url.hostname)) {
76
+ return 'host resolves to a private or loopback address (set allowPrivateHosts to permit)'
77
+ }
78
+ return null
79
+ }
80
+
81
+ /**
82
+ * Loads a document into `docCache`, fetching/reading it if needed. Remote
83
+ * documents are additionally cached for the session in `remoteCache`. On
84
+ * failure an error is recorded and the location is cached as `{}` so that
85
+ * pointer lookups degrade gracefully instead of throwing. Returns whether the
86
+ * document loaded successfully.
87
+ */
88
+ const loadDoc = async (
89
+ location: string,
90
+ docCache: Map<string, unknown>,
91
+ options: ResolveOptions,
92
+ errors: ResolveError[],
93
+ ): Promise<boolean> => {
94
+ if (docCache.has(location)) return true
95
+
96
+ if (isRemote(location)) {
97
+ if (remoteCache.has(location)) {
98
+ docCache.set(location, remoteCache.get(location))
99
+ return true
100
+ }
101
+ const reason = denialReason(location, options)
102
+ if (reason !== null) {
103
+ errors.push({ message: `Refusing to resolve remote $ref (${reason}): ${location}`, path: [] })
104
+ docCache.set(location, {})
105
+ return false
106
+ }
107
+ try {
108
+ const response = await fetch(location)
109
+ if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`)
110
+ const doc = parseContent(await response.text())
111
+ remoteCache.set(location, doc)
112
+ docCache.set(location, doc)
113
+ return true
114
+ } catch (err) {
115
+ errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: [] })
116
+ docCache.set(location, {})
117
+ return false
118
+ }
119
+ }
120
+
121
+ try {
122
+ docCache.set(location, parseContent(readFileSync(location, 'utf8')))
123
+ return true
124
+ } catch (err) {
125
+ errors.push({ message: String(err), path: [] })
126
+ docCache.set(location, {})
127
+ return false
128
+ }
129
+ }
130
+
131
+ /** Collects the distinct document parts of every `$ref` directly under `node`. */
132
+ const collectRefTargets = (node: unknown, out: Set<string>): Set<string> => {
133
+ if (node === null || typeof node !== 'object') return out
134
+ if (Array.isArray(node)) {
135
+ for (const item of node) collectRefTargets(item, out)
136
+ return out
137
+ }
138
+ const obj = node as Record<string, unknown>
139
+ if (typeof obj['$ref'] === 'string') {
140
+ // A `$ref` object's siblings are ignored on resolution, so we do not recurse
141
+ // into them — mirroring resolveAt's behaviour.
142
+ const { filePart } = splitRef(obj['$ref'])
143
+ if (filePart !== '') out.add(filePart)
144
+ return out
145
+ }
146
+ for (const key of Object.keys(obj)) collectRefTargets(obj[key], out)
147
+ return out
148
+ }
149
+
150
+ /**
151
+ * Walks every reachable document starting from `rootLocation`, loading each one
152
+ * so the synchronous resolve pass can look them up. This is the only async part
153
+ * of resolution: remote documents are fetched here (in dependency order) and
154
+ * cached for the session.
155
+ */
156
+ const prefetch = async (
157
+ rootLocation: string,
158
+ docCache: Map<string, unknown>,
159
+ options: ResolveOptions,
160
+ errors: ResolveError[],
161
+ ): Promise<void> => {
162
+ const seen = new Set<string>([rootLocation])
163
+ const queue: string[] = [rootLocation]
164
+ while (queue.length > 0) {
165
+ const location = queue.shift() as string
166
+ for (const filePart of collectRefTargets(docCache.get(location), new Set())) {
167
+ const target = joinLocation(location, filePart)
168
+ if (seen.has(target)) continue
169
+ seen.add(target)
170
+ await loadDoc(target, docCache, options, errors)
171
+ queue.push(target)
172
+ }
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Single-pass resolver that inlines internal and external (`$ref` to other
178
+ * file/URL) references. Every reachable document has already been loaded into
179
+ * `docCache` by `prefetch`, so this stays synchronous. Refs are resolved once
180
+ * (`refCache`); the CYCLE sentinel short-circuits re-entrant resolution.
181
+ *
182
+ * `baseLocation` is the location of the document `node` belongs to, used to
183
+ * resolve relative refs and `#/...` pointers within it.
184
+ */
185
+ const resolveAt = (
186
+ node: unknown,
187
+ baseLocation: string,
188
+ docCache: Map<string, unknown>,
189
+ refCache: Map<string, CacheValue>,
190
+ ): unknown => {
191
+ if (node === null || typeof node !== 'object') return node
192
+ if (Array.isArray(node)) {
193
+ return node.map((item) => resolveAt(item, baseLocation, docCache, refCache))
194
+ }
195
+ const obj = node as Record<string, unknown>
196
+ if (typeof obj['$ref'] === 'string') {
197
+ const { filePart, pointer } = splitRef(obj['$ref'])
198
+ const targetLocation = filePart === '' ? baseLocation : joinLocation(baseLocation, filePart)
199
+ const targetRoot = docCache.get(targetLocation) ?? {}
200
+
201
+ const cacheKey = `${targetLocation}#${pointer}`
202
+ if (refCache.has(cacheKey)) {
203
+ const cached = refCache.get(cacheKey)
204
+ return cached === CYCLE ? {} : cached
205
+ }
206
+ refCache.set(cacheKey, CYCLE)
207
+ const target = pointer ? getByPointer(targetRoot, pointer) : targetRoot
208
+ const resolved = resolveAt(target, targetLocation, docCache, refCache)
209
+ refCache.set(cacheKey, resolved)
210
+ return resolved
211
+ }
212
+ const result: Record<string, unknown> = {}
213
+ for (const key of Object.keys(obj)) {
214
+ result[key] = resolveAt(obj[key], baseLocation, docCache, refCache)
215
+ }
216
+ return result
217
+ }
218
+
219
+ /**
220
+ * Resolves `$ref`s in a document on disk (or at a URL), including cross-file
221
+ * and remote refs. Remote documents are fetched on the fly and cached in memory
222
+ * for the session; `options` governs whether/which remote hosts are allowed.
223
+ */
224
+ export const resolveRefsFromFile = async (filename: string, options: ResolveOptions = {}): Promise<ResolveResult> => {
225
+ const rootLocation = isRemote(filename) ? filename : resolvePath(filename)
226
+ const errors: ResolveError[] = []
227
+ const docCache = new Map<string, unknown>()
228
+
229
+ if (!(await loadDoc(rootLocation, docCache, options, errors))) {
230
+ return { resolved: {}, errors }
231
+ }
232
+ await prefetch(rootLocation, docCache, options, errors)
233
+ const resolved = resolveAt(docCache.get(rootLocation), rootLocation, docCache, new Map())
234
+ return { resolved, errors }
235
+ }
@@ -0,0 +1,33 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { resolveRefs } from './resolve-refs'
4
+
5
+ describe('resolve-refs', () => {
6
+ it('inlines an internal $ref', () => {
7
+ const { resolved, errors } = resolveRefs({
8
+ type: 'object',
9
+ properties: { contact: { $ref: '#/$defs/contact' } },
10
+ $defs: { contact: { type: 'string' } },
11
+ })
12
+
13
+ expect(errors).toEqual([])
14
+ expect(resolved).toMatchObject({ properties: { contact: { type: 'string' } } })
15
+ })
16
+
17
+ it('breaks a self-referential cycle with an empty object', () => {
18
+ const { resolved } = resolveRefs({
19
+ $defs: { node: { type: 'object', properties: { next: { $ref: '#/$defs/node' } } } },
20
+ properties: { head: { $ref: '#/$defs/node' } },
21
+ })
22
+
23
+ const head = (resolved as { properties: { head: { properties: { next: unknown } } } }).properties.head
24
+ // The first level resolves; the recursive self-reference terminates at `{}`.
25
+ expect(head.properties.next).toEqual({})
26
+ })
27
+
28
+ it('leaves external (non-#) refs untouched', () => {
29
+ const { resolved } = resolveRefs({ properties: { pet: { $ref: 'pet.json#/Pet' } } })
30
+
31
+ expect(resolved).toEqual({ properties: { pet: { $ref: 'pet.json#/Pet' } } })
32
+ })
33
+ })
@@ -0,0 +1,49 @@
1
+ import { getByPointer } from './get-by-pointer'
2
+ import type { ResolveResult } from './types'
3
+
4
+ // A ref currently mid-resolution is marked with this sentinel; revisiting it
5
+ // means we have looped, so we return `{}` instead of recursing forever.
6
+ const CYCLE = Symbol('cycle')
7
+ type CacheValue = unknown | typeof CYCLE
8
+
9
+ /**
10
+ * Single-pass internal-only `$ref` resolver. Each unique ref string is resolved
11
+ * exactly once (the `cache`); revisiting a ref that is still mid-resolution
12
+ * means a cycle, so we return `{}` (the CYCLE sentinel). Non-`#` refs (external
13
+ * files, HTTP) are left untouched — callers that need those should use
14
+ * `resolveRefsFromFile`.
15
+ */
16
+ const resolveInternal = (node: unknown, root: unknown, cache: Map<string, CacheValue>): unknown => {
17
+ if (node === null || typeof node !== 'object') return node
18
+ if (Array.isArray(node)) return node.map((item) => resolveInternal(item, root, cache))
19
+
20
+ const obj = node as Record<string, unknown>
21
+ if (typeof obj['$ref'] === 'string') {
22
+ const ref = obj['$ref']
23
+ if (!ref.startsWith('#')) return obj // external ref — leave as-is
24
+ if (cache.has(ref)) {
25
+ const cached = cache.get(ref)
26
+ return cached === CYCLE ? {} : cached
27
+ }
28
+ cache.set(ref, CYCLE)
29
+ const resolved = resolveInternal(getByPointer(root, ref.slice(1)), root, cache)
30
+ cache.set(ref, resolved)
31
+ return resolved
32
+ }
33
+
34
+ const result: Record<string, unknown> = {}
35
+ for (const key of Object.keys(obj)) {
36
+ result[key] = resolveInternal(obj[key], root, cache)
37
+ }
38
+ return result
39
+ }
40
+
41
+ /**
42
+ * Resolves all internal (`#/...`) `$ref`s in an in-memory document, inlining
43
+ * each target. External and remote refs are left as-is. Cycles are broken with
44
+ * an empty object so the result is always finite.
45
+ */
46
+ export const resolveRefs = (data: unknown): ResolveResult => {
47
+ const resolved = resolveInternal(data, data, new Map())
48
+ return { resolved, errors: [] }
49
+ }
package/src/types.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * A path into a JSON document: object keys and array indices, in order. Errors
3
+ * report the location of the offending `$ref` with one of these.
4
+ */
5
+ export type JsonPath = (string | number)[]
6
+
7
+ /** A single `$ref` resolution failure (a missing file, a bad URL, a refusal). */
8
+ export type ResolveError = {
9
+ message: string
10
+ path: JsonPath
11
+ }
12
+
13
+ /** The outcome of a resolve pass: the dereferenced document plus any errors. */
14
+ export type ResolveResult = {
15
+ /** The dereferenced document (all resolvable `$ref`s inlined). */
16
+ resolved: unknown
17
+ errors: ResolveError[]
18
+ }
19
+
20
+ /** Controls how external `$ref`s to other documents are loaded. */
21
+ export type ResolveOptions = {
22
+ /**
23
+ * Whether http(s) `$ref`s may be fetched. Defaults to `true`.
24
+ */
25
+ remote?: boolean
26
+ /**
27
+ * If non-empty, only these hosts (e.g. `api.example.com`) may be fetched for
28
+ * remote `$ref`s. An empty/undefined list allows any host (subject to
29
+ * `remote`). An explicit entry here always bypasses the private-host guard.
30
+ */
31
+ allowedHosts?: string[]
32
+ /**
33
+ * Allow remote `$ref`s to loopback, private, link-local, and other
34
+ * non-public addresses. Defaults to `false`: such hosts are refused as a
35
+ * best-effort SSRF guard (notably the `169.254.169.254` cloud-metadata
36
+ * endpoint). An explicit `allowedHosts` entry always bypasses this guard.
37
+ */
38
+ allowPrivateHosts?: boolean
39
+ }