@speclynx/apidom-reference 3.0.0 → 3.1.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +97 -0
  3. package/dist/apidom-reference.browser.js +3854 -3241
  4. package/dist/apidom-reference.browser.min.js +1 -1
  5. package/package.json +25 -25
  6. package/src/dereference/index.cjs +4 -0
  7. package/src/dereference/index.mjs +4 -0
  8. package/src/dereference/strategies/apidom/visitor.cjs +139 -59
  9. package/src/dereference/strategies/apidom/visitor.mjs +142 -62
  10. package/src/dereference/strategies/arazzo-1/index.cjs +1 -4
  11. package/src/dereference/strategies/arazzo-1/index.mjs +2 -4
  12. package/src/dereference/strategies/arazzo-1/visitor.cjs +288 -199
  13. package/src/dereference/strategies/arazzo-1/visitor.mjs +291 -203
  14. package/src/dereference/strategies/asyncapi-2/index.cjs +1 -4
  15. package/src/dereference/strategies/asyncapi-2/index.mjs +2 -4
  16. package/src/dereference/strategies/asyncapi-2/visitor.cjs +323 -229
  17. package/src/dereference/strategies/asyncapi-2/visitor.mjs +326 -233
  18. package/src/dereference/strategies/openapi-2/index.cjs +1 -4
  19. package/src/dereference/strategies/openapi-2/index.mjs +2 -4
  20. package/src/dereference/strategies/openapi-2/visitor.cjs +417 -318
  21. package/src/dereference/strategies/openapi-2/visitor.mjs +422 -324
  22. package/src/dereference/strategies/openapi-3-0/index.cjs +1 -4
  23. package/src/dereference/strategies/openapi-3-0/index.mjs +2 -4
  24. package/src/dereference/strategies/openapi-3-0/visitor.cjs +403 -286
  25. package/src/dereference/strategies/openapi-3-0/visitor.mjs +407 -291
  26. package/src/dereference/strategies/openapi-3-1/index.cjs +1 -4
  27. package/src/dereference/strategies/openapi-3-1/index.mjs +2 -4
  28. package/src/dereference/strategies/openapi-3-1/visitor.cjs +598 -484
  29. package/src/dereference/strategies/openapi-3-1/visitor.mjs +602 -489
  30. package/src/errors/DereferenceError.cjs +1 -1
  31. package/src/errors/DereferenceError.mjs +2 -2
  32. package/src/errors/ResolveError.cjs +1 -1
  33. package/src/errors/ResolveError.mjs +2 -2
  34. package/src/errors/UnresolvableReferenceError.cjs +11 -0
  35. package/src/errors/UnresolvableReferenceError.mjs +6 -0
  36. package/src/index.cjs +3 -1
  37. package/src/index.mjs +1 -0
  38. package/src/options/index.cjs +10 -1
  39. package/src/options/index.mjs +10 -1
  40. package/src/util/plugins.cjs +1 -6
  41. package/src/util/plugins.mjs +2 -5
  42. package/types/apidom-reference.d.ts +10 -2
  43. package/types/dereference/strategies/apidom/visitor.d.ts +10 -0
  44. package/types/dereference/strategies/arazzo-1/visitor.d.ts +19 -5
  45. package/types/dereference/strategies/asyncapi-2/visitor.d.ts +21 -7
  46. package/types/dereference/strategies/openapi-2/visitor.d.ts +21 -8
  47. package/types/dereference/strategies/openapi-3-0/visitor.d.ts +21 -7
  48. package/types/dereference/strategies/openapi-3-1/visitor.d.ts +21 -7
  49. package/types/errors/DereferenceError.d.ts +2 -2
  50. package/types/errors/ResolveError.d.ts +2 -2
  51. package/types/errors/UnresolvableReferenceError.d.ts +7 -0
  52. package/types/index.d.ts +1 -0
  53. package/types/options/index.d.ts +2 -0
@@ -1,47 +1,53 @@
1
1
  import { propEq } from 'ramda';
2
- import { RefElement, isPrimitiveElement, isStringElement, isElement, cloneShallow, cloneDeep } from '@speclynx/apidom-datamodel';
3
- import { IdentityManager, toValue } from '@speclynx/apidom-core';
4
- import { ApiDOMError } from '@speclynx/apidom-error';
5
- import { traverseAsync } from '@speclynx/apidom-traverse';
2
+ import { RefElement, isStringElement, isElement, cloneShallow, cloneDeep } from '@speclynx/apidom-datamodel';
3
+ import { toValue, toYAML } from '@speclynx/apidom-core';
4
+ import { ApiDOMStructuredError } from '@speclynx/apidom-error';
5
+ import { traverse, traverseAsync } from '@speclynx/apidom-traverse';
6
6
  import { evaluate, URIFragmentIdentifier } from '@speclynx/apidom-json-pointer';
7
- import { isReferenceElement, isJSONReferenceElement, isPathItemElement, isReferenceLikeElement, isJSONReferenceLikeElement, refract, refractReference, refractPathItem } from '@speclynx/apidom-ns-openapi-2';
7
+ import { isReferenceElement, isJSONReferenceElement, isPathItemElement, isReferenceLikeElement, isJSONReferenceLikeElement, refract, refractReference, refractPathItem, refractJSONReference } from '@speclynx/apidom-ns-openapi-2';
8
+ import UnresolvableReferenceError from "../../../errors/UnresolvableReferenceError.mjs";
8
9
  import MaximumDereferenceDepthError from "../../../errors/MaximumDereferenceDepthError.mjs";
9
10
  import MaximumResolveDepthError from "../../../errors/MaximumResolveDepthError.mjs";
10
11
  import { AncestorLineage } from "../../util.mjs";
11
12
  import * as url from "../../../util/url.mjs";
12
13
  import parse from "../../../parse/index.mjs";
13
14
  import Reference from "../../../Reference.mjs";
14
- // initialize element identity manager
15
- const identityManager = new IdentityManager();
16
-
17
15
  /**
18
16
  * @public
19
17
  */
20
-
21
18
  /**
22
19
  * @public
23
20
  */
24
21
  class OpenAPI2DereferenceVisitor {
25
22
  indirections;
26
- namespace;
27
23
  reference;
28
24
  options;
29
- ancestors;
30
25
  refractCache;
26
+
27
+ /**
28
+ * Tracks element ancestors across dive-deep traversal boundaries.
29
+ * Used for cycle detection: if a referenced element is found in
30
+ * the ancestor lineage, a circular reference is detected.
31
+ */
32
+ ancestors;
31
33
  constructor({
32
34
  reference,
33
- namespace,
34
35
  options,
35
36
  indirections = [],
36
37
  ancestors = new AncestorLineage(),
37
- refractCache = new Map()
38
+ refractCache = new WeakMap()
38
39
  }) {
39
40
  this.indirections = indirections;
40
- this.namespace = namespace;
41
41
  this.reference = reference;
42
42
  this.options = options;
43
- this.ancestors = new AncestorLineage(...ancestors);
44
43
  this.refractCache = refractCache;
44
+ this.ancestors = new AncestorLineage(...ancestors);
45
+ }
46
+ toAncestorLineage(path) {
47
+ const ancestorNodes = path.getAncestorNodes();
48
+ const directAncestors = new Set(ancestorNodes.filter(isElement));
49
+ const ancestorsLineage = new AncestorLineage(...this.ancestors, directAncestors);
50
+ return [ancestorsLineage, directAncestors];
45
51
  }
46
52
  toBaseURI(uri) {
47
53
  return url.resolve(this.reference.uri, url.sanitize(url.stripHash(uri)));
@@ -49,7 +55,10 @@ class OpenAPI2DereferenceVisitor {
49
55
  async toReference(uri) {
50
56
  // detect maximum depth of resolution
51
57
  if (this.reference.depth >= this.options.resolve.maxDepth) {
52
- throw new MaximumResolveDepthError(`Maximum resolution depth of ${this.options.resolve.maxDepth} has been exceeded by file "${this.reference.uri}"`);
58
+ throw new MaximumResolveDepthError(`Maximum resolution depth of ${this.options.resolve.maxDepth} has been exceeded by file "${this.reference.uri}"`, {
59
+ maxDepth: this.options.resolve.maxDepth,
60
+ uri: this.reference.uri
61
+ });
53
62
  }
54
63
  const baseURI = this.toBaseURI(uri);
55
64
  const {
@@ -69,9 +78,23 @@ class OpenAPI2DereferenceVisitor {
69
78
  });
70
79
 
71
80
  // register new mutable reference with a refSet
81
+ //
82
+ // NOTE(known limitation): the mutable reference is mutated in place during traversal
83
+ // (via `{ mutable: true }`). When an external document evaluates a JSON pointer back
84
+ // into this document, it may receive an already-resolved element instead of the original
85
+ // $ref. That resolved element was produced using the entry document's resolution context
86
+ // (ancestors, indirections), which may differ from the external document's context.
87
+ // This can affect cycle detection in rare cross-document circular reference patterns.
88
+ //
89
+ // Remediation: evaluate JSON pointers against the immutable (original) parse tree
90
+ // instead of the mutable working copy. The `immutable://` reference below preserves
91
+ // the original tree and could be used for pointer evaluation, ensuring every resolution
92
+ // context always sees raw, unresolved elements and processes them with its own
93
+ // ancestors/indirections. The trade-off is that elements referenced by multiple
94
+ // documents would be resolved once per context instead of being reused.
72
95
  const mutableReference = new Reference({
73
96
  uri: baseURI,
74
- value: cloneDeep(parseResult),
97
+ value: this.options.dereference.immutable ? cloneDeep(parseResult) : parseResult,
75
98
  depth: this.reference.depth + 1
76
99
  });
77
100
  refSet.add(mutableReference);
@@ -86,15 +109,77 @@ class OpenAPI2DereferenceVisitor {
86
109
  }
87
110
  return mutableReference;
88
111
  }
89
- toAncestorLineage(path) {
90
- /**
91
- * Compute full ancestors lineage.
92
- * Ancestors are flatten to unwrap all Element instances.
93
- */
94
- const ancestorNodes = path.getAncestorNodes();
95
- const directAncestors = new Set(ancestorNodes.filter(isElement));
96
- const ancestorsLineage = new AncestorLineage(...this.ancestors, directAncestors);
97
- return [ancestorsLineage, directAncestors];
112
+
113
+ /**
114
+ * Handles an error according to the continueOnError option.
115
+ *
116
+ * For new errors: wraps in UnresolvableReferenceError with structured context
117
+ * (type, uri, location, codeFrame, refFieldName, refFieldValue, trace).
118
+ * For errors already wrapped by a nested visitor: prepends the current hop to the trace.
119
+ *
120
+ * Inner/intermediate visitors always throw to let the trace accumulate.
121
+ * Only the entry document visitor respects continueOnError (callback/swallow/throw).
122
+ */
123
+ handleError(message, error, referencingElement, refFieldName, refFieldValue, visitorPath) {
124
+ const {
125
+ continueOnError
126
+ } = this.options.dereference;
127
+ const isEntryDocument = url.stripHash(this.reference.refSet?.rootRef?.uri ?? '') === this.reference.uri;
128
+ const uri = this.reference.uri;
129
+ const type = referencingElement.element;
130
+ const codeFrame = toYAML(referencingElement);
131
+
132
+ // find element location: tree search for entry documents, visitor path for external
133
+ let location;
134
+ traverse(this.reference.value.result, {
135
+ enter: p => {
136
+ if (p.node === referencingElement || this.refractCache.get(p.node) === referencingElement) {
137
+ location = p.formatPath();
138
+ p.stop();
139
+ }
140
+ }
141
+ });
142
+ location ??= visitorPath.formatPath();
143
+ const hop = {
144
+ uri,
145
+ type,
146
+ refFieldName,
147
+ refFieldValue,
148
+ location,
149
+ codeFrame
150
+ };
151
+
152
+ // enrich existing error from nested visitor or create new one
153
+ let unresolvedError;
154
+ if (error instanceof UnresolvableReferenceError) {
155
+ // prefix relative locations for entries belonging to the referenced document
156
+ const refBaseURI = this.toBaseURI(refFieldValue);
157
+ const fragment = URIFragmentIdentifier.fromURIReference(refFieldValue);
158
+ if (fragment) {
159
+ if (refBaseURI === error.uri && error.location) {
160
+ error.location = fragment + error.location;
161
+ }
162
+ for (const h of error.trace) {
163
+ if (h.uri === refBaseURI && h.location) h.location = fragment + h.location;
164
+ }
165
+ }
166
+ // @ts-ignore
167
+ error.trace = [hop, ...error.trace];
168
+ unresolvedError = error;
169
+ } else {
170
+ unresolvedError = new UnresolvableReferenceError(message, {
171
+ cause: error,
172
+ type,
173
+ uri,
174
+ location,
175
+ codeFrame,
176
+ refFieldName,
177
+ refFieldValue,
178
+ trace: []
179
+ });
180
+ }
181
+ if (!isEntryDocument || continueOnError === false) throw unresolvedError;
182
+ if (typeof continueOnError === 'function') continueOnError(unresolvedError);
98
183
  }
99
184
  async ReferenceElement(path) {
100
185
  const referencingElement = path.node;
@@ -104,7 +189,6 @@ class OpenAPI2DereferenceVisitor {
104
189
  path.skip();
105
190
  return;
106
191
  }
107
- const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
108
192
  const retrievalURI = this.toBaseURI(toValue(referencingElement.$ref));
109
193
  const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
110
194
  const isExternalReference = !isInternalReference;
@@ -121,118 +205,121 @@ class OpenAPI2DereferenceVisitor {
121
205
  path.skip();
122
206
  return;
123
207
  }
124
- const reference = await this.toReference(toValue(referencingElement.$ref));
125
208
  const $refBaseURI = url.resolve(retrievalURI, toValue(referencingElement.$ref));
126
- this.indirections.push(referencingElement);
127
- const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
209
+ try {
210
+ const reference = await this.toReference(toValue(referencingElement.$ref));
211
+ this.indirections.push(referencingElement);
212
+ const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
128
213
 
129
- // possibly non-semantic fragment
130
- let referencedElement = evaluate(reference.value.result, jsonPointer);
131
- referencedElement.id = identityManager.identify(referencedElement);
214
+ // possibly non-semantic fragment
215
+ let referencedElement = evaluate(reference.value.result, jsonPointer);
132
216
 
133
- /**
134
- * Applying semantics to a referenced element if semantics are missing.
135
- */
136
- if (isPrimitiveElement(referencedElement)) {
217
+ // applying semantics to a fragment
137
218
  const referencedElementType = referencingElement.meta.get('referenced-element');
138
- const cacheKey = `${referencedElementType}-${identityManager.identify(referencedElement)}`;
139
- if (this.refractCache.has(cacheKey)) {
140
- referencedElement = this.refractCache.get(cacheKey);
141
- } else if (isReferenceLikeElement(referencedElement)) {
142
- // handling indirect references
143
- referencedElement = refractReference(referencedElement);
144
- referencedElement.meta.set('referenced-element', referencedElementType);
145
- this.refractCache.set(cacheKey, referencedElement);
146
- } else {
147
- // handling direct references
148
- referencedElement = refract(referencedElement, {
149
- element: referencedElementType
219
+ if (referencedElement.element !== referencedElementType && !isReferenceElement(referencedElement)) {
220
+ if (this.refractCache.has(referencedElement)) {
221
+ referencedElement = this.refractCache.get(referencedElement);
222
+ } else if (isReferenceLikeElement(referencedElement)) {
223
+ // handling generic indirect references
224
+ const sourceElement = referencedElement;
225
+ referencedElement = refractReference(referencedElement);
226
+ referencedElement.meta.set('referenced-element', referencedElementType);
227
+ this.refractCache.set(sourceElement, referencedElement);
228
+ } else {
229
+ // handling direct references
230
+ const sourceElement = referencedElement;
231
+ referencedElement = refract(referencedElement, {
232
+ element: referencedElementType
233
+ });
234
+ this.refractCache.set(sourceElement, referencedElement);
235
+ }
236
+ }
237
+
238
+ // detect direct or indirect reference
239
+ if (referencingElement === referencedElement) {
240
+ throw new ApiDOMStructuredError('Recursive Reference Object detected', {
241
+ $ref: toValue(referencingElement.$ref)
150
242
  });
151
- this.refractCache.set(cacheKey, referencedElement);
152
243
  }
153
- }
154
244
 
155
- // detect direct or circular reference
156
- if (referencingElement === referencedElement) {
157
- throw new ApiDOMError('Recursive Reference Object detected');
158
- }
245
+ // detect maximum depth of dereferencing
246
+ if (this.indirections.length > this.options.dereference.maxDepth) {
247
+ throw new MaximumDereferenceDepthError(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
248
+ maxDepth: this.options.dereference.maxDepth,
249
+ uri: this.reference.uri
250
+ });
251
+ }
159
252
 
160
- // detect maximum depth of dereferencing
161
- if (this.indirections.length > this.options.dereference.maxDepth) {
162
- throw new MaximumDereferenceDepthError(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`);
163
- }
253
+ // detect cross-boundary cycle
254
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
255
+ if (ancestorsLineage.includes(referencedElement)) {
256
+ reference.refSet.circular = true;
257
+ if (this.options.dereference.circular === 'error') {
258
+ throw new ApiDOMStructuredError('Circular reference detected', {
259
+ $ref: toValue(referencingElement.$ref)
260
+ });
261
+ } else if (this.options.dereference.circular === 'replace') {
262
+ const refElement = new RefElement($refBaseURI, {
263
+ type: referencingElement.element,
264
+ uri: reference.uri,
265
+ $ref: toValue(referencingElement.$ref)
266
+ });
267
+ const replacer = this.options.dereference.strategyOpts['openapi-2']?.circularReplacer ?? this.options.dereference.circularReplacer;
268
+ const replacement = replacer(refElement);
269
+ this.indirections.pop();
270
+ path.replaceWith(replacement);
271
+ return;
272
+ }
273
+ }
164
274
 
165
- // detect second deep dive into the same fragment and avoid it
166
- if (ancestorsLineage.includes(referencedElement)) {
167
- reference.refSet.circular = true;
168
- if (this.options.dereference.circular === 'error') {
169
- throw new ApiDOMError('Circular reference detected');
170
- } else if (this.options.dereference.circular === 'replace') {
171
- const refElement = new RefElement(referencedElement.id, {
172
- type: 'reference',
173
- uri: reference.uri,
174
- $ref: toValue(referencingElement.$ref)
275
+ /**
276
+ * Dive deep into the fragment.
277
+ *
278
+ * Cases to consider:
279
+ * 1. We're crossing document boundary
280
+ * 2. Fragment is from non-entry document
281
+ * 3. Fragment is a Reference Object. We need to follow it to get the eventual value
282
+ * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
283
+ */
284
+ const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
285
+ const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
286
+ if ((isExternalReference || isNonEntryDocument || isReferenceElement(referencedElement) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
287
+ // append referencing reference to ancestors lineage
288
+ directAncestors.add(referencingElement);
289
+ const visitor = new OpenAPI2DereferenceVisitor({
290
+ reference,
291
+ indirections: [...this.indirections],
292
+ options: this.options,
293
+ refractCache: this.refractCache,
294
+ ancestors: ancestorsLineage
295
+ });
296
+ referencedElement = await traverseAsync(referencedElement, visitor, {
297
+ mutable: true
175
298
  });
176
- const replacer = this.options.dereference.strategyOpts['openapi-2']?.circularReplacer ?? this.options.dereference.circularReplacer;
177
- const replacement = replacer(refElement);
178
- this.indirections.pop();
179
- path.replaceWith(replacement);
180
- return;
299
+ directAncestors.delete(referencingElement);
181
300
  }
182
- }
301
+ this.indirections.pop();
183
302
 
184
- /**
185
- * Dive deep into the fragment.
186
- *
187
- * Cases to consider:
188
- * 1. We're crossing document boundary
189
- * 2. Fragment is from non-entry document
190
- * 3. Fragment is a Reference Object. We need to follow it to get the eventual value
191
- * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
192
- */
193
- const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
194
- const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
195
- if ((isExternalReference || isNonEntryDocument || isReferenceElement(referencedElement) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
196
- // append referencing reference to ancestors lineage
197
- directAncestors.add(referencingElement);
198
- const visitor = new OpenAPI2DereferenceVisitor({
199
- reference,
200
- namespace: this.namespace,
201
- indirections: [...this.indirections],
202
- options: this.options,
203
- refractCache: this.refractCache,
204
- ancestors: ancestorsLineage
205
- });
206
- referencedElement = await traverseAsync(referencedElement, visitor, {
207
- mutable: true
303
+ /**
304
+ * Creating a new version of referenced element to avoid modifying the original one.
305
+ */
306
+ const mergedElement = cloneShallow(referencedElement);
307
+ // annotate referenced element with info about original referencing element
308
+ mergedElement.meta.set('ref-fields', {
309
+ $ref: toValue(referencingElement.$ref)
208
310
  });
209
-
210
- // remove referencing reference from ancestors lineage
211
- directAncestors.delete(referencingElement);
311
+ // annotate fragment with info about origin
312
+ mergedElement.meta.set('ref-origin', reference.uri);
313
+ mergedElement.meta.set('ref-type', referencingElement.element);
314
+
315
+ /**
316
+ * Transclude referencing element with merged referenced element.
317
+ */
318
+ path.replaceWith(mergedElement);
319
+ } catch (error) {
320
+ const $ref = toValue(referencingElement.$ref);
321
+ this.handleError(`Error while dereferencing Reference Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
212
322
  }
213
- this.indirections.pop();
214
-
215
- /**
216
- * Creating a new version of referenced element to avoid modifying the original one.
217
- */
218
- const mergedElement = cloneShallow(referencedElement);
219
- // assign unique id to merged element
220
- mergedElement.meta.set('id', identityManager.generateId());
221
- // annotate referenced element with info about original referencing element
222
- mergedElement.meta.set('ref-fields', {
223
- // @ts-ignore
224
- $ref: toValue(referencingElement.$ref)
225
- });
226
- // annotate fragment with info about origin
227
- mergedElement.meta.set('ref-origin', reference.uri);
228
- // annotate fragment with info about referencing element
229
- mergedElement.meta.set('ref-referencing-element-id', identityManager.identify(referencingElement));
230
-
231
- /**
232
- * Transclude referencing element with merged referenced element.
233
- */
234
- path.replaceWith(mergedElement);
235
- return;
236
323
  }
237
324
  async PathItemElement(path) {
238
325
  const referencingElement = path.node;
@@ -247,7 +334,6 @@ class OpenAPI2DereferenceVisitor {
247
334
  path.skip();
248
335
  return;
249
336
  }
250
- const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
251
337
  const retrievalURI = this.toBaseURI(toValue(referencingElement.$ref));
252
338
  const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
253
339
  const isExternalReference = !isInternalReference;
@@ -262,116 +348,124 @@ class OpenAPI2DereferenceVisitor {
262
348
  // skip traversing this Path Item element but traverse all it's child elements
263
349
  return;
264
350
  }
265
- const reference = await this.toReference(toValue(referencingElement.$ref));
266
351
  const $refBaseURI = url.resolve(retrievalURI, toValue(referencingElement.$ref));
267
- this.indirections.push(referencingElement);
268
- const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
269
-
270
- // possibly non-semantic referenced element
271
- let referencedElement = evaluate(reference.value.result, jsonPointer);
272
- referencedElement.id = identityManager.identify(referencedElement);
273
-
274
- /**
275
- * Applying semantics to a referenced element if semantics are missing.
276
- */
277
- if (isPrimitiveElement(referencedElement)) {
278
- const cacheKey = `pathItem-${identityManager.identify(referencedElement)}`;
279
- if (this.refractCache.has(cacheKey)) {
280
- referencedElement = this.refractCache.get(cacheKey);
281
- } else {
282
- referencedElement = refractPathItem(referencedElement);
283
- this.refractCache.set(cacheKey, referencedElement);
352
+ try {
353
+ const reference = await this.toReference(toValue(referencingElement.$ref));
354
+ this.indirections.push(referencingElement);
355
+ const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
356
+
357
+ // possibly non-semantic referenced element
358
+ let referencedElement = evaluate(reference.value.result, jsonPointer);
359
+
360
+ // applying semantics to a referenced element
361
+ if (!isPathItemElement(referencedElement)) {
362
+ if (this.refractCache.has(referencedElement)) {
363
+ referencedElement = this.refractCache.get(referencedElement);
364
+ } else {
365
+ const sourceElement = referencedElement;
366
+ referencedElement = refractPathItem(referencedElement);
367
+ this.refractCache.set(sourceElement, referencedElement);
368
+ }
284
369
  }
285
- }
286
-
287
- // detect direct or indirect reference
288
- if (referencingElement === referencedElement) {
289
- throw new ApiDOMError('Recursive Path Item Object reference detected');
290
- }
291
-
292
- // detect maximum depth of dereferencing
293
- if (this.indirections.length > this.options.dereference.maxDepth) {
294
- throw new MaximumDereferenceDepthError(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`);
295
- }
296
370
 
297
- // detect second deep dive into the same fragment and avoid it
298
- if (ancestorsLineage.includes(referencedElement)) {
299
- reference.refSet.circular = true;
300
- if (this.options.dereference.circular === 'error') {
301
- throw new ApiDOMError('Circular reference detected');
302
- } else if (this.options.dereference.circular === 'replace') {
303
- const refElement = new RefElement(referencedElement.id, {
304
- type: 'path-item',
305
- uri: reference.uri,
371
+ // detect direct or indirect reference
372
+ if (referencingElement === referencedElement) {
373
+ throw new ApiDOMStructuredError('Recursive Path Item Object reference detected', {
306
374
  $ref: toValue(referencingElement.$ref)
307
375
  });
308
- const replacer = this.options.dereference.strategyOpts['openapi-2']?.circularReplacer ?? this.options.dereference.circularReplacer;
309
- const replacement = replacer(refElement);
310
- this.indirections.pop();
311
- path.replaceWith(replacement);
312
- return;
313
376
  }
314
- }
315
377
 
316
- /**
317
- * Dive deep into the fragment.
318
- *
319
- * Cases to consider:
320
- * 1. We're crossing document boundary
321
- * 2. Fragment is from non-entry document
322
- * 3. Fragment is a Path Item Object with $ref field. We need to follow it to get the eventual value
323
- * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
324
- */
325
- const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
326
- const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
327
- if ((isExternalReference || isNonEntryDocument || isPathItemElement(referencedElement) && isStringElement(referencedElement.$ref) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
328
- // append referencing reference to ancestors lineage
329
- directAncestors.add(referencingElement);
330
- const visitor = new OpenAPI2DereferenceVisitor({
331
- reference,
332
- namespace: this.namespace,
333
- indirections: [...this.indirections],
334
- options: this.options,
335
- refractCache: this.refractCache,
336
- ancestors: ancestorsLineage
337
- });
338
- referencedElement = await traverseAsync(referencedElement, visitor, {
339
- mutable: true
340
- });
378
+ // detect maximum depth of dereferencing
379
+ if (this.indirections.length > this.options.dereference.maxDepth) {
380
+ throw new MaximumDereferenceDepthError(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
381
+ maxDepth: this.options.dereference.maxDepth,
382
+ uri: this.reference.uri
383
+ });
384
+ }
341
385
 
342
- // remove referencing reference from ancestors lineage
343
- directAncestors.delete(referencingElement);
344
- }
345
- this.indirections.pop();
386
+ // detect cross-boundary cycle
387
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
388
+ if (ancestorsLineage.includes(referencedElement)) {
389
+ reference.refSet.circular = true;
390
+ if (this.options.dereference.circular === 'error') {
391
+ throw new ApiDOMStructuredError('Circular reference detected', {
392
+ $ref: toValue(referencingElement.$ref)
393
+ });
394
+ } else if (this.options.dereference.circular === 'replace') {
395
+ const refElement = new RefElement($refBaseURI, {
396
+ type: referencingElement.element,
397
+ uri: reference.uri,
398
+ $ref: toValue(referencingElement.$ref)
399
+ });
400
+ const replacer = this.options.dereference.strategyOpts['openapi-2']?.circularReplacer ?? this.options.dereference.circularReplacer;
401
+ const replacement = replacer(refElement);
402
+ this.indirections.pop();
403
+ path.replaceWith(replacement);
404
+ return;
405
+ }
406
+ }
346
407
 
347
- // merge fields from referenced Path Item with referencing one
348
- if (isPathItemElement(referencedElement)) {
349
- const mergedElement = cloneShallow(referencedElement);
350
- // assign unique id to merged element
351
- mergedElement.meta.set('id', identityManager.generateId());
352
- // existing keywords from referencing PathItemElement overrides ones from referenced element
353
- referencingElement.forEach((value, keyElement, item) => {
354
- mergedElement.remove(toValue(keyElement));
355
- mergedElement.content.push(item);
356
- });
357
- mergedElement.remove('$ref');
408
+ /**
409
+ * Dive deep into the fragment.
410
+ *
411
+ * Cases to consider:
412
+ * 1. We're crossing document boundary
413
+ * 2. Fragment is from non-entry document
414
+ * 3. Fragment is a Path Item Object with $ref field. We need to follow it to get the eventual value
415
+ * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
416
+ */
417
+ const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
418
+ const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
419
+ if ((isExternalReference || isNonEntryDocument || isPathItemElement(referencedElement) && isStringElement(referencedElement.$ref) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
420
+ // append referencing reference to ancestors lineage
421
+ directAncestors.add(referencingElement);
422
+ const visitor = new OpenAPI2DereferenceVisitor({
423
+ reference,
424
+ indirections: [...this.indirections],
425
+ options: this.options,
426
+ refractCache: this.refractCache,
427
+ ancestors: ancestorsLineage
428
+ });
429
+ referencedElement = await traverseAsync(referencedElement, visitor, {
430
+ mutable: true
431
+ });
358
432
 
359
- // annotate referenced element with info about original referencing element
360
- mergedElement.meta.set('ref-fields', {
361
- $ref: toValue(referencingElement.$ref)
362
- });
363
- // annotate referenced element with info about origin
364
- mergedElement.meta.set('ref-origin', reference.uri);
365
- // annotate fragment with info about referencing element
366
- mergedElement.meta.set('ref-referencing-element-id', identityManager.identify(referencingElement));
367
- referencedElement = mergedElement;
368
- }
433
+ // remove referencing reference from ancestors lineage
434
+ directAncestors.delete(referencingElement);
435
+ }
436
+ this.indirections.pop();
437
+
438
+ /**
439
+ * Creating a new version of Path Item by merging fields from referenced Path Item with referencing one.
440
+ */
441
+ if (isPathItemElement(referencedElement)) {
442
+ const mergedElement = cloneShallow(referencedElement);
443
+ // existing keywords from referencing PathItemElement overrides ones from referenced element
444
+ referencingElement.forEach((value, keyElement, item) => {
445
+ mergedElement.remove(toValue(keyElement));
446
+ mergedElement.content.push(item);
447
+ });
448
+ mergedElement.remove('$ref');
449
+
450
+ // annotate referenced element with info about original referencing element
451
+ mergedElement.meta.set('ref-fields', {
452
+ $ref: toValue(referencingElement.$ref)
453
+ });
454
+ // annotate referenced element with info about origin and type
455
+ mergedElement.meta.set('ref-origin', reference.uri);
456
+ mergedElement.meta.set('ref-type', referencingElement.element);
457
+ referencedElement = mergedElement;
458
+ }
369
459
 
370
- /**
371
- * Transclude referencing element with merged referenced element.
372
- */
373
- path.replaceWith(referencedElement);
374
- return;
460
+ /**
461
+ * Transclude referencing element with merged referenced element.
462
+ */
463
+ path.replaceWith(referencedElement);
464
+ return;
465
+ } catch (error) {
466
+ const $ref = toValue(referencingElement.$ref);
467
+ this.handleError(`Error while dereferencing Path Item Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
468
+ }
375
469
  }
376
470
  async JSONReferenceElement(path) {
377
471
  const referencingElement = path.node;
@@ -381,7 +475,6 @@ class OpenAPI2DereferenceVisitor {
381
475
  path.skip();
382
476
  return;
383
477
  }
384
- const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
385
478
  const retrievalURI = this.toBaseURI(toValue(referencingElement.$ref));
386
479
  const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
387
480
  const isExternalReference = !isInternalReference;
@@ -398,118 +491,123 @@ class OpenAPI2DereferenceVisitor {
398
491
  path.skip();
399
492
  return;
400
493
  }
401
- const reference = await this.toReference(toValue(referencingElement.$ref));
402
494
  const $refBaseURI = url.resolve(retrievalURI, toValue(referencingElement.$ref));
403
- this.indirections.push(referencingElement);
404
- const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
495
+ try {
496
+ const reference = await this.toReference(toValue(referencingElement.$ref));
497
+ this.indirections.push(referencingElement);
498
+ const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
405
499
 
406
- // possibly non-semantic fragment
407
- let referencedElement = evaluate(reference.value.result, jsonPointer);
408
- referencedElement.id = identityManager.identify(referencedElement);
500
+ // possibly non-semantic fragment
501
+ let referencedElement = evaluate(reference.value.result, jsonPointer);
409
502
 
410
- /**
411
- * Applying semantics to a referenced element if semantics are missing.
412
- */
413
- if (isPrimitiveElement(referencedElement)) {
503
+ // applying semantics to a fragment
414
504
  const referencedElementType = referencingElement.meta.get('referenced-element');
415
- const cacheKey = `path-item-${identityManager.identify(referencedElement)}`;
416
- if (this.refractCache.has(cacheKey)) {
417
- referencedElement = this.refractCache.get(cacheKey);
418
- } else if (isJSONReferenceLikeElement(referencedElement)) {
419
- // handling indirect references
420
- referencedElement = refractReference(toValue(referencedElement));
421
- referencedElement.meta.set('referenced-element', referencedElementType);
422
- this.refractCache.set(cacheKey, referencedElement);
423
- } else {
424
- // handling direct references
425
- referencedElement = refract(toValue(referencedElement), {
426
- element: referencedElementType
505
+ if (referencedElement.element !== referencedElementType && !isJSONReferenceElement(referencedElement)) {
506
+ if (this.refractCache.has(referencedElement)) {
507
+ referencedElement = this.refractCache.get(referencedElement);
508
+ } else if (isJSONReferenceLikeElement(referencedElement)) {
509
+ // handling generic indirect references
510
+ const sourceElement = referencedElement;
511
+ referencedElement = refractJSONReference(referencedElement);
512
+ referencedElement.meta.set('referenced-element', referencedElementType);
513
+ this.refractCache.set(sourceElement, referencedElement);
514
+ } else {
515
+ // handling direct references
516
+ const sourceElement = referencedElement;
517
+ referencedElement = refract(referencedElement, {
518
+ element: referencedElementType
519
+ });
520
+ this.refractCache.set(sourceElement, referencedElement);
521
+ }
522
+ }
523
+
524
+ // detect direct or indirect reference
525
+ if (referencingElement === referencedElement) {
526
+ throw new ApiDOMStructuredError('Recursive JSON Reference Object detected', {
527
+ $ref: toValue(referencingElement.$ref)
427
528
  });
428
- this.refractCache.set(cacheKey, referencedElement);
429
529
  }
430
- }
431
530
 
432
- // detect direct or circular reference
433
- if (referencingElement === referencedElement) {
434
- throw new ApiDOMError('Recursive Reference Object detected');
435
- }
531
+ // detect maximum depth of dereferencing
532
+ if (this.indirections.length > this.options.dereference.maxDepth) {
533
+ throw new MaximumDereferenceDepthError(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
534
+ maxDepth: this.options.dereference.maxDepth,
535
+ uri: this.reference.uri
536
+ });
537
+ }
436
538
 
437
- // detect maximum depth of dereferencing
438
- if (this.indirections.length > this.options.dereference.maxDepth) {
439
- throw new MaximumDereferenceDepthError(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`);
440
- }
539
+ // detect cross-boundary cycle
540
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
541
+ if (ancestorsLineage.includes(referencedElement)) {
542
+ reference.refSet.circular = true;
543
+ if (this.options.dereference.circular === 'error') {
544
+ throw new ApiDOMStructuredError('Circular reference detected', {
545
+ $ref: toValue(referencingElement.$ref)
546
+ });
547
+ } else if (this.options.dereference.circular === 'replace') {
548
+ const refElement = new RefElement($refBaseURI, {
549
+ type: referencingElement.element,
550
+ uri: reference.uri,
551
+ $ref: toValue(referencingElement.$ref)
552
+ });
553
+ const replacer = this.options.dereference.strategyOpts['openapi-2']?.circularReplacer ?? this.options.dereference.circularReplacer;
554
+ const replacement = replacer(refElement);
555
+ this.indirections.pop();
556
+ path.replaceWith(replacement);
557
+ return;
558
+ }
559
+ }
441
560
 
442
- // detect second deep dive into the same fragment and avoid it
443
- if (ancestorsLineage.includes(referencedElement)) {
444
- reference.refSet.circular = true;
445
- if (this.options.dereference.circular === 'error') {
446
- throw new ApiDOMError('Circular reference detected');
447
- } else if (this.options.dereference.circular === 'replace') {
448
- const refElement = new RefElement(referencedElement.id, {
449
- type: 'json-reference',
450
- uri: reference.uri,
451
- $ref: toValue(referencingElement.$ref)
561
+ /**
562
+ * Dive deep into the fragment.
563
+ *
564
+ * Cases to consider:
565
+ * 1. We're crossing document boundary
566
+ 2. Fragment is from non-entry document
567
+ * 3. Fragment is a JSON Reference Object. We need to follow it to get the eventual value
568
+ * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
569
+ */
570
+ const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
571
+ const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
572
+ if ((isExternalReference || isNonEntryDocument || isJSONReferenceElement(referencedElement) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
573
+ // append referencing reference to ancestors lineage
574
+ directAncestors.add(referencingElement);
575
+ const visitor = new OpenAPI2DereferenceVisitor({
576
+ reference,
577
+ indirections: [...this.indirections],
578
+ options: this.options,
579
+ refractCache: this.refractCache,
580
+ ancestors: ancestorsLineage
452
581
  });
453
- const replacer = this.options.dereference.strategyOpts['openapi-2']?.circularReplacer ?? this.options.dereference.circularReplacer;
454
- const replacement = replacer(refElement);
455
- this.indirections.pop();
456
- path.replaceWith(replacement);
457
- return;
582
+ referencedElement = await traverseAsync(referencedElement, visitor, {
583
+ mutable: true
584
+ });
585
+
586
+ // remove referencing reference from ancestors lineage
587
+ directAncestors.delete(referencingElement);
458
588
  }
459
- }
589
+ this.indirections.pop();
460
590
 
461
- /**
462
- * Dive deep into the fragment.
463
- *
464
- * Cases to consider:
465
- * 1. We're crossing document boundary
466
- 2. Fragment is from non-entry document
467
- * 3. Fragment is a JSON Reference Object. We need to follow it to get the eventual value
468
- * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
469
- */
470
- const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
471
- const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
472
- if ((isExternalReference || isNonEntryDocument || isJSONReferenceElement(referencedElement) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
473
- // append referencing reference to ancestors lineage
474
- directAncestors.add(referencingElement);
475
- const visitor = new OpenAPI2DereferenceVisitor({
476
- reference,
477
- namespace: this.namespace,
478
- indirections: [...this.indirections],
479
- options: this.options,
480
- refractCache: this.refractCache,
481
- ancestors: ancestorsLineage
482
- });
483
- referencedElement = await traverseAsync(referencedElement, visitor, {
484
- mutable: true
591
+ /**
592
+ * Creating a new version of referenced element to avoid modifying the original one.
593
+ */
594
+ const mergedElement = cloneShallow(referencedElement);
595
+ // annotate referenced element with info about original referencing element
596
+ mergedElement.meta.set('ref-fields', {
597
+ $ref: toValue(referencingElement.$ref)
485
598
  });
486
-
487
- // remove referencing reference from ancestors lineage
488
- directAncestors.delete(referencingElement);
599
+ // annotate fragment with info about origin
600
+ mergedElement.meta.set('ref-origin', reference.uri);
601
+ mergedElement.meta.set('ref-type', referencingElement.element);
602
+
603
+ /**
604
+ * Transclude referencing element with merged referenced element.
605
+ */
606
+ path.replaceWith(mergedElement);
607
+ } catch (error) {
608
+ const $ref = toValue(referencingElement.$ref);
609
+ this.handleError(`Error while dereferencing JSON Reference Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
489
610
  }
490
- this.indirections.pop();
491
-
492
- /**
493
- * Creating a new version of referenced element to avoid modifying the original one.
494
- */
495
- const mergedElement = cloneShallow(referencedElement);
496
- // assign unique id to merged element
497
- mergedElement.meta.set('id', identityManager.generateId());
498
- // annotate referenced element with info about original referencing element
499
- mergedElement.meta.set('ref-fields', {
500
- // @ts-ignore
501
- $ref: toValue(referencingElement.$ref)
502
- });
503
- // annotate fragment with info about origin
504
- mergedElement.meta.set('ref-origin', reference.uri);
505
- // annotate fragment with info about referencing element
506
- mergedElement.meta.set('ref-referencing-element-id', identityManager.identify(referencingElement));
507
-
508
- /**
509
- * Transclude referencing element with merged referenced element.
510
- */
511
- path.replaceWith(mergedElement);
512
- return;
513
611
  }
514
612
  }
515
613
  export default OpenAPI2DereferenceVisitor;