@amritk/resolve-refs 0.3.0 → 0.4.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,53 +1,116 @@
1
1
  import { pointerToPath } from './get-by-pointer.js';
2
2
  import { readReference, resolveFragment } from './reference.js';
3
+ import { baseOfNode, buildResourceRegistry, resolveRefInScope } from './resource-registry.js';
3
4
  import { assignKey } from './safe-assign.js';
4
5
  // 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
+ // means we have looped, so we keep the original reference instead of recursing
7
+ // forever (see the CYCLE branch below).
6
8
  const CYCLE = Symbol('cycle');
7
9
  // A ref that resolved to nothing; cached so a repeated bad ref reports once.
8
10
  const MISSING = Symbol('missing');
9
11
  /**
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`.
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.
15
17
  */
16
- const resolveInternal = (node, root, cache, origins, errors) => {
18
+ const ANNOTATION_ONLY_SIBLINGS = new Set(['summary', 'description']);
19
+ /**
20
+ * Single-pass internal `$ref` resolver. Each unique ref string is resolved
21
+ * exactly once per scope (the `cache`); revisiting a ref that is still
22
+ * mid-resolution means a cycle, so the original reference node is kept — its
23
+ * target still exists in the resolved document, preserving the recursive
24
+ * branch instead of collapsing it to `{}`. Refs that resolve to nothing in
25
+ * this document (external files, HTTP) are left in place but recorded as an
26
+ * error — callers that need those should use `resolveRefsFromFile`.
27
+ *
28
+ * `base` is the current `$id` base URI, used to scope anchor lookups and to
29
+ * match refs against embedded resources (see `resource-registry.ts`).
30
+ */
31
+ const resolveInternal = (node, root, registry, base, cache, origins, errors) => {
17
32
  if (node === null || typeof node !== 'object')
18
33
  return node;
19
- if (Array.isArray(node))
20
- return node.map((item) => resolveInternal(item, root, cache, origins, errors));
34
+ if (Array.isArray(node)) {
35
+ return node.map((item) => resolveInternal(item, root, registry, base, cache, origins, errors));
36
+ }
21
37
  const obj = node;
38
+ // A subschema's `$id` re-bases everything inside it, its own `$ref` included.
39
+ const nodeBase = typeof obj['$id'] === 'string' ? baseOfNode(registry, obj, base) : base;
22
40
  const reference = readReference(obj);
23
41
  if (reference) {
24
42
  const { keyword, value: ref } = reference;
25
- if (!ref.startsWith('#'))
26
- return obj; // external ref — leave as-is
27
- // Cache/cycle key includes the keyword: `$ref #x` and `$dynamicRef #x` can
28
- // bind to different targets, so they must not share a cache slot.
29
- const cacheKey = `${keyword} ${ref}`;
43
+ // An external ref (another file or an http(s) URL) can't be dereferenced by
44
+ // the in-memory resolver — it has no access to other documents. Record a
45
+ // diagnostic and keep the original node, so callers see a half-resolved
46
+ // document flagged rather than a silently-unresolved ref. Note this is
47
+ // decided *after* `$id`-scope matching below: a non-`#` ref whose URI
48
+ // matches an embedded resource's `$id` is internal, not external.
49
+ const externalRef = () => {
50
+ errors.push({
51
+ message: `Cannot resolve external ${keyword} "${ref}": external ref requires resolveRefsFromFile`,
52
+ path: [],
53
+ });
54
+ return obj;
55
+ };
56
+ // Resolve within the document's `$id` scope. `$recursiveRef` ignores its
57
+ // fragment and binds document-globally, so it skips the scoped path.
58
+ let found;
59
+ let targetBase = nodeBase;
60
+ if (keyword === '$recursiveRef') {
61
+ found = resolveFragment(root, keyword, ref.startsWith('#') ? ref.slice(1) : ref);
62
+ targetBase = registry.rootBase;
63
+ }
64
+ else {
65
+ const scoped = resolveRefInScope(registry, keyword, ref, nodeBase);
66
+ if (scoped === 'external')
67
+ return externalRef();
68
+ if (scoped !== undefined) {
69
+ found = scoped;
70
+ targetBase = scoped.base;
71
+ }
72
+ else if (ref.startsWith('#')) {
73
+ // Scope-aware lookup found nothing; fall back to the document-global
74
+ // search for compatibility with documents that reference an anchor
75
+ // declared in a sibling resource.
76
+ found = resolveFragment(root, keyword, ref.slice(1));
77
+ targetBase = registry.rootBase;
78
+ }
79
+ else {
80
+ return externalRef();
81
+ }
82
+ }
83
+ // Cache/cycle key includes the keyword (`$ref #x` and `$dynamicRef #x` can
84
+ // bind differently) and the base URI (the same anchor name can bind
85
+ // differently inside different embedded resources).
86
+ const cacheKey = `${keyword} ${nodeBase} ${ref}`;
30
87
  let target;
31
88
  let pointer;
32
89
  const cached = cache.get(cacheKey);
33
90
  if (cached === MISSING)
34
91
  return obj;
35
92
  if (cached === CYCLE) {
36
- target = {};
37
- pointer = [];
93
+ // Mid-resolution revisit — a reference cycle. Keep the reference node
94
+ // (siblings resolved, the ref itself verbatim): its target still exists
95
+ // in the resolved document, so consumers resolve the recursion locally
96
+ // rather than finding an empty `{}` where the recursive branch was.
97
+ const kept = {};
98
+ for (const key of Object.keys(obj)) {
99
+ assignKey(kept, key, key === keyword ? obj[key] : resolveInternal(obj[key], root, registry, nodeBase, cache, origins, errors));
100
+ }
101
+ return kept;
38
102
  }
39
- else if (cached !== undefined) {
103
+ if (cached !== undefined) {
40
104
  target = cached.target;
41
105
  pointer = cached.pointer;
42
106
  }
43
107
  else {
44
108
  cache.set(cacheKey, CYCLE);
45
- const found = resolveFragment(root, keyword, ref.slice(1));
46
109
  if (found === undefined) {
47
110
  // A reference that resolves to nothing (a typo'd pointer or a missing
48
111
  // anchor) was previously inlined as literal `undefined` with no trace.
49
112
  // Record it and keep the original node so the failure is visible.
50
- const fragment = ref.slice(1);
113
+ const fragment = ref.startsWith('#') ? ref.slice(1) : ref;
51
114
  errors.push({
52
115
  message: `Cannot resolve internal ${keyword} "${ref}"`,
53
116
  path: fragment === '' || fragment.startsWith('/') ? pointerToPath(fragment) : [],
@@ -56,7 +119,7 @@ const resolveInternal = (node, root, cache, origins, errors) => {
56
119
  return obj;
57
120
  }
58
121
  pointer = found.pointer;
59
- target = resolveInternal(found.value, root, cache, origins, errors);
122
+ target = resolveInternal(found.value, root, registry, targetBase, cache, origins, errors);
60
123
  cache.set(cacheKey, { target, pointer });
61
124
  // Stamp the inlined node with the path it was defined at (see resolveAt).
62
125
  // First-write-wins so the deepest definition stamps before any outer ref that
@@ -65,17 +128,36 @@ const resolveInternal = (node, root, cache, origins, errors) => {
65
128
  origins.set(target, { location: '', pointer });
66
129
  }
67
130
  }
131
+ const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
132
+ if (siblingKeys.length === 0)
133
+ return target;
134
+ const siblings = {};
135
+ for (const key of siblingKeys) {
136
+ assignKey(siblings, key, resolveInternal(obj[key], root, registry, nodeBase, cache, origins, errors));
137
+ }
138
+ // Annotation-only siblings (OpenAPI Reference Objects): inline the target
139
+ // with the annotations overriding — never wrap in `allOf`, which is invalid
140
+ // where those references appear (see ANNOTATION_ONLY_SIBLINGS).
141
+ if (siblingKeys.every((key) => ANNOTATION_ONLY_SIBLINGS.has(key))) {
142
+ if (target !== null && typeof target === 'object' && !Array.isArray(target)) {
143
+ const overridden = {};
144
+ for (const key of Object.keys(target))
145
+ assignKey(overridden, key, target[key]);
146
+ for (const key of Object.keys(siblings))
147
+ assignKey(overridden, key, siblings[key]);
148
+ if (origins && !origins.has(overridden))
149
+ origins.set(overridden, { location: '', pointer });
150
+ return overridden;
151
+ }
152
+ // A non-object target (boolean schema, primitive) has no members to
153
+ // override; the annotations have nowhere to live, so return the target.
154
+ return target;
155
+ }
68
156
  // Per JSON Schema 2020-12, keywords sibling to `$ref` are *not* ignored: they
69
157
  // apply alongside the referenced schema. Preserve them by combining both in an
70
158
  // `allOf` (so a constraint present on both sides is never silently dropped)
71
159
  // rather than returning the bare target. The cache always stores the
72
160
  // sibling-free target so each occurrence applies its own siblings.
73
- const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
74
- if (siblingKeys.length === 0)
75
- return target;
76
- const siblings = {};
77
- for (const key of siblingKeys)
78
- assignKey(siblings, key, resolveInternal(obj[key], root, cache, origins, errors));
79
161
  const existingAllOf = Array.isArray(siblings['allOf']) ? siblings['allOf'] : [];
80
162
  const merged = { ...siblings, allOf: [...existingAllOf, target] };
81
163
  // Stamp the wrapper too, so a consumer mapping the resolved node back to its
@@ -86,18 +168,23 @@ const resolveInternal = (node, root, cache, origins, errors) => {
86
168
  }
87
169
  const result = {};
88
170
  for (const key of Object.keys(obj)) {
89
- assignKey(result, key, resolveInternal(obj[key], root, cache, origins, errors));
171
+ assignKey(result, key, resolveInternal(obj[key], root, registry, nodeBase, cache, origins, errors));
90
172
  }
91
173
  return result;
92
174
  };
93
175
  /**
94
- * Resolves all internal (`#/...`) `$ref`s in an in-memory document, inlining
95
- * each target. External and remote refs are left as-is. Cycles are broken with
96
- * an empty object so the result is always finite.
176
+ * Resolves all internal `$ref`s in an in-memory document — plain `#/...`
177
+ * pointers, `$anchor`/`$dynamicAnchor` names (scoped by `$id`), and refs whose
178
+ * URI matches an embedded resource's `$id` — inlining each target. Refs to
179
+ * other files/URLs are left in place and reported on `errors` (this resolver
180
+ * can't load other documents — use `resolveRefsFromFile` for those). Cycles are
181
+ * broken by keeping the original reference node, so recursive schemas keep
182
+ * their recursive branch.
97
183
  */
98
184
  export const resolveRefs = (data, options = {}) => {
99
185
  const origins = options.trackOrigins ? new Map() : undefined;
100
186
  const errors = [];
101
- const resolved = resolveInternal(data, data, new Map(), origins, errors);
187
+ const registry = buildResourceRegistry(data);
188
+ const resolved = resolveInternal(data, data, registry, registry.rootBase, new Map(), origins, errors);
102
189
  return origins ? { resolved, errors, origins } : { resolved, errors };
103
190
  };
@@ -0,0 +1,100 @@
1
+ import type { RefKeyword } from './reference.js';
2
+ import type { JsonPath } from './types.js';
3
+ /**
4
+ * JSON Schema 2020-12 `$id` base-URI scoping, modelled as a pre-computed
5
+ * registry of the document's embedded resources and anchors.
6
+ *
7
+ * A subschema carrying `$id` is an *embedded resource*: it establishes a new
8
+ * base URI (its `$id` resolved against the enclosing base), refs inside it
9
+ * resolve against that base, and its anchors are scoped to it. Bundled schemas
10
+ * lean on this — each `$defs` entry declares an absolute `$id` and the rest of
11
+ * the document references it by URI rather than by `#/$defs/...` pointer.
12
+ *
13
+ * Supported subset (deliberate, documented in the package README):
14
+ *
15
+ * - Anchors (`$anchor`/`$dynamicAnchor`) resolve within the referencing
16
+ * resource's scope first, falling back to a document-global search — so
17
+ * duplicate anchor names under different `$id`s bind correctly.
18
+ * - A ref whose URI (resolved against the enclosing base) matches an embedded
19
+ * resource's `$id` resolves to that resource without any fetching; a pointer
20
+ * or anchor fragment on such a ref applies *within* that resource.
21
+ * - A plain `#/pointer` fragment stays **document-root-relative** (matching the
22
+ * previous behavior and what bundled real-world documents rely on), even when
23
+ * it appears inside an embedded resource.
24
+ * - `$dynamicRef` prefers a `$dynamicAnchor` in scope, then degrades to `$ref`
25
+ * semantics. The full dynamic-scope algorithm (outermost anchor along the
26
+ * *runtime* reference chain) is not modelled — for the single bundled
27
+ * document this resolver produces, the two agree unless the same
28
+ * `$dynamicAnchor` name is redeclared across resources *and* dispatched
29
+ * through recursive scopes.
30
+ * - Document *retrieval* is unaffected: which file/URL an external ref loads
31
+ * from is still derived from the referencing document's location, not from
32
+ * its `$id` — so a root `$id` naming a remote URL never turns a local
33
+ * sibling-file ref into a network fetch.
34
+ */
35
+ /** A resolved scoped target: the node, its in-document path, and its base URI. */
36
+ export type ScopedTarget = {
37
+ value: unknown;
38
+ pointer: JsonPath;
39
+ base: string;
40
+ };
41
+ export type ResourceRegistry = {
42
+ /** Normalized absolute URI (fragment stripped) → embedded resource root. */
43
+ resources: Map<string, {
44
+ value: unknown;
45
+ pointer: JsonPath;
46
+ }>;
47
+ /** `${base}#${name}` → target, for `$anchor` and `$dynamicAnchor` alike. */
48
+ staticAnchors: Map<string, {
49
+ value: unknown;
50
+ pointer: JsonPath;
51
+ }>;
52
+ /** `${base}#${name}` → target, for `$dynamicAnchor` only. */
53
+ dynamicAnchors: Map<string, {
54
+ value: unknown;
55
+ pointer: JsonPath;
56
+ }>;
57
+ /** The document root's base URI (its root `$id` resolved, or the initial base). */
58
+ rootBase: string;
59
+ /** The document root value, for root-relative pointer lookups. */
60
+ root: unknown;
61
+ };
62
+ /**
63
+ * The synthetic base used when a document has no natural URI to resolve
64
+ * relative `$id`s against (an in-memory document, or a local file path — which
65
+ * is not a URL). Uses the reserved `.invalid` TLD so it can never collide with
66
+ * a real `$id`.
67
+ */
68
+ export declare const SYNTHETIC_BASE = "https://mjst-internal.invalid/document";
69
+ /** `new URL(ref, base).href`, or `undefined` when the pair does not parse. */
70
+ export declare const resolveUri: (ref: string, base: string) => string | undefined;
71
+ /** Splits a ref string into its URI part and its fragment (pointer or anchor name). */
72
+ export declare const splitFragment: (ref: string) => {
73
+ uriPart: string;
74
+ fragment: string;
75
+ };
76
+ /**
77
+ * Walks the document once, registering every embedded resource (`$id`) and
78
+ * every anchor under the base URI it is scoped to. First declaration wins on
79
+ * a duplicate URI or anchor name, matching document order.
80
+ */
81
+ export declare const buildResourceRegistry: (root: unknown, initialBase?: string) => ResourceRegistry;
82
+ /**
83
+ * The base URI `node` establishes via its `$id`, as assigned during the
84
+ * registry walk (identity lookup), or `enclosing` when it declares none that
85
+ * registered. Resolvers call this while walking so refs inside an embedded
86
+ * resource resolve against the right base.
87
+ */
88
+ export declare const baseOfNode: (registry: ResourceRegistry, node: Record<string, unknown>, enclosing: string) => string;
89
+ /**
90
+ * Resolves a reference within the document's `$id` scope. Returns:
91
+ *
92
+ * - a {@link ScopedTarget} when the ref resolves to something in this document
93
+ * (a root-relative pointer, an anchor in scope, or an embedded resource);
94
+ * - `'external'` when the ref names a URI that matches no embedded resource —
95
+ * the caller decides whether to fetch it or leave it untouched;
96
+ * - `undefined` when the ref *should* resolve here but nothing matches (a
97
+ * missing anchor, a bad pointer into an embedded resource) — the caller may
98
+ * fall back to a document-global search for compatibility.
99
+ */
100
+ export declare const resolveRefInScope: (registry: ResourceRegistry, keyword: RefKeyword, ref: string, currentBase: string) => ScopedTarget | 'external' | undefined;
@@ -0,0 +1,186 @@
1
+ import { getByPointer, pointerToPath } from './get-by-pointer.js';
2
+ /**
3
+ * The synthetic base used when a document has no natural URI to resolve
4
+ * relative `$id`s against (an in-memory document, or a local file path — which
5
+ * is not a URL). Uses the reserved `.invalid` TLD so it can never collide with
6
+ * a real `$id`.
7
+ */
8
+ export const SYNTHETIC_BASE = 'https://mjst-internal.invalid/document';
9
+ // Keywords whose values are data, not subschemas — an `$id`/`$anchor` key
10
+ // inside an enum member or example value is instance data, not a declaration.
11
+ const NON_SCHEMA_KEYWORDS = new Set(['enum', 'const', 'default', 'examples']);
12
+ /** `new URL(ref, base).href`, or `undefined` when the pair does not parse. */
13
+ export const resolveUri = (ref, base) => {
14
+ try {
15
+ return new URL(ref, base).href;
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ };
21
+ /** Strips the fragment from an absolute URI string. */
22
+ const withoutFragment = (uri) => {
23
+ const hashIdx = uri.indexOf('#');
24
+ return hashIdx === -1 ? uri : uri.slice(0, hashIdx);
25
+ };
26
+ /** Splits a ref string into its URI part and its fragment (pointer or anchor name). */
27
+ export const splitFragment = (ref) => {
28
+ const hashIdx = ref.indexOf('#');
29
+ return {
30
+ uriPart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
31
+ fragment: hashIdx === -1 ? '' : ref.slice(hashIdx + 1),
32
+ };
33
+ };
34
+ /** The base URI a subschema establishes via `$id`, or the enclosing base. */
35
+ const baseAfterId = (node, enclosingBase) => {
36
+ const id = node['$id'];
37
+ if (typeof id !== 'string' || id === '')
38
+ return enclosingBase;
39
+ const resolved = resolveUri(id, enclosingBase);
40
+ // A draft-07-style `$id: "#name"` (or a malformed one) sets no new base.
41
+ if (resolved === undefined)
42
+ return enclosingBase;
43
+ const bare = withoutFragment(resolved);
44
+ return bare === '' ? enclosingBase : bare;
45
+ };
46
+ /**
47
+ * Walks the document once, registering every embedded resource (`$id`) and
48
+ * every anchor under the base URI it is scoped to. First declaration wins on
49
+ * a duplicate URI or anchor name, matching document order.
50
+ */
51
+ export const buildResourceRegistry = (root, initialBase = SYNTHETIC_BASE) => {
52
+ const resources = new Map();
53
+ const staticAnchors = new Map();
54
+ const dynamicAnchors = new Map();
55
+ const rootBase = root !== null && typeof root === 'object' && !Array.isArray(root)
56
+ ? baseAfterId(root, initialBase)
57
+ : initialBase;
58
+ const registerAnchors = (node, base, pointer) => {
59
+ const anchor = node['$anchor'];
60
+ if (typeof anchor === 'string') {
61
+ const key = `${base}#${anchor}`;
62
+ if (!staticAnchors.has(key))
63
+ staticAnchors.set(key, { value: node, pointer });
64
+ }
65
+ const dynamicAnchor = node['$dynamicAnchor'];
66
+ if (typeof dynamicAnchor === 'string') {
67
+ const key = `${base}#${dynamicAnchor}`;
68
+ // Per 2020-12 a `$dynamicAnchor` also creates an ordinary anchor.
69
+ if (!dynamicAnchors.has(key))
70
+ dynamicAnchors.set(key, { value: node, pointer });
71
+ if (!staticAnchors.has(key))
72
+ staticAnchors.set(key, { value: node, pointer });
73
+ }
74
+ };
75
+ const walk = (node, base, pointer) => {
76
+ if (node === null || typeof node !== 'object')
77
+ return;
78
+ if (Array.isArray(node)) {
79
+ for (let i = 0; i < node.length; i++)
80
+ walk(node[i], base, [...pointer, i]);
81
+ return;
82
+ }
83
+ const record = node;
84
+ const nodeBase = baseAfterId(record, base);
85
+ if (nodeBase !== base && !resources.has(nodeBase))
86
+ resources.set(nodeBase, { value: node, pointer });
87
+ registerAnchors(record, nodeBase, pointer);
88
+ for (const key of Object.keys(record)) {
89
+ if (NON_SCHEMA_KEYWORDS.has(key))
90
+ continue;
91
+ walk(record[key], nodeBase, [...pointer, key]);
92
+ }
93
+ };
94
+ // The root registers under its own `$id` (when it has one) and under the
95
+ // initial base, so both spellings of a self-reference resolve. `$id` first:
96
+ // `baseOfNode` scans in insertion order, and refs inside the root must
97
+ // resolve against its declared base, not the synthetic one.
98
+ if (rootBase !== initialBase)
99
+ resources.set(rootBase, { value: root, pointer: [] });
100
+ if (!resources.has(withoutFragment(initialBase))) {
101
+ resources.set(withoutFragment(initialBase), { value: root, pointer: [] });
102
+ }
103
+ walk(root, initialBase, []);
104
+ return { resources, staticAnchors, dynamicAnchors, rootBase, root };
105
+ };
106
+ /**
107
+ * Walks a JSON Pointer within `start`, tracking `$id` base changes along the
108
+ * way so the returned target carries the base URI refs inside it resolve
109
+ * against. Returns `undefined` when the pointer does not resolve.
110
+ */
111
+ const getByPointerWithBase = (start, startBase, startPointer, fragment) => {
112
+ const value = getByPointer(start, fragment);
113
+ if (value === undefined)
114
+ return undefined;
115
+ // Re-walk the same path for base tracking only (cheap: fragment paths are short).
116
+ let base = startBase;
117
+ let current = start;
118
+ for (const segment of pointerToPath(fragment)) {
119
+ if (current === null || typeof current !== 'object')
120
+ break;
121
+ if (!Array.isArray(current))
122
+ base = baseAfterId(current, base);
123
+ current = current[segment];
124
+ }
125
+ if (current !== null && typeof current === 'object' && !Array.isArray(current)) {
126
+ base = baseAfterId(current, base);
127
+ }
128
+ return { value, pointer: [...startPointer, ...pointerToPath(fragment)], base };
129
+ };
130
+ /** A fragment is a JSON Pointer when it is empty or begins with `/`; otherwise an anchor name. */
131
+ const isPointerFragment = (fragment) => fragment === '' || fragment.startsWith('/');
132
+ /**
133
+ * The base URI `node` establishes via its `$id`, as assigned during the
134
+ * registry walk (identity lookup), or `enclosing` when it declares none that
135
+ * registered. Resolvers call this while walking so refs inside an embedded
136
+ * resource resolve against the right base.
137
+ */
138
+ export const baseOfNode = (registry, node, enclosing) => {
139
+ for (const [uri, resource] of registry.resources) {
140
+ if (resource.value === node)
141
+ return uri;
142
+ }
143
+ return enclosing;
144
+ };
145
+ /** Looks up an anchor name under `base`, honoring `$dynamicRef`'s preference order. */
146
+ const lookupAnchor = (registry, keyword, base, name) => {
147
+ const key = `${base}#${name}`;
148
+ if (keyword === '$dynamicRef')
149
+ return registry.dynamicAnchors.get(key) ?? registry.staticAnchors.get(key);
150
+ return registry.staticAnchors.get(key);
151
+ };
152
+ /**
153
+ * Resolves a reference within the document's `$id` scope. Returns:
154
+ *
155
+ * - a {@link ScopedTarget} when the ref resolves to something in this document
156
+ * (a root-relative pointer, an anchor in scope, or an embedded resource);
157
+ * - `'external'` when the ref names a URI that matches no embedded resource —
158
+ * the caller decides whether to fetch it or leave it untouched;
159
+ * - `undefined` when the ref *should* resolve here but nothing matches (a
160
+ * missing anchor, a bad pointer into an embedded resource) — the caller may
161
+ * fall back to a document-global search for compatibility.
162
+ */
163
+ export const resolveRefInScope = (registry, keyword, ref, currentBase) => {
164
+ const { uriPart, fragment } = splitFragment(ref);
165
+ if (uriPart === '') {
166
+ // A plain `#/pointer` stays document-root-relative (see module doc).
167
+ if (isPointerFragment(fragment)) {
168
+ return getByPointerWithBase(registry.root, registry.rootBase, [], fragment);
169
+ }
170
+ // An anchor name resolves within the current resource's scope.
171
+ const anchored = lookupAnchor(registry, keyword, currentBase, fragment);
172
+ return anchored === undefined ? undefined : { ...anchored, base: currentBase };
173
+ }
174
+ const absolute = resolveUri(ref, currentBase);
175
+ if (absolute === undefined)
176
+ return 'external';
177
+ const resource = registry.resources.get(withoutFragment(absolute));
178
+ if (resource === undefined)
179
+ return 'external';
180
+ if (isPointerFragment(fragment)) {
181
+ const resourceBase = withoutFragment(absolute);
182
+ return getByPointerWithBase(resource.value, resourceBase, resource.pointer, fragment);
183
+ }
184
+ const anchored = lookupAnchor(registry, keyword, withoutFragment(absolute), fragment);
185
+ return anchored === undefined ? undefined : { ...anchored, base: withoutFragment(absolute) };
186
+ };
package/dist/types.d.ts CHANGED
@@ -80,4 +80,38 @@ export type ResolveOptions = {
80
80
  * to their source without re-walking the `$ref` chain. Defaults to `false`.
81
81
  */
82
82
  trackOrigins?: boolean;
83
+ /**
84
+ * Extra HTTP headers sent with remote `$ref` requests (e.g. an `Authorization`
85
+ * token for a private schema registry) — a static record, or a function
86
+ * returning headers per URL so different hosts can carry different
87
+ * credentials. To avoid leaking credentials, headers are only sent on redirect
88
+ * hops whose origin matches the originally requested URL — the same policy
89
+ * browsers apply to `Authorization` across cross-origin redirects.
90
+ */
91
+ headers?: Record<string, string> | ((url: string) => Record<string, string> | undefined);
92
+ /**
93
+ * Custom fetch implementation for remote documents (an instrumented client, a
94
+ * proxy-aware one, a test stub). Called once per redirect hop with
95
+ * `redirect: 'manual'` and a timeout signal. The SSRF guard still evaluates
96
+ * every hop before this is called — a custom fetch widens *how* documents are
97
+ * fetched, never *which* hosts may be. Defaults to the global `fetch`.
98
+ */
99
+ fetch?: (url: string, init: {
100
+ redirect: 'manual';
101
+ signal: AbortSignal;
102
+ headers?: Record<string, string>;
103
+ }) => Promise<Response>;
104
+ /** Milliseconds before an unresponsive remote fetch is aborted. Defaults to `30_000`. */
105
+ timeoutMs?: number;
106
+ /** Maximum redirect hops to follow per remote document. Defaults to `5`. */
107
+ maxRedirects?: number;
108
+ /** Maximum bytes buffered per remote document. Defaults to `16` MiB. */
109
+ maxBytes?: number;
110
+ /**
111
+ * Whether fetched remote documents may be served from (and stored into) the
112
+ * process-wide session cache. Pass `false` to bypass it for one call: every
113
+ * remote document is re-fetched and nothing new is cached — useful when a
114
+ * remote schema is known to have changed mid-session. Defaults to `true`.
115
+ */
116
+ cache?: boolean;
83
117
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/resolve-refs",
3
- "version": "0.3.0",
3
+ "version": "0.4.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
  "module": "./dist/index.js",
6
6
  "type": "module",