@amritk/resolve-refs 0.4.5 → 0.6.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.
@@ -1,10 +1,19 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { readFileSync } from "node:fs";
2
3
  import { dirname, resolve as resolvePath } from "node:path";
4
+ import { assertPublicHost } from "./assert-public-host.js";
5
+ import { childRole } from "./child-role.js";
6
+ import { bindsAtEvaluationTime, declaresAmbiguousAnchor, inliningKeepsScope, isScopeSensitive } from "./dynamic-scope.js";
7
+ import { pointerToPath } from "./get-by-pointer.js";
8
+ import { isContainedPath } from "./is-contained-path.js";
3
9
  import { isPrivateHost } from "./is-private-host.js";
10
+ import { DEFAULT_MAX_DEPTH, depthLimitError } from "./max-depth.js";
4
11
  import { readReference, resolveFragment } from "./reference.js";
5
12
  import { baseOfNode, buildResourceRegistry, resolveRefInScope, SYNTHETIC_BASE } from "./resource-registry.js";
13
+ import { roleAtPath } from "./role-at-path.js";
6
14
  import { assignKey } from "./safe-assign.js";
7
15
  const CYCLE = /* @__PURE__ */ Symbol("cycle");
16
+ const MISSING = /* @__PURE__ */ Symbol("missing");
8
17
  const ANNOTATION_ONLY_SIBLINGS = /* @__PURE__ */ new Set(["summary", "description"]);
9
18
  const isRemote = (location) => /^https?:\/\//i.test(location);
10
19
  const joinLocation = (base, ref) => {
@@ -21,10 +30,43 @@ const splitRef = (ref) => {
21
30
  fragment: hashIdx === -1 ? "" : ref.slice(hashIdx + 1)
22
31
  };
23
32
  };
33
+ const REMOTE_CACHE_TTL_MS = 10 * 6e4;
34
+ const REMOTE_CACHE_MAX_ENTRIES = 256;
24
35
  const remoteCache = /* @__PURE__ */ new Map();
25
36
  const inFlight = /* @__PURE__ */ new Map();
26
- const clearRemoteCache = () => {
27
- remoteCache.clear();
37
+ const SCOPE_SEPARATOR = "\0";
38
+ const clearRemoteCache = (location) => {
39
+ if (location === void 0) {
40
+ remoteCache.clear();
41
+ return;
42
+ }
43
+ const suffix = `${SCOPE_SEPARATOR}${location}`;
44
+ for (const key of remoteCache.keys()) {
45
+ if (key.endsWith(suffix))
46
+ remoteCache.delete(key);
47
+ }
48
+ };
49
+ const readRemoteCache = (key) => {
50
+ const entry = remoteCache.get(key);
51
+ if (entry === void 0)
52
+ return void 0;
53
+ if (Date.now() >= entry.expiresAt) {
54
+ remoteCache.delete(key);
55
+ return void 0;
56
+ }
57
+ remoteCache.delete(key);
58
+ remoteCache.set(key, entry);
59
+ return entry;
60
+ };
61
+ const writeRemoteCache = (key, value) => {
62
+ remoteCache.delete(key);
63
+ remoteCache.set(key, { value, expiresAt: Date.now() + REMOTE_CACHE_TTL_MS });
64
+ while (remoteCache.size > REMOTE_CACHE_MAX_ENTRIES) {
65
+ const oldest = remoteCache.keys().next();
66
+ if (oldest.done)
67
+ break;
68
+ remoteCache.delete(oldest.value);
69
+ }
28
70
  };
29
71
  const MAX_REDIRECTS = 5;
30
72
  const FETCH_TIMEOUT_MS = 3e4;
@@ -53,7 +95,41 @@ const headersFor = (url, options) => {
53
95
  return void 0;
54
96
  return typeof options.headers === "function" ? options.headers(url) : options.headers;
55
97
  };
56
- const fetchRemote = async (location, options) => {
98
+ const callableIds = /* @__PURE__ */ new WeakMap();
99
+ let nextCallableId = 0;
100
+ const callableId = (fn) => {
101
+ if (typeof fn !== "function")
102
+ return "default";
103
+ let id = callableIds.get(fn);
104
+ if (id === void 0) {
105
+ id = `fn${++nextCallableId}`;
106
+ callableIds.set(fn, id);
107
+ }
108
+ return id;
109
+ };
110
+ const headersFingerprint = (headers) => {
111
+ if (headers === void 0)
112
+ return "none";
113
+ const entries = Object.entries(headers).map(([name, value]) => `${name.toLowerCase()}:${value}`).sort();
114
+ if (entries.length === 0)
115
+ return "none";
116
+ return createHash("sha256").update(entries.join("\n")).digest("hex").slice(0, 32);
117
+ };
118
+ const fetchScope = (location, options) => [
119
+ headersFingerprint(headersFor(location, options)),
120
+ callableId(options.fetch),
121
+ callableId(options.parse),
122
+ String(options.timeoutMs ?? FETCH_TIMEOUT_MS),
123
+ String(options.maxRedirects ?? MAX_REDIRECTS),
124
+ String(options.maxBytes ?? MAX_REMOTE_BYTES),
125
+ options.verifyDns === false ? "nodns" : "dns",
126
+ options.allowPrivateHosts === true ? "private" : "public",
127
+ // Sorted so two callers spelling the same allowlist in a different order
128
+ // still share a document.
129
+ [...options.allowedHosts ?? []].sort().join(",")
130
+ ].join("|");
131
+ const cacheKeyFor = (location, options) => `${fetchScope(location, options)}${SCOPE_SEPARATOR}${location}`;
132
+ const fetchRemote = async (location, options, deadline) => {
57
133
  const maxRedirects = options.maxRedirects ?? MAX_REDIRECTS;
58
134
  const timeoutMs = options.timeoutMs ?? FETCH_TIMEOUT_MS;
59
135
  const maxBytes = options.maxBytes ?? MAX_REMOTE_BYTES;
@@ -64,11 +140,15 @@ const fetchRemote = async (location, options) => {
64
140
  const reason = denialReason(current, options);
65
141
  if (reason !== null)
66
142
  throw new Error(`refusing to follow redirect (${reason}): ${current}`);
143
+ if (needsDnsVerification(options))
144
+ await assertPublicHost(new URL(current).hostname);
67
145
  const headers = new URL(current).origin === origin ? headersFor(location, options) : void 0;
68
146
  const response = await doFetch(current, {
69
147
  redirect: "manual",
70
- // Cap the wait for a response so a stalling host can't hang resolution forever.
71
- signal: AbortSignal.timeout(timeoutMs),
148
+ // Cap the wait for a response so a stalling host can't hang resolution
149
+ // forever — and never past the whole resolve's deadline, so a chain of
150
+ // slow hops cannot outlive the caller's total budget.
151
+ signal: AbortSignal.timeout(Math.max(0, Math.min(timeoutMs, deadline - Date.now()))),
72
152
  ...headers !== void 0 ? { headers } : {}
73
153
  });
74
154
  if (response.status >= 300 && response.status < 400) {
@@ -85,6 +165,15 @@ const fetchRemote = async (location, options) => {
85
165
  }
86
166
  throw new Error(`too many redirects (>${maxRedirects}): ${location}`);
87
167
  };
168
+ const isAllowedHost = (url, allow) => {
169
+ const hostname = url.hostname.toLowerCase();
170
+ const port = url.port === "" ? url.protocol === "https:" ? "443" : "80" : url.port;
171
+ const withPort = `${hostname}:${port}`;
172
+ return allow.some((entry) => {
173
+ const candidate = entry.trim().toLowerCase();
174
+ return candidate === hostname || candidate === withPort;
175
+ });
176
+ };
88
177
  const denialReason = (location, options) => {
89
178
  if (options.remote === false)
90
179
  return "remote $ref resolution is disabled";
@@ -99,14 +188,23 @@ const denialReason = (location, options) => {
99
188
  }
100
189
  const allow = options.allowedHosts;
101
190
  if (allow && allow.length > 0) {
102
- return allow.includes(url.host) ? null : "host is not in the allow-list";
191
+ return isAllowedHost(url, allow) ? null : "host is not in the allow-list";
103
192
  }
104
193
  if (!options.allowPrivateHosts && isPrivateHost(url.hostname)) {
105
194
  return "host resolves to a private or loopback address (set allowPrivateHosts to permit)";
106
195
  }
107
196
  return null;
108
197
  };
109
- const loadDoc = async (location, docCache, options, errors) => {
198
+ const needsDnsVerification = (options) => {
199
+ if (options.verifyDns === false)
200
+ return false;
201
+ if (options.allowPrivateHosts)
202
+ return false;
203
+ if (options.allowedHosts && options.allowedHosts.length > 0)
204
+ return false;
205
+ return true;
206
+ };
207
+ const loadDoc = async (location, docCache, options, errors, deadline) => {
110
208
  if (docCache.has(location))
111
209
  return true;
112
210
  if (isRemote(location)) {
@@ -117,13 +215,17 @@ const loadDoc = async (location, docCache, options, errors) => {
117
215
  return false;
118
216
  }
119
217
  const useSessionCache = options.cache !== false;
120
- if (useSessionCache && remoteCache.has(location)) {
121
- docCache.set(location, remoteCache.get(location));
122
- return true;
218
+ const key = cacheKeyFor(location, options);
219
+ if (useSessionCache) {
220
+ const entry = readRemoteCache(key);
221
+ if (entry !== void 0) {
222
+ docCache.set(location, entry.value);
223
+ return true;
224
+ }
123
225
  }
124
226
  if (!useSessionCache) {
125
227
  try {
126
- const doc = await fetchRemote(location, options);
228
+ const doc = await fetchRemote(location, options, deadline);
127
229
  docCache.set(location, doc);
128
230
  return true;
129
231
  } catch (err) {
@@ -132,15 +234,15 @@ const loadDoc = async (location, docCache, options, errors) => {
132
234
  return false;
133
235
  }
134
236
  }
135
- let pending = inFlight.get(location);
237
+ let pending = inFlight.get(key);
136
238
  const owner = pending === void 0;
137
239
  if (pending === void 0) {
138
- pending = fetchRemote(location, options);
139
- inFlight.set(location, pending);
240
+ pending = fetchRemote(location, options, deadline);
241
+ inFlight.set(key, pending);
140
242
  }
141
243
  try {
142
244
  const doc = await pending;
143
- remoteCache.set(location, doc);
245
+ writeRemoteCache(key, doc);
144
246
  docCache.set(location, doc);
145
247
  return true;
146
248
  } catch (err) {
@@ -149,7 +251,7 @@ const loadDoc = async (location, docCache, options, errors) => {
149
251
  return false;
150
252
  } finally {
151
253
  if (owner)
152
- inFlight.delete(location);
254
+ inFlight.delete(key);
153
255
  }
154
256
  }
155
257
  try {
@@ -162,7 +264,63 @@ const loadDoc = async (location, docCache, options, errors) => {
162
264
  return false;
163
265
  }
164
266
  };
165
- const escapeSegment = (segment) => segment.replace(/~/g, "~0").replace(/\//g, "~1");
267
+ const escapeSegment = (segment) => segment.replace(/~/g, "~0").replace(/\//g, "~1").replace(/%/g, "%25");
268
+ const detach = (node) => {
269
+ if (node === null || typeof node !== "object")
270
+ return node;
271
+ const seen = /* @__PURE__ */ new Map();
272
+ const out = { value: void 0 };
273
+ const stack = [
274
+ {
275
+ src: node,
276
+ set: (value) => {
277
+ out.value = value;
278
+ }
279
+ }
280
+ ];
281
+ while (stack.length > 0) {
282
+ const frame = stack.pop();
283
+ if (frame === void 0)
284
+ break;
285
+ const { src, set } = frame;
286
+ if (src === null || typeof src !== "object") {
287
+ set(src);
288
+ continue;
289
+ }
290
+ const already = seen.get(src);
291
+ if (already !== void 0) {
292
+ set(already);
293
+ continue;
294
+ }
295
+ if (Array.isArray(src)) {
296
+ const copy2 = new Array(src.length);
297
+ seen.set(src, copy2);
298
+ set(copy2);
299
+ for (let index = src.length - 1; index >= 0; index--) {
300
+ const at = index;
301
+ stack.push({
302
+ src: src[at],
303
+ set: (value) => {
304
+ copy2[at] = value;
305
+ }
306
+ });
307
+ }
308
+ continue;
309
+ }
310
+ const copy = {};
311
+ seen.set(src, copy);
312
+ set(copy);
313
+ const keys = Object.keys(src);
314
+ for (let index = keys.length - 1; index >= 0; index--) {
315
+ const key = keys[index];
316
+ stack.push({
317
+ src: src[key],
318
+ set: (value) => assignKey(copy, key, value)
319
+ });
320
+ }
321
+ }
322
+ return out.value;
323
+ };
166
324
  const pathToRef = (path) => path.length === 0 ? "#" : `#/${path.map((segment) => escapeSegment(String(segment))).join("/")}`;
167
325
  const hoistName = (targetLocation, fragment, taken) => {
168
326
  const fragmentTail = fragment.split("/").filter(Boolean).pop();
@@ -175,34 +333,64 @@ const hoistName = (targetLocation, fragment, taken) => {
175
333
  taken.add(name);
176
334
  return name;
177
335
  };
336
+ const MAX_DOCUMENTS = 500;
337
+ const TOTAL_TIMEOUT_MS = 6e4;
178
338
  const resolveRefsFromFile = async (filename, options = {}) => {
179
339
  const rootLocation = isRemote(filename) ? filename : resolvePath(filename);
180
340
  const errors = [];
181
341
  const docCache = /* @__PURE__ */ new Map();
182
- if (!await loadDoc(rootLocation, docCache, options, errors)) {
342
+ const unloadable = /* @__PURE__ */ new Set();
343
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
344
+ const maxDocuments = options.maxDocuments ?? MAX_DOCUMENTS;
345
+ const deadline = Date.now() + (options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS);
346
+ const localRoots = (options.allowedRoots ?? (isRemote(rootLocation) ? [] : [dirname(rootLocation)])).map((root) => resolvePath(root));
347
+ const localDenialReason = (location) => {
348
+ if (options.localRefs === false)
349
+ return "local $ref resolution is disabled";
350
+ if (localRoots.length === 0) {
351
+ return "no local directory is allowed for this document (set allowedRoots to permit one)";
352
+ }
353
+ if (localRoots.some((root) => isContainedPath(root, location)))
354
+ return null;
355
+ return `it resolves outside the allowed roots [${localRoots.join(", ")}] (set allowedRoots to permit it)`;
356
+ };
357
+ if (!await loadDoc(rootLocation, docCache, options, errors, deadline)) {
183
358
  return { resolved: {}, errors };
184
359
  }
185
360
  const registries = /* @__PURE__ */ new Map();
186
361
  const registryFor = (location) => {
187
362
  let registry = registries.get(location);
188
363
  if (registry === void 0) {
189
- registry = buildResourceRegistry(docCache.get(location), isRemote(location) ? location : SYNTHETIC_BASE);
364
+ registry = buildResourceRegistry(docCache.get(location), isRemote(location) ? location : SYNTHETIC_BASE, maxDepth);
190
365
  registries.set(location, registry);
191
366
  }
192
367
  return registry;
193
368
  };
194
- const collectRefTargets = (node, location, base, out) => {
195
- if (node === null || typeof node !== "object")
369
+ let depthLimitReported = false;
370
+ const reportDepthLimit = () => {
371
+ if (depthLimitReported)
372
+ return;
373
+ depthLimitReported = true;
374
+ errors.push(depthLimitError(maxDepth));
375
+ };
376
+ const collectRefTargets = (node, location, base, out, depth, role) => {
377
+ if (node === null || typeof node !== "object" || role === "value")
196
378
  return;
379
+ if (depth > maxDepth) {
380
+ reportDepthLimit();
381
+ return;
382
+ }
197
383
  if (Array.isArray(node)) {
198
- for (const item of node)
199
- collectRefTargets(item, location, base, out);
384
+ node.forEach((item, index) => {
385
+ collectRefTargets(item, location, base, out, depth + 1, childRole(role, index));
386
+ });
200
387
  return;
201
388
  }
202
389
  const obj = node;
203
390
  const registry = registryFor(location);
204
- const nodeBase = typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
205
- const reference = readReference(obj);
391
+ const isSchema = role !== "schemaMap";
392
+ const nodeBase = isSchema && typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
393
+ const reference = isSchema ? readReference(obj) : void 0;
206
394
  if (reference && reference.keyword !== "$recursiveRef") {
207
395
  const scoped = resolveRefInScope(registry, reference.keyword, reference.value, nodeBase);
208
396
  if (scoped === "external") {
@@ -214,22 +402,48 @@ const resolveRefsFromFile = async (filename, options = {}) => {
214
402
  for (const key of Object.keys(obj)) {
215
403
  if (reference && key === reference.keyword)
216
404
  continue;
217
- collectRefTargets(obj[key], location, nodeBase, out);
405
+ collectRefTargets(obj[key], location, nodeBase, out, depth + 1, childRole(role, key));
218
406
  }
219
407
  };
220
408
  const prefetch = async () => {
221
409
  const seen = /* @__PURE__ */ new Set([rootLocation]);
222
410
  const queue = [rootLocation];
411
+ let loaded = 1;
223
412
  while (queue.length > 0) {
224
413
  const location = queue.shift();
225
414
  const out = /* @__PURE__ */ new Set();
226
- collectRefTargets(docCache.get(location), location, registryFor(location).rootBase, out);
415
+ collectRefTargets(docCache.get(location), location, registryFor(location).rootBase, out, 0, "schema");
227
416
  for (const filePart of out) {
228
417
  const target = joinLocation(location, filePart);
229
418
  if (seen.has(target))
230
419
  continue;
231
420
  seen.add(target);
232
- await loadDoc(target, docCache, options, errors);
421
+ if (loaded >= maxDocuments) {
422
+ errors.push({
423
+ message: `Refusing to load more than ${maxDocuments} documents; the rest of the $ref graph was left unresolved (raise maxDocuments to allow more)`,
424
+ path: []
425
+ });
426
+ return;
427
+ }
428
+ if (Date.now() >= deadline) {
429
+ errors.push({
430
+ message: `Resolve deadline of ${options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS}ms elapsed; the rest of the $ref graph was left unresolved (raise totalTimeoutMs to allow more)`,
431
+ path: []
432
+ });
433
+ return;
434
+ }
435
+ if (!isRemote(target)) {
436
+ const reason = localDenialReason(target);
437
+ if (reason !== null) {
438
+ errors.push({ message: `Refusing to read local $ref (${reason}): ${target}`, path: [] });
439
+ docCache.set(target, {});
440
+ unloadable.add(target);
441
+ continue;
442
+ }
443
+ }
444
+ loaded++;
445
+ if (!await loadDoc(target, docCache, options, errors, deadline))
446
+ unloadable.add(target);
233
447
  queue.push(target);
234
448
  }
235
449
  }
@@ -237,20 +451,42 @@ const resolveRefsFromFile = async (filename, options = {}) => {
237
451
  await prefetch();
238
452
  const origins = options.trackOrigins ? /* @__PURE__ */ new Map() : void 0;
239
453
  const refCache = /* @__PURE__ */ new Map();
454
+ const sensitive = /* @__PURE__ */ new WeakSet();
455
+ const ambiguousDynamicAnchors = docCache.size === 1 ? registryFor(rootLocation).ambiguousDynamicAnchors : /* @__PURE__ */ new Set();
240
456
  const hoists = /* @__PURE__ */ new Map();
241
- const hoistTaken = /* @__PURE__ */ new Set();
242
- const resolveAt = (node, baseLocation, base) => {
457
+ const rootDoc = docCache.get(rootLocation);
458
+ const rootDefs = rootDoc !== null && typeof rootDoc === "object" && !Array.isArray(rootDoc) ? rootDoc["$defs"] : void 0;
459
+ const hoistTaken = new Set(rootDefs !== null && typeof rootDefs === "object" && !Array.isArray(rootDefs) ? Object.keys(rootDefs) : []);
460
+ const resolveAt = (node, baseLocation, base, depth, role) => {
243
461
  if (node === null || typeof node !== "object")
244
462
  return node;
463
+ if (role === "value")
464
+ return detach(node);
465
+ if (depth > maxDepth) {
466
+ reportDepthLimit();
467
+ return detach(node);
468
+ }
245
469
  if (Array.isArray(node)) {
246
- return node.map((item) => resolveAt(item, baseLocation, base));
470
+ const items = node.map((item, index) => resolveAt(item, baseLocation, base, depth + 1, childRole(role, index)));
471
+ if (items.some((item) => isScopeSensitive(sensitive, item)))
472
+ sensitive.add(items);
473
+ return items;
247
474
  }
248
475
  const obj = node;
249
476
  const registry = registryFor(baseLocation);
250
- const nodeBase = typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
251
- const reference = readReference(obj);
477
+ const isSchema = role !== "schemaMap";
478
+ const nodeBase = isSchema && typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
479
+ const reference = isSchema ? readReference(obj) : void 0;
252
480
  if (reference) {
253
481
  const { keyword, value } = reference;
482
+ if (bindsAtEvaluationTime(keyword, value, ambiguousDynamicAnchors)) {
483
+ const kept = {};
484
+ for (const key of Object.keys(obj)) {
485
+ assignKey(kept, key, key === keyword ? obj[key] : resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
486
+ }
487
+ sensitive.add(kept);
488
+ return kept;
489
+ }
254
490
  let scoped;
255
491
  let targetLocation = baseLocation;
256
492
  let fragment = "";
@@ -271,6 +507,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
271
507
  const cacheKey = scoped !== void 0 ? `${keyword} ${baseLocation} ${nodeBase} ${value}` : `${keyword} ${targetLocation}#${fragment}`;
272
508
  let resolved2;
273
509
  let pointer;
510
+ let targetBase = nodeBase;
274
511
  const cached = refCache.get(cacheKey);
275
512
  if (cached === CYCLE) {
276
513
  let keptRef;
@@ -290,18 +527,30 @@ const resolveRefsFromFile = async (filename, options = {}) => {
290
527
  for (const key of Object.keys(obj)) {
291
528
  if (key === keyword)
292
529
  continue;
293
- assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase));
530
+ assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
294
531
  }
295
532
  assignKey(kept, "$ref", keptRef);
296
533
  return kept;
297
534
  }
535
+ const keepUnresolved = () => {
536
+ const kept = {};
537
+ for (const key of Object.keys(obj)) {
538
+ if (key === keyword)
539
+ continue;
540
+ assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
541
+ }
542
+ assignKey(kept, keyword, value);
543
+ return kept;
544
+ };
545
+ if (cached === MISSING)
546
+ return keepUnresolved();
298
547
  if (cached !== void 0) {
299
548
  resolved2 = cached.value;
300
549
  pointer = cached.pointer;
550
+ targetBase = cached.base;
301
551
  } else {
302
552
  refCache.set(cacheKey, CYCLE);
303
553
  let found;
304
- let targetBase;
305
554
  if (scoped !== void 0) {
306
555
  found = scoped;
307
556
  targetBase = scoped.base;
@@ -322,19 +571,43 @@ const resolveRefsFromFile = async (filename, options = {}) => {
322
571
  }
323
572
  }
324
573
  }
574
+ if (found === void 0 && !unloadable.has(targetLocation)) {
575
+ if (docCache.has(targetLocation)) {
576
+ errors.push({
577
+ message: `Cannot resolve ${keyword} "${value}"`,
578
+ path: fragment === "" || fragment.startsWith("/") ? pointerToPath(fragment) : []
579
+ });
580
+ }
581
+ refCache.set(cacheKey, MISSING);
582
+ return keepUnresolved();
583
+ }
325
584
  pointer = found?.pointer ?? [];
326
- resolved2 = resolveAt(found?.value, targetLocation, targetBase);
327
- refCache.set(cacheKey, { value: resolved2, pointer });
585
+ resolved2 = resolveAt(found?.value, targetLocation, targetBase, depth + 1, roleAtPath(pointer));
586
+ refCache.set(cacheKey, { value: resolved2, pointer, base: targetBase });
328
587
  if (origins && resolved2 !== null && typeof resolved2 === "object" && !origins.has(resolved2)) {
329
588
  origins.set(resolved2, { location: targetLocation, pointer });
330
589
  }
331
590
  }
591
+ if (isScopeSensitive(sensitive, resolved2) && !inliningKeepsScope(resolved2, nodeBase, targetBase)) {
592
+ const kept = {};
593
+ for (const key of Object.keys(obj)) {
594
+ assignKey(kept, key, key === keyword ? obj[key] : resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
595
+ }
596
+ sensitive.add(kept);
597
+ return kept;
598
+ }
332
599
  const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
333
600
  if (siblingKeys.length === 0)
334
601
  return resolved2;
335
602
  const siblings = {};
336
- for (const key of siblingKeys)
337
- assignKey(siblings, key, resolveAt(obj[key], baseLocation, nodeBase));
603
+ let siblingIsSensitive = false;
604
+ for (const key of siblingKeys) {
605
+ const child = resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key));
606
+ assignKey(siblings, key, child);
607
+ if (isScopeSensitive(sensitive, child))
608
+ siblingIsSensitive = true;
609
+ }
610
+ const inlineIsSensitive = siblingIsSensitive || isScopeSensitive(sensitive, resolved2) || declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors);
338
611
  if (siblingKeys.every((key) => ANNOTATION_ONLY_SIBLINGS.has(key))) {
339
612
  if (resolved2 !== null && typeof resolved2 === "object" && !Array.isArray(resolved2)) {
340
613
  const overridden = {};
@@ -345,6 +618,8 @@ const resolveRefsFromFile = async (filename, options = {}) => {
345
618
  assignKey(overridden, key, siblings[key]);
346
619
  if (origins && !origins.has(overridden))
347
620
  origins.set(overridden, { location: targetLocation, pointer });
621
+ if (inlineIsSensitive)
622
+ sensitive.add(overridden);
348
623
  return overridden;
349
624
  }
350
625
  return resolved2;
@@ -353,23 +628,31 @@ const resolveRefsFromFile = async (filename, options = {}) => {
353
628
  const merged = { ...siblings, allOf: [...existingAllOf, resolved2] };
354
629
  if (origins && !origins.has(merged))
355
630
  origins.set(merged, { location: targetLocation, pointer });
631
+ if (inlineIsSensitive)
632
+ sensitive.add(merged);
356
633
  return merged;
357
634
  }
358
635
  const result = {};
359
636
  for (const key of Object.keys(obj)) {
360
- assignKey(result, key, resolveAt(obj[key], baseLocation, nodeBase));
637
+ const child = resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key));
638
+ assignKey(result, key, child);
639
+ if (isScopeSensitive(sensitive, child))
640
+ sensitive.add(result);
361
641
  }
642
+ if (isSchema && declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors))
643
+ sensitive.add(result);
362
644
  return result;
363
645
  };
364
646
  const rootRegistry = registryFor(rootLocation);
365
- const resolved = resolveAt(docCache.get(rootLocation), rootLocation, rootRegistry.rootBase);
647
+ const resolved = resolveAt(docCache.get(rootLocation), rootLocation, rootRegistry.rootBase, 0, "schema");
366
648
  if (hoists.size > 0) {
367
649
  if (resolved !== null && typeof resolved === "object" && !Array.isArray(resolved)) {
368
650
  const container = resolved;
369
651
  const defs = container["$defs"] !== null && typeof container["$defs"] === "object" && !Array.isArray(container["$defs"]) ? container["$defs"] : {};
370
652
  for (const [cacheKey, name] of hoists) {
371
653
  const cached = refCache.get(cacheKey);
372
- assignKey(defs, name, cached !== void 0 && cached !== CYCLE ? cached.value ?? {} : {});
654
+ const attachable = cached !== void 0 && cached !== CYCLE && cached !== MISSING;
655
+ assignKey(defs, name, attachable ? cached.value ?? {} : {});
373
656
  }
374
657
  assignKey(container, "$defs", defs);
375
658
  } else {
@@ -8,15 +8,43 @@ export type ResolveRefsOptions = {
8
8
  * Defaults to `false`.
9
9
  */
10
10
  trackOrigins?: boolean;
11
+ /**
12
+ * How deep the resolver walks before leaving a subtree unresolved and
13
+ * recording an error. Defaults to `512`. The walk is recursive, so a
14
+ * pathologically nested document would otherwise unwind the stack with a
15
+ * `RangeError` — a thrown error this package promises never to throw.
16
+ */
17
+ maxDepth?: number;
11
18
  };
12
19
  /**
13
20
  * Resolves all internal `$ref`s in an in-memory document — plain `#/...`
14
21
  * pointers, `$anchor`/`$dynamicAnchor` names (scoped by `$id`), and refs whose
15
22
  * URI matches an embedded resource's `$id` — inlining each target. Refs to
16
23
  * other files/URLs are left in place and reported on `errors` (this resolver
17
- * can't load other documents — use `resolveRefsFromFile` for those). Cycles are
18
- * broken by keeping the original reference node, so recursive schemas keep
19
- * their recursive branch.
24
+ * can't load other documents — use `resolveRefsFromFile` for those).
25
+ *
26
+ * Only references in *schema* positions are inlined: a `$ref`-shaped object
27
+ * inside `enum`, `const`, `default` or `examples` is instance data and is kept
28
+ * verbatim (see `child-role.ts`).
29
+ *
30
+ * **Not every reference can be inlined, and the ones that cannot are kept.** The
31
+ * output is a dereferenced document with two documented exceptions, both of
32
+ * which resolve *within* the output:
33
+ *
34
+ * - a **cycle** keeps its reference node, so a recursive schema keeps its
35
+ * recursive branch instead of collapsing to `{}`;
36
+ * - a **`$dynamicRef` that binds at evaluation time** keeps its keyword, along
37
+ * with the `$dynamicAnchor`s it may bind to and the `$id`s scoping them.
38
+ * Inlining one target would be a guess, and a wrong guess changes what the
39
+ * document accepts; a reference kept in place does not (see
40
+ * `dynamic-scope.ts`). A `$ref` whose target carries that scaffolding is kept
41
+ * for the same reason when inlining it would move the scaffolding out of the
42
+ * resource that scopes it.
43
+ *
44
+ * Neither is an error — nothing failed — so neither appears on `errors`, and
45
+ * neither is inlined, so neither is stamped in `origins`. A consumer walking the
46
+ * output should treat a leftover `$ref`/`$dynamicRef` the way it treats one in
47
+ * the input.
20
48
  *
21
49
  * @example
22
50
  * ```ts