@speclynx/apidom-reference 3.0.0 → 3.2.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 +16 -0
  2. package/README.md +97 -0
  3. package/dist/apidom-reference.browser.js +3862 -3241
  4. package/dist/apidom-reference.browser.min.js +1 -1
  5. package/package.json +48 -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 +289 -199
  13. package/src/dereference/strategies/arazzo-1/visitor.mjs +292 -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 +325 -229
  17. package/src/dereference/strategies/asyncapi-2/visitor.mjs +328 -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 +420 -318
  21. package/src/dereference/strategies/openapi-2/visitor.mjs +425 -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 +405 -286
  25. package/src/dereference/strategies/openapi-3-0/visitor.mjs +409 -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,122 @@ 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
+ const indirectionsSize = this.indirections.length;
210
+ try {
211
+ const reference = await this.toReference(toValue(referencingElement.$ref));
212
+ this.indirections.push(referencingElement);
213
+ const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
128
214
 
129
- // possibly non-semantic fragment
130
- let referencedElement = evaluate(reference.value.result, jsonPointer);
131
- referencedElement.id = identityManager.identify(referencedElement);
215
+ // possibly non-semantic fragment
216
+ let referencedElement = evaluate(reference.value.result, jsonPointer);
132
217
 
133
- /**
134
- * Applying semantics to a referenced element if semantics are missing.
135
- */
136
- if (isPrimitiveElement(referencedElement)) {
218
+ // applying semantics to a fragment
137
219
  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
220
+ if (referencedElement.element !== referencedElementType && !isReferenceElement(referencedElement)) {
221
+ if (this.refractCache.has(referencedElement)) {
222
+ referencedElement = this.refractCache.get(referencedElement);
223
+ } else if (isReferenceLikeElement(referencedElement)) {
224
+ // handling generic indirect references
225
+ const sourceElement = referencedElement;
226
+ referencedElement = refractReference(referencedElement);
227
+ referencedElement.meta.set('referenced-element', referencedElementType);
228
+ this.refractCache.set(sourceElement, referencedElement);
229
+ } else {
230
+ // handling direct references
231
+ const sourceElement = referencedElement;
232
+ referencedElement = refract(referencedElement, {
233
+ element: referencedElementType
234
+ });
235
+ this.refractCache.set(sourceElement, referencedElement);
236
+ }
237
+ }
238
+
239
+ // detect direct or indirect reference
240
+ if (referencingElement === referencedElement) {
241
+ throw new ApiDOMStructuredError('Recursive Reference Object detected', {
242
+ $ref: toValue(referencingElement.$ref)
150
243
  });
151
- this.refractCache.set(cacheKey, referencedElement);
152
244
  }
153
- }
154
245
 
155
- // detect direct or circular reference
156
- if (referencingElement === referencedElement) {
157
- throw new ApiDOMError('Recursive Reference Object detected');
158
- }
246
+ // detect maximum depth of dereferencing
247
+ if (this.indirections.length > this.options.dereference.maxDepth) {
248
+ throw new MaximumDereferenceDepthError(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
249
+ maxDepth: this.options.dereference.maxDepth,
250
+ uri: this.reference.uri
251
+ });
252
+ }
159
253
 
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
- }
254
+ // detect cross-boundary cycle
255
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
256
+ if (ancestorsLineage.includes(referencedElement)) {
257
+ reference.refSet.circular = true;
258
+ if (this.options.dereference.circular === 'error') {
259
+ throw new ApiDOMStructuredError('Circular reference detected', {
260
+ $ref: toValue(referencingElement.$ref)
261
+ });
262
+ } else if (this.options.dereference.circular === 'replace') {
263
+ const refElement = new RefElement($refBaseURI, {
264
+ type: referencingElement.element,
265
+ uri: reference.uri,
266
+ $ref: toValue(referencingElement.$ref)
267
+ });
268
+ const replacer = this.options.dereference.strategyOpts['openapi-2']?.circularReplacer ?? this.options.dereference.circularReplacer;
269
+ const replacement = replacer(refElement);
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
- }
183
301
 
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
302
+ /**
303
+ * Creating a new version of referenced element to avoid modifying the original one.
304
+ */
305
+ const mergedElement = cloneShallow(referencedElement);
306
+ // annotate referenced element with info about original referencing element
307
+ mergedElement.meta.set('ref-fields', {
308
+ $ref: toValue(referencingElement.$ref)
208
309
  });
209
-
210
- // remove referencing reference from ancestors lineage
211
- directAncestors.delete(referencingElement);
310
+ // annotate fragment with info about origin
311
+ mergedElement.meta.set('ref-origin', reference.uri);
312
+ mergedElement.meta.set('ref-type', referencingElement.element);
313
+
314
+ /**
315
+ * Transclude referencing element with merged referenced element.
316
+ */
317
+ path.replaceWith(mergedElement);
318
+ } catch (error) {
319
+ const $ref = toValue(referencingElement.$ref);
320
+ this.handleError(`Error while dereferencing Reference Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
321
+ } finally {
322
+ if (this.indirections.length > indirectionsSize) this.indirections.pop();
212
323
  }
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
324
  }
237
325
  async PathItemElement(path) {
238
326
  const referencingElement = path.node;
@@ -247,7 +335,6 @@ class OpenAPI2DereferenceVisitor {
247
335
  path.skip();
248
336
  return;
249
337
  }
250
- const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
251
338
  const retrievalURI = this.toBaseURI(toValue(referencingElement.$ref));
252
339
  const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
253
340
  const isExternalReference = !isInternalReference;
@@ -262,116 +349,125 @@ class OpenAPI2DereferenceVisitor {
262
349
  // skip traversing this Path Item element but traverse all it's child elements
263
350
  return;
264
351
  }
265
- const reference = await this.toReference(toValue(referencingElement.$ref));
266
352
  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);
353
+ const indirectionsSize = this.indirections.length;
354
+ try {
355
+ const reference = await this.toReference(toValue(referencingElement.$ref));
356
+ this.indirections.push(referencingElement);
357
+ const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
358
+
359
+ // possibly non-semantic referenced element
360
+ let referencedElement = evaluate(reference.value.result, jsonPointer);
361
+
362
+ // applying semantics to a referenced element
363
+ if (!isPathItemElement(referencedElement)) {
364
+ if (this.refractCache.has(referencedElement)) {
365
+ referencedElement = this.refractCache.get(referencedElement);
366
+ } else {
367
+ const sourceElement = referencedElement;
368
+ referencedElement = refractPathItem(referencedElement);
369
+ this.refractCache.set(sourceElement, referencedElement);
370
+ }
284
371
  }
285
- }
286
-
287
- // detect direct or indirect reference
288
- if (referencingElement === referencedElement) {
289
- throw new ApiDOMError('Recursive Path Item Object reference detected');
290
- }
291
372
 
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
-
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,
373
+ // detect direct or indirect reference
374
+ if (referencingElement === referencedElement) {
375
+ throw new ApiDOMStructuredError('Recursive Path Item Object reference detected', {
306
376
  $ref: toValue(referencingElement.$ref)
307
377
  });
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
378
  }
314
- }
315
379
 
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
- });
380
+ // detect maximum depth of dereferencing
381
+ if (this.indirections.length > this.options.dereference.maxDepth) {
382
+ throw new MaximumDereferenceDepthError(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
383
+ maxDepth: this.options.dereference.maxDepth,
384
+ uri: this.reference.uri
385
+ });
386
+ }
341
387
 
342
- // remove referencing reference from ancestors lineage
343
- directAncestors.delete(referencingElement);
344
- }
345
- this.indirections.pop();
388
+ // detect cross-boundary cycle
389
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
390
+ if (ancestorsLineage.includes(referencedElement)) {
391
+ reference.refSet.circular = true;
392
+ if (this.options.dereference.circular === 'error') {
393
+ throw new ApiDOMStructuredError('Circular reference detected', {
394
+ $ref: toValue(referencingElement.$ref)
395
+ });
396
+ } else if (this.options.dereference.circular === 'replace') {
397
+ const refElement = new RefElement($refBaseURI, {
398
+ type: referencingElement.element,
399
+ uri: reference.uri,
400
+ $ref: toValue(referencingElement.$ref)
401
+ });
402
+ const replacer = this.options.dereference.strategyOpts['openapi-2']?.circularReplacer ?? this.options.dereference.circularReplacer;
403
+ const replacement = replacer(refElement);
404
+ path.replaceWith(replacement);
405
+ return;
406
+ }
407
+ }
346
408
 
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');
409
+ /**
410
+ * Dive deep into the fragment.
411
+ *
412
+ * Cases to consider:
413
+ * 1. We're crossing document boundary
414
+ * 2. Fragment is from non-entry document
415
+ * 3. Fragment is a Path Item Object with $ref field. We need to follow it to get the eventual value
416
+ * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
417
+ */
418
+ const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
419
+ const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
420
+ if ((isExternalReference || isNonEntryDocument || isPathItemElement(referencedElement) && isStringElement(referencedElement.$ref) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
421
+ // append referencing reference to ancestors lineage
422
+ directAncestors.add(referencingElement);
423
+ const visitor = new OpenAPI2DereferenceVisitor({
424
+ reference,
425
+ indirections: [...this.indirections],
426
+ options: this.options,
427
+ refractCache: this.refractCache,
428
+ ancestors: ancestorsLineage
429
+ });
430
+ referencedElement = await traverseAsync(referencedElement, visitor, {
431
+ mutable: true
432
+ });
358
433
 
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
- }
434
+ // remove referencing reference from ancestors lineage
435
+ directAncestors.delete(referencingElement);
436
+ }
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
+ } finally {
469
+ if (this.indirections.length > indirectionsSize) this.indirections.pop();
470
+ }
375
471
  }
376
472
  async JSONReferenceElement(path) {
377
473
  const referencingElement = path.node;
@@ -381,7 +477,6 @@ class OpenAPI2DereferenceVisitor {
381
477
  path.skip();
382
478
  return;
383
479
  }
384
- const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
385
480
  const retrievalURI = this.toBaseURI(toValue(referencingElement.$ref));
386
481
  const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
387
482
  const isExternalReference = !isInternalReference;
@@ -398,118 +493,124 @@ class OpenAPI2DereferenceVisitor {
398
493
  path.skip();
399
494
  return;
400
495
  }
401
- const reference = await this.toReference(toValue(referencingElement.$ref));
402
496
  const $refBaseURI = url.resolve(retrievalURI, toValue(referencingElement.$ref));
403
- this.indirections.push(referencingElement);
404
- const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
497
+ const indirectionsSize = this.indirections.length;
498
+ try {
499
+ const reference = await this.toReference(toValue(referencingElement.$ref));
500
+ this.indirections.push(referencingElement);
501
+ const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
405
502
 
406
- // possibly non-semantic fragment
407
- let referencedElement = evaluate(reference.value.result, jsonPointer);
408
- referencedElement.id = identityManager.identify(referencedElement);
503
+ // possibly non-semantic fragment
504
+ let referencedElement = evaluate(reference.value.result, jsonPointer);
409
505
 
410
- /**
411
- * Applying semantics to a referenced element if semantics are missing.
412
- */
413
- if (isPrimitiveElement(referencedElement)) {
506
+ // applying semantics to a fragment
414
507
  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
508
+ if (referencedElement.element !== referencedElementType && !isJSONReferenceElement(referencedElement)) {
509
+ if (this.refractCache.has(referencedElement)) {
510
+ referencedElement = this.refractCache.get(referencedElement);
511
+ } else if (isJSONReferenceLikeElement(referencedElement)) {
512
+ // handling generic indirect references
513
+ const sourceElement = referencedElement;
514
+ referencedElement = refractJSONReference(referencedElement);
515
+ referencedElement.meta.set('referenced-element', referencedElementType);
516
+ this.refractCache.set(sourceElement, referencedElement);
517
+ } else {
518
+ // handling direct references
519
+ const sourceElement = referencedElement;
520
+ referencedElement = refract(referencedElement, {
521
+ element: referencedElementType
522
+ });
523
+ this.refractCache.set(sourceElement, referencedElement);
524
+ }
525
+ }
526
+
527
+ // detect direct or indirect reference
528
+ if (referencingElement === referencedElement) {
529
+ throw new ApiDOMStructuredError('Recursive JSON Reference Object detected', {
530
+ $ref: toValue(referencingElement.$ref)
427
531
  });
428
- this.refractCache.set(cacheKey, referencedElement);
429
532
  }
430
- }
431
533
 
432
- // detect direct or circular reference
433
- if (referencingElement === referencedElement) {
434
- throw new ApiDOMError('Recursive Reference Object detected');
435
- }
534
+ // detect maximum depth of dereferencing
535
+ if (this.indirections.length > this.options.dereference.maxDepth) {
536
+ throw new MaximumDereferenceDepthError(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
537
+ maxDepth: this.options.dereference.maxDepth,
538
+ uri: this.reference.uri
539
+ });
540
+ }
436
541
 
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
- }
542
+ // detect cross-boundary cycle
543
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
544
+ if (ancestorsLineage.includes(referencedElement)) {
545
+ reference.refSet.circular = true;
546
+ if (this.options.dereference.circular === 'error') {
547
+ throw new ApiDOMStructuredError('Circular reference detected', {
548
+ $ref: toValue(referencingElement.$ref)
549
+ });
550
+ } else if (this.options.dereference.circular === 'replace') {
551
+ const refElement = new RefElement($refBaseURI, {
552
+ type: referencingElement.element,
553
+ uri: reference.uri,
554
+ $ref: toValue(referencingElement.$ref)
555
+ });
556
+ const replacer = this.options.dereference.strategyOpts['openapi-2']?.circularReplacer ?? this.options.dereference.circularReplacer;
557
+ const replacement = replacer(refElement);
558
+ path.replaceWith(replacement);
559
+ return;
560
+ }
561
+ }
441
562
 
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)
563
+ /**
564
+ * Dive deep into the fragment.
565
+ *
566
+ * Cases to consider:
567
+ * 1. We're crossing document boundary
568
+ 2. Fragment is from non-entry document
569
+ * 3. Fragment is a JSON Reference Object. We need to follow it to get the eventual value
570
+ * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
571
+ */
572
+ const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
573
+ const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
574
+ if ((isExternalReference || isNonEntryDocument || isJSONReferenceElement(referencedElement) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
575
+ // append referencing reference to ancestors lineage
576
+ directAncestors.add(referencingElement);
577
+ const visitor = new OpenAPI2DereferenceVisitor({
578
+ reference,
579
+ indirections: [...this.indirections],
580
+ options: this.options,
581
+ refractCache: this.refractCache,
582
+ ancestors: ancestorsLineage
452
583
  });
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;
584
+ referencedElement = await traverseAsync(referencedElement, visitor, {
585
+ mutable: true
586
+ });
587
+
588
+ // remove referencing reference from ancestors lineage
589
+ directAncestors.delete(referencingElement);
458
590
  }
459
- }
460
591
 
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
592
+ /**
593
+ * Creating a new version of referenced element to avoid modifying the original one.
594
+ */
595
+ const mergedElement = cloneShallow(referencedElement);
596
+ // annotate referenced element with info about original referencing element
597
+ mergedElement.meta.set('ref-fields', {
598
+ $ref: toValue(referencingElement.$ref)
485
599
  });
486
-
487
- // remove referencing reference from ancestors lineage
488
- directAncestors.delete(referencingElement);
600
+ // annotate fragment with info about origin
601
+ mergedElement.meta.set('ref-origin', reference.uri);
602
+ mergedElement.meta.set('ref-type', referencingElement.element);
603
+
604
+ /**
605
+ * Transclude referencing element with merged referenced element.
606
+ */
607
+ path.replaceWith(mergedElement);
608
+ } catch (error) {
609
+ const $ref = toValue(referencingElement.$ref);
610
+ this.handleError(`Error while dereferencing JSON Reference Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
611
+ } finally {
612
+ if (this.indirections.length > indirectionsSize) this.indirections.pop();
489
613
  }
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
614
  }
514
615
  }
515
616
  export default OpenAPI2DereferenceVisitor;