@amritk/resolve-refs 0.6.0 → 0.7.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,4 +1,4 @@
1
- const VALUE_KEYWORDS = /* @__PURE__ */ new Set(["enum", "const", "default", "examples"]);
1
+ const VALUE_KEYWORDS = /* @__PURE__ */ new Set(["enum", "const", "default", "examples", "example"]);
2
2
  const SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([
3
3
  "properties",
4
4
  "patternProperties",
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
- import { dirname, resolve as resolvePath } from "node:path";
3
+ import { dirname, relative as relativePath, resolve as resolvePath, sep } from "node:path";
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";
@@ -307,6 +307,13 @@ const detach = (node) => {
307
307
  }
308
308
  continue;
309
309
  }
310
+ const prototype = Object.getPrototypeOf(src);
311
+ if (prototype !== Object.prototype && prototype !== null) {
312
+ const kept = src instanceof Date ? new Date(src.getTime()) : src;
313
+ seen.set(src, kept);
314
+ set(kept);
315
+ continue;
316
+ }
310
317
  const copy = {};
311
318
  seen.set(src, copy);
312
319
  set(copy);
@@ -321,6 +328,62 @@ const detach = (node) => {
321
328
  }
322
329
  return out.value;
323
330
  };
331
+ const rebaseKeptRef = (value, from, root) => {
332
+ if (from === root)
333
+ return value;
334
+ const { filePart, fragment } = splitRef(value);
335
+ if (filePart === "")
336
+ return `${renderLocation(from, root)}${value}`;
337
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]+:/.test(filePart))
338
+ return value;
339
+ const target = joinLocation(from, filePart);
340
+ const suffix = value.includes("#") ? `#${fragment}` : "";
341
+ return `${renderLocation(target, root)}${suffix}`;
342
+ };
343
+ const renderLocation = (target, root) => {
344
+ if (isRemote(target) || isRemote(root))
345
+ return target;
346
+ const relative = relativePath(dirname(root), target).split(sep).join("/");
347
+ return relative.startsWith(".") ? relative : `./${relative}`;
348
+ };
349
+ const rebaseKeptRefs = (node, from, root, role) => {
350
+ if (from === root || node === null || typeof node !== "object")
351
+ return node;
352
+ const seen = /* @__PURE__ */ new Set();
353
+ const stack = [{ value: node, role }];
354
+ while (stack.length > 0) {
355
+ const current = stack.pop();
356
+ if (current === void 0)
357
+ break;
358
+ const { value: current_, role: currentRole } = current;
359
+ if (current_ === null || typeof current_ !== "object")
360
+ continue;
361
+ if (currentRole === "value")
362
+ continue;
363
+ if (seen.has(current_))
364
+ continue;
365
+ seen.add(current_);
366
+ if (Array.isArray(current_)) {
367
+ for (let index = 0; index < current_.length; index++) {
368
+ stack.push({ value: current_[index], role: childRole(currentRole, index) });
369
+ }
370
+ continue;
371
+ }
372
+ const prototype = Object.getPrototypeOf(current_);
373
+ if (prototype !== Object.prototype && prototype !== null)
374
+ continue;
375
+ const obj = current_;
376
+ const isSchema = currentRole !== "schemaMap";
377
+ for (const [key, value] of Object.entries(obj)) {
378
+ if (isSchema && key === "$ref" && typeof value === "string") {
379
+ assignKey(obj, key, rebaseKeptRef(value, from, root));
380
+ } else {
381
+ stack.push({ value, role: childRole(currentRole, key) });
382
+ }
383
+ }
384
+ }
385
+ return node;
386
+ };
324
387
  const pathToRef = (path) => path.length === 0 ? "#" : `#/${path.map((segment) => escapeSegment(String(segment))).join("/")}`;
325
388
  const hoistName = (targetLocation, fragment, taken) => {
326
389
  const fragmentTail = fragment.split("/").filter(Boolean).pop();
@@ -457,6 +520,15 @@ const resolveRefsFromFile = async (filename, options = {}) => {
457
520
  const rootDoc = docCache.get(rootLocation);
458
521
  const rootDefs = rootDoc !== null && typeof rootDoc === "object" && !Array.isArray(rootDoc) ? rootDoc["$defs"] : void 0;
459
522
  const hoistTaken = new Set(rootDefs !== null && typeof rootDefs === "object" && !Array.isArray(rootDefs) ? Object.keys(rootDefs) : []);
523
+ const hoistRefSites = /* @__PURE__ */ new Map();
524
+ const keepScopedReference = (obj, keyword, baseLocation, nodeBase, depth, role) => {
525
+ const kept = {};
526
+ for (const key of Object.keys(obj)) {
527
+ const value = obj[key];
528
+ assignKey(kept, key, key !== keyword ? resolveAt(value, baseLocation, nodeBase, depth + 1, childRole(role, key)) : keyword === "$ref" && typeof value === "string" ? rebaseKeptRef(value, baseLocation, rootLocation) : value);
529
+ }
530
+ return kept;
531
+ };
460
532
  const resolveAt = (node, baseLocation, base, depth, role) => {
461
533
  if (node === null || typeof node !== "object")
462
534
  return node;
@@ -464,7 +536,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
464
536
  return detach(node);
465
537
  if (depth > maxDepth) {
466
538
  reportDepthLimit();
467
- return detach(node);
539
+ return rebaseKeptRefs(detach(node), baseLocation, rootLocation, role);
468
540
  }
469
541
  if (Array.isArray(node)) {
470
542
  const items = node.map((item, index) => resolveAt(item, baseLocation, base, depth + 1, childRole(role, index)));
@@ -480,10 +552,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
480
552
  if (reference) {
481
553
  const { keyword, value } = reference;
482
554
  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
- }
555
+ const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
487
556
  sensitive.add(kept);
488
557
  return kept;
489
558
  }
@@ -511,6 +580,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
511
580
  const cached = refCache.get(cacheKey);
512
581
  if (cached === CYCLE) {
513
582
  let keptRef;
583
+ let hoisted = false;
514
584
  if (scoped !== void 0 && baseLocation === rootLocation) {
515
585
  keptRef = pathToRef(scoped.pointer);
516
586
  } else if (scoped === void 0 && targetLocation === rootLocation) {
@@ -521,6 +591,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
521
591
  name = hoistName(targetLocation, fragment, hoistTaken);
522
592
  hoists.set(cacheKey, name);
523
593
  }
594
+ hoisted = true;
524
595
  keptRef = `#/$defs/${name}`;
525
596
  }
526
597
  const kept = {};
@@ -530,6 +601,8 @@ const resolveRefsFromFile = async (filename, options = {}) => {
530
601
  assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
531
602
  }
532
603
  assignKey(kept, "$ref", keptRef);
604
+ if (hoisted)
605
+ hoistRefSites.set(kept, cacheKey);
533
606
  return kept;
534
607
  }
535
608
  const keepUnresolved = () => {
@@ -539,7 +612,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
539
612
  continue;
540
613
  assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
541
614
  }
542
- assignKey(kept, keyword, value);
615
+ assignKey(kept, keyword, keyword === "$ref" ? rebaseKeptRef(value, baseLocation, rootLocation) : value);
543
616
  return kept;
544
617
  };
545
618
  if (cached === MISSING)
@@ -571,8 +644,9 @@ const resolveRefsFromFile = async (filename, options = {}) => {
571
644
  }
572
645
  }
573
646
  }
574
- if (found === void 0 && !unloadable.has(targetLocation)) {
575
- if (docCache.has(targetLocation)) {
647
+ const targetLoaded = docCache.has(targetLocation) && !unloadable.has(targetLocation);
648
+ if (found === void 0 || !targetLoaded) {
649
+ if (targetLoaded) {
576
650
  errors.push({
577
651
  message: `Cannot resolve ${keyword} "${value}"`,
578
652
  path: fragment === "" || fragment.startsWith("/") ? pointerToPath(fragment) : []
@@ -589,10 +663,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
589
663
  }
590
664
  }
591
665
  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
- }
666
+ const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
596
667
  sensitive.add(kept);
597
668
  return kept;
598
669
  }
@@ -616,6 +687,9 @@ const resolveRefsFromFile = async (filename, options = {}) => {
616
687
  }
617
688
  for (const key of Object.keys(siblings))
618
689
  assignKey(overridden, key, siblings[key]);
690
+ const hoistOf = hoistRefSites.get(resolved2);
691
+ if (hoistOf !== void 0)
692
+ hoistRefSites.set(overridden, hoistOf);
619
693
  if (origins && !origins.has(overridden))
620
694
  origins.set(overridden, { location: targetLocation, pointer });
621
695
  if (inlineIsSensitive)
@@ -649,10 +723,24 @@ const resolveRefsFromFile = async (filename, options = {}) => {
649
723
  if (resolved !== null && typeof resolved === "object" && !Array.isArray(resolved)) {
650
724
  const container = resolved;
651
725
  const defs = container["$defs"] !== null && typeof container["$defs"] === "object" && !Array.isArray(container["$defs"]) ? container["$defs"] : {};
726
+ const taken = new Set(Object.keys(defs));
727
+ const finalNames = /* @__PURE__ */ new Map();
652
728
  for (const [cacheKey, name] of hoists) {
729
+ let unique = name;
730
+ for (let n = 2; taken.has(unique); n++)
731
+ unique = `${name}-${n}`;
732
+ taken.add(unique);
733
+ finalNames.set(cacheKey, unique);
734
+ }
735
+ for (const [node, cacheKey] of hoistRefSites) {
736
+ const name = finalNames.get(cacheKey);
737
+ if (name !== void 0)
738
+ assignKey(node, "$ref", `#/$defs/${name}`);
739
+ }
740
+ for (const [cacheKey] of hoists) {
653
741
  const cached = refCache.get(cacheKey);
654
742
  const attachable = cached !== void 0 && cached !== CYCLE && cached !== MISSING;
655
- assignKey(defs, name, attachable ? cached.value ?? {} : {});
743
+ assignKey(defs, finalNames.get(cacheKey), attachable ? cached.value ?? {} : {});
656
744
  }
657
745
  assignKey(container, "$defs", defs);
658
746
  } else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/resolve-refs",
3
- "version": "0.6.0",
3
+ "version": "0.7.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",
@@ -52,6 +52,6 @@
52
52
  }
53
53
  },
54
54
  "devDependencies": {
55
- "@amritk/runtime-validators": "^0.10.1"
55
+ "@amritk/runtime-validators": "^0.11.0"
56
56
  }
57
57
  }