@apidevtools/json-schema-ref-parser 15.3.0 → 15.3.2

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/lib/pointer.ts CHANGED
@@ -3,6 +3,7 @@ import type { ParserOptions } from "./options.js";
3
3
  import $Ref from "./ref.js";
4
4
  import * as url from "./util/url.js";
5
5
  import { JSONParserError, InvalidPointerError, MissingPointerError, isHandledError } from "./util/errors.js";
6
+ import { getSchemaBasePath } from "./util/schema-resources.js";
6
7
  import type { JSONSchema } from "./index.js";
7
8
  import type { JSONSchema4Type, JSONSchema6Type, JSONSchema7Type } from "json-schema";
8
9
 
@@ -38,6 +39,11 @@ class Pointer<S extends object = JSONSchema, O extends ParserOptions<S> = Parser
38
39
  */
39
40
  originalPath: string;
40
41
 
42
+ /**
43
+ * The current base URI used to resolve nested $ref pointers while walking this pointer.
44
+ */
45
+ scopeBase: string;
46
+
41
47
  /**
42
48
  * The value of the JSON pointer.
43
49
  * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays).
@@ -61,6 +67,8 @@ class Pointer<S extends object = JSONSchema, O extends ParserOptions<S> = Parser
61
67
 
62
68
  this.originalPath = friendlyPath || path;
63
69
 
70
+ this.scopeBase = $ref.path || url.stripHash(path);
71
+
64
72
  this.value = undefined;
65
73
 
66
74
  this.circular = false;
@@ -87,6 +95,9 @@ class Pointer<S extends object = JSONSchema, O extends ParserOptions<S> = Parser
87
95
 
88
96
  // Crawl the object, one token at a time
89
97
  this.value = unwrapOrThrow(obj);
98
+ if (this.$ref.dynamicIdScope) {
99
+ this.scopeBase = getSchemaBasePath(this.scopeBase, this.value);
100
+ }
90
101
 
91
102
  for (let i = 0; i < tokens.length; i++) {
92
103
  // During token walking, if the current value is an extended $ref (has sibling keys
@@ -149,10 +160,14 @@ class Pointer<S extends object = JSONSchema, O extends ParserOptions<S> = Parser
149
160
  }
150
161
 
151
162
  found.push(token);
163
+ if (this.$ref.dynamicIdScope) {
164
+ this.scopeBase = getSchemaBasePath(this.scopeBase, this.value);
165
+ }
152
166
  }
153
167
 
154
168
  // Resolve the final value
155
- if (!this.value || (this.value.$ref && url.resolve(this.path, this.value.$ref) !== pathFromRoot)) {
169
+ const finalResolutionBase = this.$ref.dynamicIdScope ? this.scopeBase : this.path;
170
+ if (!this.value || (this.value.$ref && url.resolve(finalResolutionBase, this.value.$ref) !== pathFromRoot)) {
156
171
  resolveIf$Ref(this, options, pathFromRoot);
157
172
  }
158
173
 
@@ -181,6 +196,9 @@ class Pointer<S extends object = JSONSchema, O extends ParserOptions<S> = Parser
181
196
 
182
197
  // Crawl the object, one token at a time
183
198
  this.value = unwrapOrThrow(obj);
199
+ if (this.$ref.dynamicIdScope) {
200
+ this.scopeBase = getSchemaBasePath(this.scopeBase, this.value);
201
+ }
184
202
 
185
203
  for (let i = 0; i < tokens.length - 1; i++) {
186
204
  resolveIf$Ref(this, options);
@@ -193,6 +211,10 @@ class Pointer<S extends object = JSONSchema, O extends ParserOptions<S> = Parser
193
211
  // The token doesn't exist, so create it
194
212
  this.value = setValue(this, token, {});
195
213
  }
214
+
215
+ if (this.$ref.dynamicIdScope) {
216
+ this.scopeBase = getSchemaBasePath(this.scopeBase, this.value);
217
+ }
196
218
  }
197
219
 
198
220
  // Set the value of the final token
@@ -287,7 +309,8 @@ function resolveIf$Ref<S extends object = JSONSchema, O extends ParserOptions<S>
287
309
  // Is the value a JSON reference? (and allowed?)
288
310
 
289
311
  if ($Ref.isAllowed$Ref(pointer.value, options)) {
290
- const $refPath = url.resolve(pointer.path, pointer.value.$ref);
312
+ const resolutionBase = pointer.$ref.dynamicIdScope ? pointer.scopeBase : pointer.path;
313
+ const $refPath = url.resolve(resolutionBase, pointer.value.$ref);
291
314
 
292
315
  if ($refPath === pointer.path && !isRootPath(pathFromRoot)) {
293
316
  // The value is a reference to itself, so there's nothing to do.
@@ -304,12 +327,18 @@ function resolveIf$Ref<S extends object = JSONSchema, O extends ParserOptions<S>
304
327
  // This JSON reference "extends" the resolved value, rather than simply pointing to it.
305
328
  // So the resolved path does NOT change. Just the value does.
306
329
  pointer.value = $Ref.dereference(pointer.value, resolved.value, options);
330
+ if (pointer.$ref.dynamicIdScope) {
331
+ pointer.scopeBase = getSchemaBasePath(pointer.scopeBase, pointer.value);
332
+ }
307
333
  return false;
308
334
  } else {
309
335
  // Resolve the reference
310
336
  pointer.$ref = resolved.$ref;
311
337
  pointer.path = resolved.path;
312
338
  pointer.value = resolved.value;
339
+ pointer.scopeBase = pointer.$ref.dynamicIdScope
340
+ ? getSchemaBasePath(pointer.$ref.path!, pointer.value)
341
+ : pointer.$ref.path!;
313
342
  }
314
343
 
315
344
  return true;
package/lib/ref.ts CHANGED
@@ -47,6 +47,11 @@ class $Ref<S extends object = JSONSchema, O extends ParserOptions<S> = ParserOpt
47
47
  */
48
48
  pathType: string | unknown;
49
49
 
50
+ /**
51
+ * Whether this document/resource should use JSON Schema 2019-09+ nested $id scope semantics.
52
+ */
53
+ dynamicIdScope = false;
54
+
50
55
  /**
51
56
  * List of all errors. Undefined if no errors.
52
57
  */
package/lib/refs.ts CHANGED
@@ -95,11 +95,10 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
95
95
  */
96
96
  set(path: string, value: JSONSchema4Type | JSONSchema6Type | JSONSchema7Type) {
97
97
  const absPath = url.resolve(this._root$Ref.path!, path);
98
- const withoutHash = url.stripHash(absPath);
99
- const $ref = this._$refs[withoutHash];
98
+ const $ref = this._getRef(absPath);
100
99
 
101
100
  if (!$ref) {
102
- throw new Error(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`);
101
+ throw new Error(`Error resolving $ref pointer "${path}". \n"${url.stripHash(absPath)}" not found.`);
103
102
  }
104
103
 
105
104
  $ref.set(absPath, value);
@@ -113,8 +112,7 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
113
112
  */
114
113
  _get$Ref(path: string) {
115
114
  path = url.resolve(this._root$Ref.path!, path);
116
- const withoutHash = url.stripHash(path);
117
- return this._$refs[withoutHash];
115
+ return this._getRef(path);
118
116
  }
119
117
 
120
118
  /**
@@ -134,6 +132,23 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
134
132
  return $ref;
135
133
  }
136
134
 
135
+ _addAlias(path: string, value: S, pathType?: string | unknown, dynamicIdScope = false) {
136
+ const withoutHash = url.stripHash(path);
137
+
138
+ if (!withoutHash || this._$refs[withoutHash] || this._aliases[withoutHash]) {
139
+ return this._$refs[withoutHash] || this._aliases[withoutHash];
140
+ }
141
+
142
+ const $ref = new $Ref<S, O>(this);
143
+ $ref.path = withoutHash;
144
+ $ref.pathType = pathType;
145
+ $ref.value = value;
146
+ $ref.dynamicIdScope = dynamicIdScope;
147
+
148
+ this._aliases[withoutHash] = $ref;
149
+ return $ref;
150
+ }
151
+
137
152
  /**
138
153
  * Resolves the given JSON reference.
139
154
  *
@@ -145,11 +160,10 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
145
160
  */
146
161
  _resolve(path: string, pathFromRoot: string, options?: O) {
147
162
  const absPath = url.resolve(this._root$Ref.path!, path);
148
- const withoutHash = url.stripHash(absPath);
149
- const $ref = this._$refs[withoutHash];
163
+ const $ref = this._getRef(absPath);
150
164
 
151
165
  if (!$ref) {
152
- throw new Error(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`);
166
+ throw new Error(`Error resolving $ref pointer "${path}". \n"${url.stripHash(absPath)}" not found.`);
153
167
  }
154
168
 
155
169
  return $ref.resolve(absPath, options, path, pathFromRoot);
@@ -163,6 +177,8 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
163
177
  */
164
178
  _$refs: $RefsMap<S, O> = {};
165
179
 
180
+ _aliases: $RefsMap<S, O> = {};
181
+
166
182
  /**
167
183
  * The {@link $Ref} object that is the root of the JSON schema.
168
184
  *
@@ -180,6 +196,7 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
180
196
  this.circular = false;
181
197
 
182
198
  this._$refs = {};
199
+ this._aliases = {};
183
200
 
184
201
  // @ts-ignore
185
202
  this._root$Ref = null;
@@ -205,6 +222,11 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
205
222
  * @returns {object}
206
223
  */
207
224
  toJSON = this.values;
225
+
226
+ private _getRef(path: string) {
227
+ const withoutHash = url.stripHash(path);
228
+ return this._$refs[withoutHash] || this._aliases[withoutHash];
229
+ }
208
230
  }
209
231
 
210
232
  /**
@@ -3,6 +3,7 @@ import Pointer from "./pointer.js";
3
3
  import parse from "./parse.js";
4
4
  import * as url from "./util/url.js";
5
5
  import { isHandledError } from "./util/errors.js";
6
+ import { getSchemaBasePath } from "./util/schema-resources.js";
6
7
  import type $Refs from "./refs.js";
7
8
  import type { ParserOptions } from "./options.js";
8
9
  import type { JSONSchema } from "./types/index.js";
@@ -29,7 +30,14 @@ function resolveExternal<S extends object = JSONSchema, O extends ParserOptions<
29
30
 
30
31
  try {
31
32
  // console.log('Resolving $ref pointers in %s', parser.$refs._root$Ref.path);
32
- const promises = crawl(parser.schema, parser.$refs._root$Ref.path + "#", parser.$refs, options);
33
+ const promises = crawl(
34
+ parser.schema,
35
+ parser.$refs._root$Ref.path + "#",
36
+ parser.$refs._root$Ref.path!,
37
+ parser.$refs._root$Ref.dynamicIdScope,
38
+ parser.$refs,
39
+ options,
40
+ );
33
41
  return Promise.all(promises);
34
42
  } catch (e) {
35
43
  return Promise.reject(e);
@@ -55,6 +63,8 @@ function resolveExternal<S extends object = JSONSchema, O extends ParserOptions<
55
63
  function crawl<S extends object = JSONSchema, O extends ParserOptions<S> = ParserOptions<S>>(
56
64
  obj: string | Buffer | S | undefined | null,
57
65
  path: string,
66
+ scopeBase: string,
67
+ dynamicIdScope: boolean,
58
68
  $refs: $Refs<S, O>,
59
69
  options: O,
60
70
  seen?: Set<any>,
@@ -65,15 +75,18 @@ function crawl<S extends object = JSONSchema, O extends ParserOptions<S> = Parse
65
75
 
66
76
  if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj) && !seen.has(obj)) {
67
77
  seen.add(obj); // Track previously seen objects to avoid infinite recursion
78
+ const currentScopeBase = dynamicIdScope ? getSchemaBasePath(scopeBase, obj) : scopeBase;
68
79
  if ($Ref.isExternal$Ref(obj)) {
69
- promises.push(resolve$Ref<S, O>(obj, path, $refs, options));
80
+ promises.push(resolve$Ref<S, O>(obj, path, currentScopeBase, dynamicIdScope, $refs, options));
70
81
  }
71
82
 
72
83
  const keys = Object.keys(obj) as string[];
73
84
  for (const key of keys) {
74
85
  const keyPath = Pointer.join(path, key);
75
86
  const value = obj[key as keyof typeof obj] as string | JSONSchema | Buffer | undefined;
76
- promises = promises.concat(crawl(value, keyPath, $refs, options, seen, external));
87
+ const childScopeBase =
88
+ dynamicIdScope && $Ref.isExternal$Ref(value) ? getSchemaBasePath(currentScopeBase, value) : currentScopeBase;
89
+ promises = promises.concat(crawl(value, keyPath, childScopeBase, dynamicIdScope, $refs, options, seen, external));
77
90
  }
78
91
  }
79
92
 
@@ -95,17 +108,20 @@ function crawl<S extends object = JSONSchema, O extends ParserOptions<S> = Parse
95
108
  async function resolve$Ref<S extends object = JSONSchema, O extends ParserOptions<S> = ParserOptions<S>>(
96
109
  $ref: S,
97
110
  path: string,
111
+ scopeBase: string,
112
+ dynamicIdScope: boolean,
98
113
  $refs: $Refs<S, O>,
99
114
  options: O,
100
115
  ) {
101
116
  const shouldResolveOnCwd = options.dereference?.externalReferenceResolution === "root";
102
- const resolvedPath = url.resolve(shouldResolveOnCwd ? url.cwd() : path, ($ref as JSONSchema).$ref!);
117
+ const resolutionBase = shouldResolveOnCwd ? url.cwd() : dynamicIdScope ? scopeBase : path;
118
+ const resolvedPath = url.resolve(resolutionBase, ($ref as JSONSchema).$ref!);
103
119
  const withoutHash = url.stripHash(resolvedPath);
104
120
 
105
121
  // $ref.$ref = url.relative($refs._root$Ref.path, resolvedPath);
106
122
 
107
123
  // Do we already have this $ref?
108
- const ref = $refs._$refs[withoutHash];
124
+ const ref = $refs._get$Ref(withoutHash);
109
125
  if (ref) {
110
126
  // We've already parsed this $ref, so use the existing value
111
127
  return Promise.resolve(ref.value);
@@ -113,11 +129,33 @@ async function resolve$Ref<S extends object = JSONSchema, O extends ParserOption
113
129
 
114
130
  // Parse the $referenced file/url
115
131
  try {
116
- const result = await parse(resolvedPath, $refs, options);
132
+ const reference = ($ref as JSONSchema).$ref;
133
+ const parseTarget: { url: string; baseUrl: string; reference?: string } = {
134
+ url: resolvedPath,
135
+ baseUrl: resolutionBase,
136
+ };
137
+ if (typeof reference === "string") {
138
+ parseTarget.reference = reference;
139
+ }
140
+ const result = await parse(
141
+ parseTarget,
142
+ $refs,
143
+ options,
144
+ );
117
145
 
118
146
  // Crawl the parsed value
119
147
  // console.log('Resolving $ref pointers in %s', withoutHash);
120
- const promises = crawl(result, withoutHash + "#", $refs, options, new Set(), true);
148
+ const parsedRef = $refs._get$Ref(withoutHash);
149
+ const promises = crawl(
150
+ result,
151
+ withoutHash + "#",
152
+ withoutHash,
153
+ parsedRef?.dynamicIdScope ?? false,
154
+ $refs,
155
+ options,
156
+ new Set(),
157
+ true,
158
+ );
121
159
 
122
160
  return Promise.all(promises);
123
161
  } catch (err) {
@@ -139,6 +139,19 @@ export interface FileInfo {
139
139
  */
140
140
  url: string;
141
141
 
142
+ /**
143
+ * The unresolved `$ref` value exactly as it appeared in the parent schema, without the hash.
144
+ * This is useful for custom resolvers that need to preserve relative reference semantics instead
145
+ * of relying on the already-resolved `url`.
146
+ */
147
+ reference?: string;
148
+
149
+ /**
150
+ * The URL that `reference` was resolved against to produce `url`.
151
+ * This may include a JSON Pointer fragment when the reference originated from a nested location.
152
+ */
153
+ baseUrl?: string;
154
+
142
155
  /**
143
156
  * The hash (URL fragment) of the file URL, including the # symbol. If the URL doesn't have a hash, then this will be an empty string.
144
157
  */
@@ -0,0 +1,73 @@
1
+ import * as url from "./url.js";
2
+ import type { ParserOptions } from "../options.js";
3
+ import type { JSONSchema } from "../index.js";
4
+ import type $Refs from "../refs.js";
5
+
6
+ export function getSchemaBasePath(basePath: string, value: unknown) {
7
+ const schemaId = getSchemaId(value);
8
+ return schemaId ? url.resolve(basePath, schemaId) : basePath;
9
+ }
10
+
11
+ export function usesDynamicIdScope(value: unknown) {
12
+ if (!value || typeof value !== "object" || ArrayBuffer.isView(value)) {
13
+ return false;
14
+ }
15
+
16
+ const schema = (value as { $schema?: unknown }).$schema;
17
+ if (
18
+ typeof schema === "string" &&
19
+ (schema.includes("draft/2019-09/") || schema.includes("draft/2020-12/") || schema.includes("oas/3.1/"))
20
+ ) {
21
+ return true;
22
+ }
23
+
24
+ const openapi = (value as { openapi?: unknown }).openapi;
25
+ return typeof openapi === "string" && /^3\.1(?:\.|$)/.test(openapi);
26
+ }
27
+
28
+ export function registerSchemaResources<S extends object = JSONSchema, O extends ParserOptions<S> = ParserOptions<S>>(
29
+ $refs: $Refs<S, O>,
30
+ basePath: string,
31
+ value: unknown,
32
+ pathType?: string | unknown,
33
+ dynamicIdScope = false,
34
+ ) {
35
+ if (!dynamicIdScope) {
36
+ return;
37
+ }
38
+
39
+ const seen = new Set<object>();
40
+
41
+ const visit = (node: unknown, scopeBase: string) => {
42
+ if (!node || typeof node !== "object" || ArrayBuffer.isView(node) || seen.has(node)) {
43
+ return;
44
+ }
45
+
46
+ seen.add(node);
47
+
48
+ const nextScopeBase = getSchemaBasePath(scopeBase, node);
49
+ if (nextScopeBase !== scopeBase) {
50
+ $refs._addAlias(nextScopeBase, node as S, pathType, dynamicIdScope);
51
+ }
52
+
53
+ for (const key of Object.keys(node)) {
54
+ visit((node as Record<string, unknown>)[key], nextScopeBase);
55
+ }
56
+ };
57
+
58
+ visit(value, basePath);
59
+ }
60
+
61
+ function getSchemaId(value: unknown): string | undefined {
62
+ if (
63
+ value &&
64
+ typeof value === "object" &&
65
+ "$id" in value &&
66
+ typeof (value as { $id?: unknown }).$id === "string" &&
67
+ (value as { $id: string }).$id.length > 0
68
+ ) {
69
+ return (value as { $id: string }).$id;
70
+ }
71
+
72
+ return undefined;
73
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apidevtools/json-schema-ref-parser",
3
- "version": "15.3.0",
3
+ "version": "15.3.2",
4
4
  "description": "Parse, Resolve, and Dereference JSON Schema $ref pointers",
5
5
  "type": "module",
6
6
  "types": "dist/lib/index.d.ts",
@@ -75,29 +75,29 @@
75
75
  "js-yaml": "^4.1.1"
76
76
  },
77
77
  "devDependencies": {
78
- "@eslint/compat": "^2.0.2",
78
+ "@eslint/compat": "^2.0.3",
79
79
  "@eslint/js": "^10.0.1",
80
80
  "@types/eslint": "^9.6.1",
81
81
  "@types/js-yaml": "^4.0.9",
82
82
  "@types/json-schema": "^7.0.15",
83
83
  "@types/node": "^25",
84
- "@typescript-eslint/eslint-plugin": "^8.56.1",
85
- "@typescript-eslint/parser": "^8.56.1",
86
- "@vitest/coverage-v8": "^4.0.18",
84
+ "@typescript-eslint/eslint-plugin": "^8.57.2",
85
+ "@typescript-eslint/parser": "^8.57.2",
86
+ "@vitest/coverage-v8": "^4.1.1",
87
87
  "cross-env": "^10.1.0",
88
- "eslint": "^10.0.2",
88
+ "eslint": "^10.1.0",
89
89
  "eslint-config-prettier": "^10.1.8",
90
90
  "eslint-plugin-import": "^2.32.0",
91
91
  "eslint-plugin-prettier": "^5.5.5",
92
92
  "eslint-plugin-promise": "^7.2.1",
93
93
  "eslint-plugin-unused-imports": "^4.4.1",
94
- "globals": "^17.3.0",
95
- "jsdom": "^28.1.0",
94
+ "globals": "^17.4.0",
95
+ "jsdom": "^29.0.1",
96
96
  "prettier": "^3.8.1",
97
97
  "rimraf": "^6.1.3",
98
- "typescript": "^5.9.3",
99
- "typescript-eslint": "^8.56.1",
100
- "vitest": "^4.0.18"
98
+ "typescript": "^6.0.2",
99
+ "typescript-eslint": "^8.57.2",
100
+ "vitest": "^4.1.1"
101
101
  },
102
102
  "release": {
103
103
  "branches": [
@@ -110,5 +110,5 @@
110
110
  "@semantic-release/github"
111
111
  ]
112
112
  },
113
- "packageManager": "yarn@4.12.0"
113
+ "packageManager": "yarn@4.13.0"
114
114
  }