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