@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
@@ -16,16 +16,14 @@ var _$anchor = require("./selectors/$anchor.cjs");
16
16
  var _uri = require("./selectors/uri.cjs");
17
17
  var _MaximumDereferenceDepthError = _interopRequireDefault(require("../../../errors/MaximumDereferenceDepthError.cjs"));
18
18
  var _MaximumResolveDepthError = _interopRequireDefault(require("../../../errors/MaximumResolveDepthError.cjs"));
19
+ var _UnresolvableReferenceError = _interopRequireDefault(require("../../../errors/UnresolvableReferenceError.cjs"));
20
+ var _EvaluationJsonSchemaUriError = _interopRequireDefault(require("../../../errors/EvaluationJsonSchemaUriError.cjs"));
19
21
  var url = _interopRequireWildcard(require("../../../util/url.cjs"));
20
22
  var _index = _interopRequireDefault(require("../../../parse/index.cjs"));
21
23
  var _Reference = _interopRequireDefault(require("../../../Reference.cjs"));
22
24
  var _File = _interopRequireDefault(require("../../../File.cjs"));
23
25
  var _util = require("./util.cjs");
24
26
  var _util2 = require("../../util.cjs");
25
- var _EvaluationJsonSchemaUriError = _interopRequireDefault(require("../../../errors/EvaluationJsonSchemaUriError.cjs"));
26
- // initialize element identity manager
27
- const identityManager = new _apidomCore.IdentityManager();
28
-
29
27
  /**
30
28
  * @public
31
29
  */
@@ -35,25 +33,34 @@ const identityManager = new _apidomCore.IdentityManager();
35
33
  */
36
34
  class OpenAPI3_1DereferenceVisitor {
37
35
  indirections;
38
- namespace;
39
36
  reference;
40
37
  options;
41
- ancestors;
42
38
  refractCache;
39
+
40
+ /**
41
+ * Tracks element ancestors across dive-deep traversal boundaries.
42
+ * Used for cycle detection: if a referenced element is found in
43
+ * the ancestor lineage, a circular reference is detected.
44
+ */
45
+ ancestors;
43
46
  constructor({
44
47
  reference,
45
- namespace,
46
48
  options,
47
49
  indirections = [],
48
- ancestors = new _util2.AncestorLineage(),
49
- refractCache = new Map()
50
+ refractCache = new WeakMap(),
51
+ ancestors = new _util2.AncestorLineage()
50
52
  }) {
51
53
  this.indirections = indirections;
52
- this.namespace = namespace;
53
54
  this.reference = reference;
54
55
  this.options = options;
55
- this.ancestors = new _util2.AncestorLineage(...ancestors);
56
56
  this.refractCache = refractCache;
57
+ this.ancestors = new _util2.AncestorLineage(...ancestors);
58
+ }
59
+ toAncestorLineage(path) {
60
+ const ancestorNodes = path.getAncestorNodes();
61
+ const directAncestors = new Set(ancestorNodes.filter(_apidomDatamodel.isElement));
62
+ const ancestorsLineage = new _util2.AncestorLineage(...this.ancestors, directAncestors);
63
+ return [ancestorsLineage, directAncestors];
57
64
  }
58
65
  toBaseURI(uri) {
59
66
  return url.resolve(this.reference.uri, url.sanitize(url.stripHash(uri)));
@@ -61,7 +68,10 @@ class OpenAPI3_1DereferenceVisitor {
61
68
  async toReference(uri) {
62
69
  // detect maximum depth of resolution
63
70
  if (this.reference.depth >= this.options.resolve.maxDepth) {
64
- throw new _MaximumResolveDepthError.default(`Maximum resolution depth of ${this.options.resolve.maxDepth} has been exceeded by file "${this.reference.uri}"`);
71
+ throw new _MaximumResolveDepthError.default(`Maximum resolution depth of ${this.options.resolve.maxDepth} has been exceeded by file "${this.reference.uri}"`, {
72
+ maxDepth: this.options.resolve.maxDepth,
73
+ uri: this.reference.uri
74
+ });
65
75
  }
66
76
  const baseURI = this.toBaseURI(uri);
67
77
  const {
@@ -81,14 +91,28 @@ class OpenAPI3_1DereferenceVisitor {
81
91
  });
82
92
 
83
93
  // register new mutable reference with a refSet
94
+ //
95
+ // NOTE(known limitation): the mutable reference is mutated in place during traversal
96
+ // (via `{ mutable: true }`). When an external document evaluates a JSON pointer back
97
+ // into this document, it may receive an already-resolved element instead of the original
98
+ // $ref. That resolved element was produced using the entry document's resolution context
99
+ // (ancestors, indirections), which may differ from the external document's context.
100
+ // This can affect cycle detection in rare cross-document circular reference patterns.
101
+ //
102
+ // Remediation: evaluate JSON pointers against the immutable (original) parse tree
103
+ // instead of the mutable working copy. The `immutable://` reference below preserves
104
+ // the original tree and could be used for pointer evaluation, ensuring every resolution
105
+ // context always sees raw, unresolved elements and processes them with its own
106
+ // ancestors/indirections. The trade-off is that elements referenced by multiple
107
+ // documents would be resolved once per context instead of being reused.
84
108
  const mutableReference = new _Reference.default({
85
109
  uri: baseURI,
86
- value: (0, _apidomDatamodel.cloneDeep)(parseResult),
110
+ value: this.options.dereference.immutable ? (0, _apidomDatamodel.cloneDeep)(parseResult) : parseResult,
87
111
  depth: this.reference.depth + 1
88
112
  });
89
113
  refSet.add(mutableReference);
90
114
  if (this.options.dereference.immutable) {
91
- // register new immutable reference with a refSet
115
+ // register new immutable reference with original parseResult
92
116
  const immutableReference = new _Reference.default({
93
117
  uri: `immutable://${baseURI}`,
94
118
  value: parseResult,
@@ -98,25 +122,86 @@ class OpenAPI3_1DereferenceVisitor {
98
122
  }
99
123
  return mutableReference;
100
124
  }
101
- toAncestorLineage(path) {
102
- /**
103
- * Compute full ancestors lineage.
104
- * Ancestors are flatten to unwrap all Element instances.
105
- */
106
- const ancestorNodes = path.getAncestorNodes();
107
- const directAncestors = new Set(ancestorNodes.filter(_apidomDatamodel.isElement));
108
- const ancestorsLineage = new _util2.AncestorLineage(...this.ancestors, directAncestors);
109
- return [ancestorsLineage, directAncestors];
125
+
126
+ /**
127
+ * Handles an error according to the continueOnError option.
128
+ *
129
+ * For new errors: wraps in UnresolvableReferenceError with structured context
130
+ * (type, uri, location, codeFrame, refFieldName, refFieldValue, trace).
131
+ * For errors already wrapped by a nested visitor: prepends the current hop to the trace.
132
+ *
133
+ * Inner/intermediate visitors always throw to let the trace accumulate.
134
+ * Only the entry document visitor respects continueOnError (callback/swallow/throw).
135
+ */
136
+ handleError(message, error, referencingElement, refFieldName, refFieldValue, visitorPath) {
137
+ const {
138
+ continueOnError
139
+ } = this.options.dereference;
140
+ const isEntryDocument = url.stripHash(this.reference.refSet?.rootRef?.uri ?? '') === this.reference.uri;
141
+ const uri = this.reference.uri;
142
+ const type = referencingElement.element;
143
+ const codeFrame = (0, _apidomCore.toYAML)(referencingElement);
144
+
145
+ // find element location: tree search for entry documents, visitor path for external
146
+ let location;
147
+ (0, _apidomTraverse.traverse)(this.reference.value.result, {
148
+ enter: p => {
149
+ if (p.node === referencingElement || this.refractCache.get(p.node) === referencingElement) {
150
+ location = p.formatPath();
151
+ p.stop();
152
+ }
153
+ }
154
+ });
155
+ location ??= visitorPath.formatPath();
156
+ const hop = {
157
+ uri,
158
+ type,
159
+ refFieldName,
160
+ refFieldValue,
161
+ location,
162
+ codeFrame
163
+ };
164
+
165
+ // enrich existing error from nested visitor or create new one
166
+ let unresolvedError;
167
+ if (error instanceof _UnresolvableReferenceError.default) {
168
+ // prefix relative locations for entries belonging to the referenced document
169
+ const refBaseURI = this.toBaseURI(refFieldValue);
170
+ const fragment = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference(refFieldValue);
171
+ if (fragment) {
172
+ if (refBaseURI === error.uri && error.location) {
173
+ error.location = fragment + error.location;
174
+ }
175
+ for (const h of error.trace) {
176
+ if (h.uri === refBaseURI && h.location) h.location = fragment + h.location;
177
+ }
178
+ }
179
+ // @ts-ignore
180
+ error.trace = [hop, ...error.trace];
181
+ unresolvedError = error;
182
+ } else {
183
+ unresolvedError = new _UnresolvableReferenceError.default(message, {
184
+ cause: error,
185
+ type,
186
+ uri,
187
+ location,
188
+ codeFrame,
189
+ refFieldName,
190
+ refFieldValue,
191
+ trace: []
192
+ });
193
+ }
194
+ if (!isEntryDocument || continueOnError === false) throw unresolvedError;
195
+ if (typeof continueOnError === 'function') continueOnError(unresolvedError);
110
196
  }
111
197
  async ReferenceElement(path) {
112
198
  const referencingElement = path.node;
113
199
 
114
- // skip current referencing element as it's already been access
200
+ // skip current referencing element as it's already been accessed
115
201
  if (this.indirections.includes(referencingElement)) {
116
202
  path.skip();
117
203
  return;
118
204
  }
119
- const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
120
205
  const retrievalURI = this.toBaseURI((0, _apidomCore.toValue)(referencingElement.$ref));
121
206
  const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
122
207
  const isExternalReference = !isInternalReference;
@@ -133,133 +218,140 @@ class OpenAPI3_1DereferenceVisitor {
133
218
  path.skip();
134
219
  return;
135
220
  }
136
- const reference = await this.toReference((0, _apidomCore.toValue)(referencingElement.$ref));
137
221
  const $refBaseURI = url.resolve(retrievalURI, (0, _apidomCore.toValue)(referencingElement.$ref));
138
- this.indirections.push(referencingElement);
139
- const jsonPointer = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference($refBaseURI);
222
+ const indirectionsSize = this.indirections.length;
223
+ try {
224
+ const reference = await this.toReference((0, _apidomCore.toValue)(referencingElement.$ref));
225
+ this.indirections.push(referencingElement);
226
+ const jsonPointer = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference($refBaseURI);
140
227
 
141
- // possibly non-semantic fragment
142
- let referencedElement = (0, _apidomJsonPointer.evaluate)(reference.value.result, jsonPointer);
143
- referencedElement.id = identityManager.identify(referencedElement);
228
+ // possibly non-semantic fragment
229
+ let referencedElement = (0, _apidomJsonPointer.evaluate)(reference.value.result, jsonPointer);
144
230
 
145
- // applying semantics to a fragment
146
- if ((0, _apidomDatamodel.isPrimitiveElement)(referencedElement)) {
231
+ // applying semantics to a fragment
147
232
  const referencedElementType = referencingElement.meta.get('referenced-element');
148
- const cacheKey = `${referencedElementType}-${identityManager.identify(referencedElement)}`;
149
- if (this.refractCache.has(cacheKey)) {
150
- referencedElement = this.refractCache.get(cacheKey);
151
- } else if ((0, _apidomNsOpenapi.isReferenceLikeElement)(referencedElement)) {
152
- // handling indirect references
153
- referencedElement = (0, _apidomNsOpenapi.refractReference)(referencedElement);
154
- referencedElement.meta.set('referenced-element', referencedElementType);
155
- this.refractCache.set(cacheKey, referencedElement);
156
- } else {
157
- // handling direct references
158
- referencedElement = (0, _apidomNsOpenapi.refract)(referencedElement, {
159
- element: referencedElementType
233
+ if (referencedElement.element !== referencedElementType && !(0, _apidomNsOpenapi.isReferenceElement)(referencedElement)) {
234
+ if (this.refractCache.has(referencedElement)) {
235
+ referencedElement = this.refractCache.get(referencedElement);
236
+ } else if ((0, _apidomNsOpenapi.isReferenceLikeElement)(referencedElement)) {
237
+ // handling generic indirect references
238
+ const sourceElement = referencedElement;
239
+ referencedElement = (0, _apidomNsOpenapi.refractReference)(referencedElement);
240
+ referencedElement.meta.set('referenced-element', referencedElementType);
241
+ this.refractCache.set(sourceElement, referencedElement);
242
+ } else {
243
+ // handling direct references
244
+ const sourceElement = referencedElement;
245
+ referencedElement = (0, _apidomNsOpenapi.refract)(referencedElement, {
246
+ element: referencedElementType
247
+ });
248
+ this.refractCache.set(sourceElement, referencedElement);
249
+ }
250
+ }
251
+
252
+ // detect direct or indirect reference
253
+ if (referencingElement === referencedElement) {
254
+ throw new _apidomError.ApiDOMStructuredError('Recursive Reference Object detected', {
255
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
160
256
  });
161
- this.refractCache.set(cacheKey, referencedElement);
162
257
  }
163
- }
164
258
 
165
- // detect direct or indirect reference
166
- if (referencingElement === referencedElement) {
167
- throw new _apidomError.ApiDOMError('Recursive Reference Object detected');
168
- }
259
+ // detect maximum depth of dereferencing
260
+ if (this.indirections.length > this.options.dereference.maxDepth) {
261
+ throw new _MaximumDereferenceDepthError.default(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
262
+ maxDepth: this.options.dereference.maxDepth,
263
+ uri: this.reference.uri
264
+ });
265
+ }
169
266
 
170
- // detect maximum depth of dereferencing
171
- if (this.indirections.length > this.options.dereference.maxDepth) {
172
- throw new _MaximumDereferenceDepthError.default(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`);
173
- }
267
+ // detect cross-boundary cycle
268
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
269
+ if (ancestorsLineage.includes(referencedElement)) {
270
+ reference.refSet.circular = true;
271
+ if (this.options.dereference.circular === 'error') {
272
+ throw new _apidomError.ApiDOMStructuredError('Circular reference detected', {
273
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
274
+ });
275
+ } else if (this.options.dereference.circular === 'replace') {
276
+ const refElement = new _apidomDatamodel.RefElement($refBaseURI, {
277
+ type: referencingElement.element,
278
+ uri: reference.uri,
279
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
280
+ });
281
+ const replacer = this.options.dereference.strategyOpts['openapi-3-1']?.circularReplacer ?? this.options.dereference.circularReplacer;
282
+ const replacement = replacer(refElement);
283
+ path.replaceWith(replacement);
284
+ return;
285
+ }
286
+ }
174
287
 
175
- // detect second deep dive into the same fragment and avoid it
176
- if (ancestorsLineage.includes(referencedElement)) {
177
- reference.refSet.circular = true;
178
- if (this.options.dereference.circular === 'error') {
179
- throw new _apidomError.ApiDOMError('Circular reference detected');
180
- } else if (this.options.dereference.circular === 'replace') {
181
- const refElement = new _apidomDatamodel.RefElement(referencedElement.id, {
182
- type: 'reference',
183
- uri: reference.uri,
184
- $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
288
+ /**
289
+ * Dive deep into the fragment.
290
+ *
291
+ * Cases to consider:
292
+ * 1. We're crossing document boundary
293
+ * 2. Fragment is from non-entry document
294
+ * 3. Fragment is a Reference Object. We need to follow it to get the eventual value
295
+ * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
296
+ */
297
+ const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
298
+ const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
299
+ if ((isExternalReference || isNonEntryDocument || (0, _apidomNsOpenapi.isReferenceElement)(referencedElement) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
300
+ directAncestors.add(referencingElement);
301
+ const visitor = new OpenAPI3_1DereferenceVisitor({
302
+ reference,
303
+ indirections: [...this.indirections],
304
+ options: this.options,
305
+ refractCache: this.refractCache,
306
+ ancestors: ancestorsLineage
185
307
  });
186
- const replacer = this.options.dereference.strategyOpts['openapi-3-1']?.circularReplacer ?? this.options.dereference.circularReplacer;
187
- const replacement = replacer(refElement);
188
- this.indirections.pop();
189
- path.replaceWith(replacement);
190
- return;
308
+ referencedElement = await (0, _apidomTraverse.traverseAsync)(referencedElement, visitor, {
309
+ mutable: true
310
+ });
311
+ directAncestors.delete(referencingElement);
191
312
  }
192
- }
193
313
 
194
- /**
195
- * Dive deep into the fragment.
196
- *
197
- * Cases to consider:
198
- * 1. We're crossing document boundary
199
- * 2. Fragment is from non-root document
200
- * 3. Fragment is a Reference Object. We need to follow it to get the eventual value
201
- * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
202
- */
203
- const isNonRootDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
204
- const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
205
- if ((isExternalReference || isNonRootDocument || (0, _apidomNsOpenapi.isReferenceElement)(referencedElement) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
206
- // append referencing reference to ancestors lineage
207
- directAncestors.add(referencingElement);
208
- const visitor = new OpenAPI3_1DereferenceVisitor({
209
- reference,
210
- namespace: this.namespace,
211
- indirections: [...this.indirections],
212
- options: this.options,
213
- refractCache: this.refractCache,
214
- ancestors: ancestorsLineage
215
- });
216
- referencedElement = await (0, _apidomTraverse.traverseAsync)(referencedElement, visitor, {
217
- mutable: true
314
+ /**
315
+ * Creating a new version of referenced element to avoid modifying the original one.
316
+ */
317
+ const mergedElement = (0, _apidomDatamodel.cloneShallow)(referencedElement);
318
+ // annotate fragment with info about original Reference element
319
+ mergedElement.meta.set('ref-fields', {
320
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref),
321
+ // @ts-ignore
322
+ description: (0, _apidomCore.toValue)(referencingElement.description),
323
+ // @ts-ignore
324
+ summary: (0, _apidomCore.toValue)(referencingElement.summary)
218
325
  });
326
+ // annotate fragment with info about origin and type
327
+ mergedElement.meta.set('ref-origin', reference.uri);
328
+ mergedElement.meta.set('ref-type', referencingElement.element);
219
329
 
220
- // remove referencing reference from ancestors lineage
221
- directAncestors.delete(referencingElement);
222
- }
223
- this.indirections.pop();
224
-
225
- /**
226
- * Creating a new version of referenced element to avoid modifying the original one.
227
- */
228
- const mergedElement = (0, _apidomDatamodel.cloneShallow)(referencedElement);
229
- // assign unique id to merged element
230
- mergedElement.meta.set('id', identityManager.generateId());
231
- // annotate fragment with info about original Reference element
232
- mergedElement.meta.set('ref-fields', {
233
- $ref: (0, _apidomCore.toValue)(referencingElement.$ref),
234
- // @ts-ignore
235
- description: (0, _apidomCore.toValue)(referencingElement.description),
236
- // @ts-ignore
237
- summary: (0, _apidomCore.toValue)(referencingElement.summary)
238
- });
239
- // annotate fragment with info about origin
240
- mergedElement.meta.set('ref-origin', reference.uri);
241
- // annotate fragment with info about referencing element
242
- mergedElement.meta.set('ref-referencing-element-id', identityManager.identify(referencingElement));
243
-
244
- // override description and summary (outer has higher priority then inner)
245
- if ((0, _apidomDatamodel.isObjectElement)(referencedElement) && (0, _apidomDatamodel.isObjectElement)(mergedElement)) {
246
- const fields = (0, _apidomCore.fixedFields)(referencedElement, {
247
- indexed: true
248
- });
249
- if (referencingElement.hasKey('description') && Object.hasOwn(fields, 'description')) {
250
- mergedElement.remove('description');
251
- mergedElement.set('description', referencingElement.get('description'));
252
- }
253
- if (referencingElement.hasKey('summary') && Object.hasOwn(fields, 'summary')) {
254
- mergedElement.remove('summary');
255
- mergedElement.set('summary', referencingElement.get('summary'));
330
+ // override description and summary (outer has higher priority then inner)
331
+ if ((0, _apidomDatamodel.isObjectElement)(referencedElement) && (0, _apidomDatamodel.isObjectElement)(mergedElement)) {
332
+ const fields = (0, _apidomCore.fixedFields)(referencedElement, {
333
+ indexed: true
334
+ });
335
+ if (referencingElement.hasKey('description') && Object.hasOwn(fields, 'description')) {
336
+ mergedElement.remove('description');
337
+ mergedElement.set('description', referencingElement.get('description'));
338
+ }
339
+ if (referencingElement.hasKey('summary') && Object.hasOwn(fields, 'summary')) {
340
+ mergedElement.remove('summary');
341
+ mergedElement.set('summary', referencingElement.get('summary'));
342
+ }
256
343
  }
257
- }
258
344
 
259
- /**
260
- * Transclude referencing element with merged referenced element.
261
- */
262
- path.replaceWith(mergedElement);
345
+ /**
346
+ * Transclude referencing element with merged referenced element.
347
+ */
348
+ path.replaceWith(mergedElement);
349
+ } catch (error) {
350
+ const $ref = (0, _apidomCore.toValue)(referencingElement.$ref);
351
+ this.handleError(`Error while dereferencing Reference Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
352
+ } finally {
353
+ if (this.indirections.length > indirectionsSize) this.indirections.pop();
354
+ }
263
355
  }
264
356
  async PathItemElement(path) {
265
357
  const referencingElement = path.node;
@@ -269,12 +361,11 @@ class OpenAPI3_1DereferenceVisitor {
269
361
  return;
270
362
  }
271
363
 
272
- // skip current referencing element as it's already been access
364
+ // skip current referencing element as it's already been accessed
273
365
  if (this.indirections.includes(referencingElement)) {
274
366
  path.skip();
275
367
  return;
276
368
  }
277
- const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
278
369
  const retrievalURI = this.toBaseURI((0, _apidomCore.toValue)(referencingElement.$ref));
279
370
  const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
280
371
  const isExternalReference = !isInternalReference;
@@ -289,117 +380,121 @@ class OpenAPI3_1DereferenceVisitor {
289
380
  // skip traversing this Path Item element but traverse all it's child elements
290
381
  return;
291
382
  }
292
- const reference = await this.toReference((0, _apidomCore.toValue)(referencingElement.$ref));
293
383
  const $refBaseURI = url.resolve(retrievalURI, (0, _apidomCore.toValue)(referencingElement.$ref));
294
- this.indirections.push(referencingElement);
295
- const jsonPointer = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference($refBaseURI);
296
-
297
- // possibly non-semantic referenced element
298
- let referencedElement = (0, _apidomJsonPointer.evaluate)(reference.value.result, jsonPointer);
299
- referencedElement.id = identityManager.identify(referencedElement);
300
-
301
- /**
302
- * Applying semantics to a referenced element if semantics are missing.
303
- */
304
- if ((0, _apidomDatamodel.isPrimitiveElement)(referencedElement)) {
305
- const cacheKey = `path-item-${identityManager.identify(referencedElement)}`;
306
- if (this.refractCache.has(cacheKey)) {
307
- referencedElement = this.refractCache.get(cacheKey);
308
- } else {
309
- referencedElement = (0, _apidomNsOpenapi.refractPathItem)(referencedElement);
310
- this.refractCache.set(cacheKey, referencedElement);
311
- }
312
- }
384
+ const indirectionsSize = this.indirections.length;
385
+ try {
386
+ const reference = await this.toReference((0, _apidomCore.toValue)(referencingElement.$ref));
387
+ this.indirections.push(referencingElement);
388
+ const jsonPointer = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference($refBaseURI);
313
389
 
314
- // detect direct or indirect reference
315
- if (referencingElement === referencedElement) {
316
- throw new _apidomError.ApiDOMError('Recursive Path Item Object reference detected');
317
- }
390
+ // possibly non-semantic referenced element
391
+ let referencedElement = (0, _apidomJsonPointer.evaluate)(reference.value.result, jsonPointer);
318
392
 
319
- // detect maximum depth of dereferencing
320
- if (this.indirections.length > this.options.dereference.maxDepth) {
321
- throw new _MaximumDereferenceDepthError.default(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`);
322
- }
393
+ // applying semantics to a referenced element
394
+ if (!(0, _apidomNsOpenapi.isPathItemElement)(referencedElement)) {
395
+ if (this.refractCache.has(referencedElement)) {
396
+ referencedElement = this.refractCache.get(referencedElement);
397
+ } else {
398
+ const sourceElement = referencedElement;
399
+ referencedElement = (0, _apidomNsOpenapi.refractPathItem)(referencedElement);
400
+ this.refractCache.set(sourceElement, referencedElement);
401
+ }
402
+ }
323
403
 
324
- // detect second deep dive into the same fragment and avoid it
325
- if (ancestorsLineage.includes(referencedElement)) {
326
- reference.refSet.circular = true;
327
- if (this.options.dereference.circular === 'error') {
328
- throw new _apidomError.ApiDOMError('Circular reference detected');
329
- } else if (this.options.dereference.circular === 'replace') {
330
- const refElement = new _apidomDatamodel.RefElement(referencedElement.id, {
331
- type: 'path-item',
332
- uri: reference.uri,
404
+ // detect direct or indirect reference
405
+ if (referencingElement === referencedElement) {
406
+ throw new _apidomError.ApiDOMStructuredError('Recursive Path Item Object reference detected', {
333
407
  $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
334
408
  });
335
- const replacer = this.options.dereference.strategyOpts['openapi-3-1']?.circularReplacer ?? this.options.dereference.circularReplacer;
336
- const replacement = replacer(refElement);
337
- this.indirections.pop();
338
- path.replaceWith(replacement);
339
- return;
340
409
  }
341
- }
342
410
 
343
- /**
344
- * Dive deep into the fragment.
345
- *
346
- * Cases to consider:
347
- * 1. We're crossing document boundary
348
- * 2. Fragment is from non-root document
349
- * 3. Fragment is a Path Item Object with $ref field. We need to follow it to get the eventual value
350
- * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
351
- */
352
- const isNonRootDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
353
- const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
354
- if ((isExternalReference || isNonRootDocument || (0, _apidomNsOpenapi.isPathItemElement)(referencedElement) && (0, _apidomDatamodel.isStringElement)(referencedElement.$ref) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
355
- // append referencing reference to ancestors lineage
356
- directAncestors.add(referencingElement);
357
- const visitor = new OpenAPI3_1DereferenceVisitor({
358
- reference,
359
- namespace: this.namespace,
360
- indirections: [...this.indirections],
361
- options: this.options,
362
- refractCache: this.refractCache,
363
- ancestors: ancestorsLineage
364
- });
365
- referencedElement = await (0, _apidomTraverse.traverseAsync)(referencedElement, visitor, {
366
- mutable: true
367
- });
411
+ // detect maximum depth of dereferencing
412
+ if (this.indirections.length > this.options.dereference.maxDepth) {
413
+ throw new _MaximumDereferenceDepthError.default(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
414
+ maxDepth: this.options.dereference.maxDepth,
415
+ uri: this.reference.uri
416
+ });
417
+ }
368
418
 
369
- // remove referencing reference from ancestors lineage
370
- directAncestors.delete(referencingElement);
371
- }
372
- this.indirections.pop();
419
+ // detect cross-boundary cycle
420
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
421
+ if (ancestorsLineage.includes(referencedElement)) {
422
+ reference.refSet.circular = true;
423
+ if (this.options.dereference.circular === 'error') {
424
+ throw new _apidomError.ApiDOMStructuredError('Circular reference detected', {
425
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
426
+ });
427
+ } else if (this.options.dereference.circular === 'replace') {
428
+ const refElement = new _apidomDatamodel.RefElement($refBaseURI, {
429
+ type: referencingElement.element,
430
+ uri: reference.uri,
431
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
432
+ });
433
+ const replacer = this.options.dereference.strategyOpts['openapi-3-1']?.circularReplacer ?? this.options.dereference.circularReplacer;
434
+ const replacement = replacer(refElement);
435
+ path.replaceWith(replacement);
436
+ return;
437
+ }
438
+ }
373
439
 
374
- /**
375
- * Creating a new version of Path Item by merging fields from referenced Path Item with referencing one.
376
- */
377
- if ((0, _apidomNsOpenapi.isPathItemElement)(referencedElement)) {
378
- const mergedElement = (0, _apidomDatamodel.cloneShallow)(referencedElement);
379
- // assign unique id to merged element
380
- mergedElement.meta.set('id', identityManager.generateId());
381
- // existing keywords from referencing PathItemElement overrides ones from referenced element
382
- referencingElement.forEach((value, keyElement, item) => {
383
- mergedElement.remove((0, _apidomCore.toValue)(keyElement));
384
- mergedElement.content.push(item);
385
- });
386
- mergedElement.remove('$ref');
440
+ /**
441
+ * Dive deep into the fragment.
442
+ *
443
+ * Cases to consider:
444
+ * 1. We're crossing document boundary
445
+ * 2. Fragment is from non-entry document
446
+ * 3. Fragment is a Path Item Object with $ref field. We need to follow it to get the eventual value
447
+ * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
448
+ */
449
+ const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
450
+ const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
451
+ if ((isExternalReference || isNonEntryDocument || (0, _apidomNsOpenapi.isPathItemElement)(referencedElement) && (0, _apidomDatamodel.isStringElement)(referencedElement.$ref) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
452
+ directAncestors.add(referencingElement);
453
+ const visitor = new OpenAPI3_1DereferenceVisitor({
454
+ reference,
455
+ indirections: [...this.indirections],
456
+ options: this.options,
457
+ refractCache: this.refractCache,
458
+ ancestors: ancestorsLineage
459
+ });
460
+ referencedElement = await (0, _apidomTraverse.traverseAsync)(referencedElement, visitor, {
461
+ mutable: true
462
+ });
463
+ directAncestors.delete(referencingElement);
464
+ }
387
465
 
388
- // annotate referenced element with info about original referencing element
389
- mergedElement.meta.set('ref-fields', {
390
- $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
391
- });
392
- // annotate referenced element with info about origin
393
- mergedElement.meta.set('ref-origin', reference.uri);
394
- // annotate fragment with info about referencing element
395
- mergedElement.meta.set('ref-referencing-element-id', identityManager.identify(referencingElement));
396
- referencedElement = mergedElement;
397
- }
466
+ /**
467
+ * Creating a new version of Path Item by merging fields from referenced Path Item with referencing one.
468
+ */
469
+ if ((0, _apidomNsOpenapi.isPathItemElement)(referencedElement)) {
470
+ const mergedElement = (0, _apidomDatamodel.cloneShallow)(referencedElement);
471
+ // existing keywords from referencing PathItemElement overrides ones from referenced element
472
+ referencingElement.forEach((value, keyElement, item) => {
473
+ mergedElement.remove((0, _apidomCore.toValue)(keyElement));
474
+ mergedElement.content.push(item);
475
+ });
476
+ mergedElement.remove('$ref');
477
+
478
+ // annotate referenced element with info about original referencing element
479
+ mergedElement.meta.set('ref-fields', {
480
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
481
+ });
482
+ // annotate referenced element with info about origin and type
483
+ mergedElement.meta.set('ref-origin', reference.uri);
484
+ mergedElement.meta.set('ref-type', referencingElement.element);
485
+ referencedElement = mergedElement;
486
+ }
398
487
 
399
- /**
400
- * Transclude referencing element with merged referenced element.
401
- */
402
- path.replaceWith(referencedElement);
488
+ /**
489
+ * Transclude referencing element with merged referenced element.
490
+ */
491
+ path.replaceWith(referencedElement);
492
+ } catch (error) {
493
+ const $ref = (0, _apidomCore.toValue)(referencingElement.$ref);
494
+ this.handleError(`Error while dereferencing Path Item Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
495
+ } finally {
496
+ if (this.indirections.length > indirectionsSize) this.indirections.pop();
497
+ }
403
498
  }
404
499
  async LinkElement(path) {
405
500
  const linkElement = path.node;
@@ -411,66 +506,78 @@ class OpenAPI3_1DereferenceVisitor {
411
506
 
412
507
  // operationRef and operationId fields are mutually exclusive
413
508
  if ((0, _apidomDatamodel.isStringElement)(linkElement.operationRef) && (0, _apidomDatamodel.isStringElement)(linkElement.operationId)) {
414
- throw new _apidomError.ApiDOMError('LinkElement operationRef and operationId fields are mutually exclusive');
509
+ throw new _apidomError.ApiDOMStructuredError('LinkElement operationRef and operationId fields are mutually exclusive', {
510
+ operationRef: (0, _apidomCore.toValue)(linkElement.operationRef),
511
+ operationId: (0, _apidomCore.toValue)(linkElement.operationId)
512
+ });
415
513
  }
416
- let operationElement;
417
- if ((0, _apidomDatamodel.isStringElement)(linkElement.operationRef)) {
418
- // possibly non-semantic referenced element
419
- const jsonPointer = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference((0, _apidomCore.toValue)(linkElement.operationRef));
420
- const retrievalURI = this.toBaseURI((0, _apidomCore.toValue)(linkElement.operationRef));
421
- const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
422
- const isExternalReference = !isInternalReference;
423
-
424
- // ignore resolving internal Operation Object reference
425
- if (!this.options.resolve.internal && isInternalReference) {
426
- // skip traversing this Link element but traverse all it's child elements
427
- return;
428
- }
429
- // ignore resolving external Operation Object reference
430
- if (!this.options.resolve.external && isExternalReference) {
431
- // skip traversing this Link element but traverse all it's child elements
514
+ try {
515
+ let operationElement;
516
+ if ((0, _apidomDatamodel.isStringElement)(linkElement.operationRef)) {
517
+ // possibly non-semantic referenced element
518
+ const jsonPointer = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference((0, _apidomCore.toValue)(linkElement.operationRef));
519
+ const retrievalURI = this.toBaseURI((0, _apidomCore.toValue)(linkElement.operationRef));
520
+ const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
521
+ const isExternalReference = !isInternalReference;
522
+
523
+ // ignore resolving internal Operation Object reference
524
+ if (!this.options.resolve.internal && isInternalReference) {
525
+ // skip traversing this Link element but traverse all it's child elements
526
+ return;
527
+ }
528
+ // ignore resolving external Operation Object reference
529
+ if (!this.options.resolve.external && isExternalReference) {
530
+ // skip traversing this Link element but traverse all it's child elements
531
+ return;
532
+ }
533
+ const reference = await this.toReference((0, _apidomCore.toValue)(linkElement.operationRef));
534
+ operationElement = (0, _apidomJsonPointer.evaluate)(reference.value.result, jsonPointer);
535
+ // applying semantics to a referenced element
536
+ if (!(0, _apidomNsOpenapi.isOperationElement)(operationElement)) {
537
+ if (this.refractCache.has(operationElement)) {
538
+ operationElement = this.refractCache.get(operationElement);
539
+ } else {
540
+ const sourceElement = operationElement;
541
+ operationElement = (0, _apidomNsOpenapi.refractOperation)(operationElement);
542
+ this.refractCache.set(sourceElement, operationElement);
543
+ }
544
+ }
545
+ // create shallow clone to be able to annotate with metadata
546
+ operationElement = (0, _apidomDatamodel.cloneShallow)(operationElement);
547
+ // annotate operation element with info about origin and type
548
+ operationElement.meta.set('ref-origin', reference.uri);
549
+ operationElement.meta.set('ref-type', linkElement.element);
550
+ const linkElementCopy = (0, _apidomDatamodel.cloneShallow)(linkElement);
551
+ linkElementCopy.operationRef?.meta.set('operation', operationElement);
552
+
553
+ /**
554
+ * Transclude Link Object containing Operation Object in its meta.
555
+ */
556
+ path.replaceWith(linkElementCopy);
432
557
  return;
433
558
  }
434
- const reference = await this.toReference((0, _apidomCore.toValue)(linkElement.operationRef));
435
- operationElement = (0, _apidomJsonPointer.evaluate)(reference.value.result, jsonPointer);
436
- // applying semantics to a referenced element
437
- if ((0, _apidomDatamodel.isPrimitiveElement)(operationElement)) {
438
- const cacheKey = `operation-${identityManager.identify(operationElement)}`;
439
- if (this.refractCache.has(cacheKey)) {
440
- operationElement = this.refractCache.get(cacheKey);
441
- } else {
442
- operationElement = (0, _apidomNsOpenapi.refractOperation)(operationElement);
443
- this.refractCache.set(cacheKey, operationElement);
559
+ if ((0, _apidomDatamodel.isStringElement)(linkElement.operationId)) {
560
+ const operationId = (0, _apidomCore.toValue)(linkElement.operationId);
561
+ const reference = await this.toReference(url.unsanitize(this.reference.uri));
562
+ operationElement = (0, _apidomTraverse.find)(reference.value.result, e => (0, _apidomNsOpenapi.isOperationElement)(e) && (0, _apidomDatamodel.isElement)(e.operationId) && e.operationId.equals(operationId));
563
+ // OperationElement not found by its operationId
564
+ if ((0, _ramdaAdjunct.isUndefined)(operationElement)) {
565
+ throw new _apidomError.ApiDOMStructuredError(`OperationElement(operationId=${operationId}) not found`, {
566
+ operationId
567
+ });
444
568
  }
445
- }
446
- // create shallow clone to be able to annotate with metadata
447
- operationElement = (0, _apidomDatamodel.cloneShallow)(operationElement);
448
- // annotate operation element with info about origin
449
- operationElement.meta.set('ref-origin', reference.uri);
450
- const linkElementCopy = (0, _apidomDatamodel.cloneShallow)(linkElement);
451
- linkElementCopy.operationRef?.meta.set('operation', operationElement);
569
+ const linkElementCopy = (0, _apidomDatamodel.cloneShallow)(linkElement);
570
+ linkElementCopy.operationId?.meta.set('operation', operationElement);
452
571
 
453
- /**
454
- * Transclude Link Object containing Operation Object in its meta.
455
- */
456
- path.replaceWith(linkElementCopy);
457
- return;
458
- }
459
- if ((0, _apidomDatamodel.isStringElement)(linkElement.operationId)) {
460
- const operationId = (0, _apidomCore.toValue)(linkElement.operationId);
461
- const reference = await this.toReference(url.unsanitize(this.reference.uri));
462
- operationElement = (0, _apidomTraverse.find)(reference.value.result, e => (0, _apidomNsOpenapi.isOperationElement)(e) && (0, _apidomDatamodel.isElement)(e.operationId) && e.operationId.equals(operationId));
463
- // OperationElement not found by its operationId
464
- if ((0, _ramdaAdjunct.isUndefined)(operationElement)) {
465
- throw new _apidomError.ApiDOMError(`OperationElement(operationId=${operationId}) not found`);
572
+ /**
573
+ * Transclude Link Object containing Operation Object in its meta.
574
+ */
575
+ path.replaceWith(linkElementCopy);
466
576
  }
467
- const linkElementCopy = (0, _apidomDatamodel.cloneShallow)(linkElement);
468
- linkElementCopy.operationId?.meta.set('operation', operationElement);
469
-
470
- /**
471
- * Transclude Link Object containing Operation Object in its meta.
472
- */
473
- path.replaceWith(linkElementCopy);
577
+ } catch (error) {
578
+ const refFieldName = (0, _apidomDatamodel.isStringElement)(linkElement.operationRef) ? 'operationRef' : 'operationId';
579
+ const refFieldValue = (0, _apidomDatamodel.isStringElement)(linkElement.operationRef) ? (0, _apidomCore.toValue)(linkElement.operationRef) : (0, _apidomCore.toValue)(linkElement.operationId);
580
+ this.handleError(`Error while dereferencing Link Object. Cannot resolve ${refFieldName} "${refFieldValue}": ${error.message}`, error, linkElement, refFieldName, refFieldValue, path);
474
581
  }
475
582
  }
476
583
  async ExampleElement(path) {
@@ -483,7 +590,10 @@ class OpenAPI3_1DereferenceVisitor {
483
590
 
484
591
  // value and externalValue fields are mutually exclusive
485
592
  if (exampleElement.hasKey('value') && (0, _apidomDatamodel.isStringElement)(exampleElement.externalValue)) {
486
- throw new _apidomError.ApiDOMError('ExampleElement value and externalValue fields are mutually exclusive');
593
+ throw new _apidomError.ApiDOMStructuredError('ExampleElement value and externalValue fields are mutually exclusive', {
594
+ value: (0, _apidomCore.toValue)(exampleElement.value),
595
+ externalValue: (0, _apidomCore.toValue)(exampleElement.externalValue)
596
+ });
487
597
  }
488
598
  const retrievalURI = this.toBaseURI((0, _apidomCore.toValue)(exampleElement.externalValue));
489
599
  const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
@@ -499,19 +609,25 @@ class OpenAPI3_1DereferenceVisitor {
499
609
  // skip traversing this Example element but traverse all it's child elements
500
610
  return;
501
611
  }
502
- const reference = await this.toReference((0, _apidomCore.toValue)(exampleElement.externalValue));
503
-
504
- // shallow clone of the referenced element
505
- const valueElement = (0, _apidomDatamodel.cloneShallow)(reference.value.result);
506
- // annotate operation element with info about origin
507
- valueElement.meta.set('ref-origin', reference.uri);
508
- const exampleElementCopy = (0, _apidomDatamodel.cloneShallow)(exampleElement);
509
- exampleElementCopy.value = valueElement;
510
-
511
- /**
512
- * Transclude Example Object containing external value.
513
- */
514
- path.replaceWith(exampleElementCopy);
612
+ try {
613
+ const reference = await this.toReference((0, _apidomCore.toValue)(exampleElement.externalValue));
614
+
615
+ // shallow clone of the referenced element
616
+ const valueElement = (0, _apidomDatamodel.cloneShallow)(reference.value.result);
617
+ // annotate element with info about origin and type
618
+ valueElement.meta.set('ref-origin', reference.uri);
619
+ valueElement.meta.set('ref-type', exampleElement.element);
620
+ const exampleElementCopy = (0, _apidomDatamodel.cloneShallow)(exampleElement);
621
+ exampleElementCopy.value = valueElement;
622
+
623
+ /**
624
+ * Transclude Example Object containing external value.
625
+ */
626
+ path.replaceWith(exampleElementCopy);
627
+ } catch (error) {
628
+ const externalValue = (0, _apidomCore.toValue)(exampleElement.externalValue);
629
+ this.handleError(`Error while dereferencing Example Object. Cannot resolve externalValue "${externalValue}": ${error.message}`, error, exampleElement, 'externalValue', externalValue, path);
630
+ }
515
631
  }
516
632
  async SchemaElement(path) {
517
633
  const referencingElement = path.node;
@@ -521,83 +637,38 @@ class OpenAPI3_1DereferenceVisitor {
521
637
  return;
522
638
  }
523
639
 
524
- // skip current referencing element as it's already been access
640
+ // skip current referencing element as it's already been accessed
525
641
  if (this.indirections.includes(referencingElement)) {
526
642
  path.skip();
527
643
  return;
528
644
  }
529
- const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
530
-
531
- // compute baseURI using rules around $id and $ref keywords
532
- let reference = await this.toReference(url.unsanitize(this.reference.uri));
533
- let {
534
- uri: retrievalURI
535
- } = reference;
536
- const $refBaseURI = (0, _util.resolveSchema$refField)(retrievalURI, referencingElement);
537
- const $refBaseURIStrippedHash = url.stripHash($refBaseURI);
538
- const file = new _File.default({
539
- uri: $refBaseURIStrippedHash
540
- });
541
- const isUnknownURI = (0, _ramda.none)(r => r.canRead(file), this.options.resolve.resolvers);
542
- const isURL = !isUnknownURI;
543
- let isInternalReference = url.stripHash(this.reference.uri) === $refBaseURI;
544
- let isExternalReference = !isInternalReference;
545
-
546
- // determining reference, proper evaluation and selection mechanism
547
- let referencedElement;
645
+ const indirectionsSize = this.indirections.length;
548
646
  try {
549
- if (isUnknownURI || isURL) {
550
- // we're dealing with canonical URI or URL with possible fragment
551
- retrievalURI = this.toBaseURI($refBaseURI);
552
- const selector = $refBaseURI;
553
- const referenceAsSchema = (0, _util.maybeRefractToSchemaElement)(reference.value.result);
554
- referencedElement = (0, _uri.evaluate)(selector, referenceAsSchema);
555
- referencedElement = (0, _util.maybeRefractToSchemaElement)(referencedElement);
556
- referencedElement.id = identityManager.identify(referencedElement);
557
-
558
- // ignore resolving internal Schema Objects
559
- if (!this.options.resolve.internal && isInternalReference) {
560
- // skip traversing this schema element but traverse all it's child elements
561
- return;
562
- }
563
- // ignore resolving external Schema Objects
564
- if (!this.options.resolve.external && isExternalReference) {
565
- // skip traversing this schema element but traverse all it's child elements
566
- return;
567
- }
568
- } else {
569
- // we're assuming here that we're dealing with JSON Pointer here
570
- retrievalURI = this.toBaseURI($refBaseURI);
571
- isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
572
- isExternalReference = !isInternalReference;
573
-
574
- // ignore resolving internal Schema Objects
575
- if (!this.options.resolve.internal && isInternalReference) {
576
- // skip traversing this schema element but traverse all it's child elements
577
- return;
578
- }
579
- // ignore resolving external Schema Objects
580
- if (!this.options.resolve.external && isExternalReference) {
581
- // skip traversing this schema element but traverse all it's child elements
582
- return;
583
- }
584
- reference = await this.toReference(url.unsanitize($refBaseURI));
585
- const selector = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference($refBaseURI);
586
- const referenceAsSchema = (0, _util.maybeRefractToSchemaElement)(reference.value.result);
587
- referencedElement = (0, _apidomJsonPointer.evaluate)(referenceAsSchema, selector);
588
- referencedElement = (0, _util.maybeRefractToSchemaElement)(referencedElement);
589
- referencedElement.id = identityManager.identify(referencedElement);
590
- }
591
- } catch (error) {
592
- /**
593
- * SchemaElement($id=URL) was not found, so we're going to try to resolve
594
- * the URL and assume the returned response is a JSON Schema.
595
- */
596
- if (isURL && error instanceof _EvaluationJsonSchemaUriError.default) {
597
- if ((0, _$anchor.isAnchor)((0, _$anchor.uriToAnchor)($refBaseURI))) {
598
- // we're dealing with JSON Schema $anchor here
599
- isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
600
- isExternalReference = !isInternalReference;
647
+ // compute baseURI using rules around $id and $ref keywords
648
+ let reference = await this.toReference(url.unsanitize(this.reference.uri));
649
+ let {
650
+ uri: retrievalURI
651
+ } = reference;
652
+ const $refBaseURI = (0, _util.resolveSchema$refField)(retrievalURI, referencingElement);
653
+ const $refBaseURIStrippedHash = url.stripHash($refBaseURI);
654
+ const file = new _File.default({
655
+ uri: $refBaseURIStrippedHash
656
+ });
657
+ const isUnknownURI = (0, _ramda.none)(r => r.canRead(file), this.options.resolve.resolvers);
658
+ const isURL = !isUnknownURI;
659
+ let isInternalReference = url.stripHash(this.reference.uri) === $refBaseURI;
660
+ let isExternalReference = !isInternalReference;
661
+
662
+ // determining reference, proper evaluation and selection mechanism
663
+ let referencedElement;
664
+ try {
665
+ if (isUnknownURI || isURL) {
666
+ // we're dealing with canonical URI or URL with possible fragment
667
+ retrievalURI = this.toBaseURI($refBaseURI);
668
+ const selector = $refBaseURI;
669
+ const referenceAsSchema = (0, _util.maybeRefractToSchemaElement)(reference.value.result);
670
+ referencedElement = (0, _uri.evaluate)(selector, referenceAsSchema);
671
+ referencedElement = (0, _util.maybeRefractToSchemaElement)(referencedElement);
601
672
 
602
673
  // ignore resolving internal Schema Objects
603
674
  if (!this.options.resolve.internal && isInternalReference) {
@@ -609,12 +680,6 @@ class OpenAPI3_1DereferenceVisitor {
609
680
  // skip traversing this schema element but traverse all it's child elements
610
681
  return;
611
682
  }
612
- reference = await this.toReference(url.unsanitize($refBaseURI));
613
- const selector = (0, _$anchor.uriToAnchor)($refBaseURI);
614
- const referenceAsSchema = (0, _util.maybeRefractToSchemaElement)(reference.value.result);
615
- referencedElement = (0, _$anchor.evaluate)(selector, referenceAsSchema);
616
- referencedElement = (0, _util.maybeRefractToSchemaElement)(referencedElement);
617
- referencedElement.id = identityManager.identify(referencedElement);
618
683
  } else {
619
684
  // we're assuming here that we're dealing with JSON Pointer here
620
685
  retrievalURI = this.toBaseURI($refBaseURI);
@@ -636,118 +701,167 @@ class OpenAPI3_1DereferenceVisitor {
636
701
  const referenceAsSchema = (0, _util.maybeRefractToSchemaElement)(reference.value.result);
637
702
  referencedElement = (0, _apidomJsonPointer.evaluate)(referenceAsSchema, selector);
638
703
  referencedElement = (0, _util.maybeRefractToSchemaElement)(referencedElement);
639
- referencedElement.id = identityManager.identify(referencedElement);
640
704
  }
641
- } else {
642
- throw error;
705
+ } catch (error) {
706
+ /**
707
+ * SchemaElement($id=URL) was not found, so we're going to try to resolve
708
+ * the URL and assume the returned response is a JSON Schema.
709
+ */
710
+ if (isURL && error instanceof _EvaluationJsonSchemaUriError.default) {
711
+ if ((0, _$anchor.isAnchor)((0, _$anchor.uriToAnchor)($refBaseURI))) {
712
+ // we're dealing with JSON Schema $anchor here
713
+ isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
714
+ isExternalReference = !isInternalReference;
715
+
716
+ // ignore resolving internal Schema Objects
717
+ if (!this.options.resolve.internal && isInternalReference) {
718
+ // skip traversing this schema element but traverse all it's child elements
719
+ return;
720
+ }
721
+ // ignore resolving external Schema Objects
722
+ if (!this.options.resolve.external && isExternalReference) {
723
+ // skip traversing this schema element but traverse all it's child elements
724
+ return;
725
+ }
726
+ reference = await this.toReference(url.unsanitize($refBaseURI));
727
+ const selector = (0, _$anchor.uriToAnchor)($refBaseURI);
728
+ const referenceAsSchema = (0, _util.maybeRefractToSchemaElement)(reference.value.result);
729
+ referencedElement = (0, _$anchor.evaluate)(selector, referenceAsSchema);
730
+ referencedElement = (0, _util.maybeRefractToSchemaElement)(referencedElement);
731
+ } else {
732
+ // we're assuming here that we're dealing with JSON Pointer here
733
+ retrievalURI = this.toBaseURI($refBaseURI);
734
+ isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
735
+ isExternalReference = !isInternalReference;
736
+
737
+ // ignore resolving internal Schema Objects
738
+ if (!this.options.resolve.internal && isInternalReference) {
739
+ // skip traversing this schema element but traverse all it's child elements
740
+ return;
741
+ }
742
+ // ignore resolving external Schema Objects
743
+ if (!this.options.resolve.external && isExternalReference) {
744
+ // skip traversing this schema element but traverse all it's child elements
745
+ return;
746
+ }
747
+ reference = await this.toReference(url.unsanitize($refBaseURI));
748
+ const selector = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference($refBaseURI);
749
+ const referenceAsSchema = (0, _util.maybeRefractToSchemaElement)(reference.value.result);
750
+ referencedElement = (0, _apidomJsonPointer.evaluate)(referenceAsSchema, selector);
751
+ referencedElement = (0, _util.maybeRefractToSchemaElement)(referencedElement);
752
+ }
753
+ } else {
754
+ throw error;
755
+ }
643
756
  }
644
- }
645
- this.indirections.push(referencingElement);
757
+ this.indirections.push(referencingElement);
646
758
 
647
- // detect direct or indirect reference
648
- if (referencingElement === referencedElement) {
649
- throw new _apidomError.ApiDOMError('Recursive Schema Object reference detected');
650
- }
759
+ // detect direct or indirect reference
760
+ if (referencingElement === referencedElement) {
761
+ throw new _apidomError.ApiDOMStructuredError('Recursive Schema Object reference detected', {
762
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
763
+ });
764
+ }
651
765
 
652
- // detect maximum depth of dereferencing
653
- if (this.indirections.length > this.options.dereference.maxDepth) {
654
- throw new _MaximumDereferenceDepthError.default(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`);
655
- }
766
+ // detect maximum depth of dereferencing
767
+ if (this.indirections.length > this.options.dereference.maxDepth) {
768
+ throw new _MaximumDereferenceDepthError.default(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
769
+ maxDepth: this.options.dereference.maxDepth,
770
+ uri: this.reference.uri
771
+ });
772
+ }
773
+
774
+ // detect cross-boundary cycle
775
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
776
+ if (ancestorsLineage.includes(referencedElement)) {
777
+ reference.refSet.circular = true;
778
+ if (this.options.dereference.circular === 'error') {
779
+ throw new _apidomError.ApiDOMStructuredError('Circular reference detected', {
780
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
781
+ });
782
+ } else if (this.options.dereference.circular === 'replace') {
783
+ const refElement = new _apidomDatamodel.RefElement($refBaseURI, {
784
+ type: referencingElement.element,
785
+ uri: reference.uri,
786
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
787
+ });
788
+ const replacer = this.options.dereference.strategyOpts['openapi-3-1']?.circularReplacer ?? this.options.dereference.circularReplacer;
789
+ const replacement = replacer(refElement);
790
+ path.replaceWith(replacement);
791
+ return;
792
+ }
793
+ }
794
+
795
+ /**
796
+ * Dive deep into the fragment.
797
+ *
798
+ * Cases to consider:
799
+ * 1. We're crossing document boundary
800
+ * 2. Fragment is from non-entry document
801
+ * 3. Fragment is a Schema Object with $ref field. We need to follow it to get the eventual value
802
+ * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
803
+ */
804
+ const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
805
+ const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
806
+ if ((isExternalReference || isNonEntryDocument || (0, _apidomNsOpenapi.isSchemaElement)(referencedElement) && (0, _apidomDatamodel.isStringElement)(referencedElement.$ref) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
807
+ directAncestors.add(referencingElement);
808
+ const visitor = new OpenAPI3_1DereferenceVisitor({
809
+ reference,
810
+ indirections: [...this.indirections],
811
+ options: this.options,
812
+ refractCache: this.refractCache,
813
+ ancestors: ancestorsLineage
814
+ });
815
+ referencedElement = await (0, _apidomTraverse.traverseAsync)(referencedElement, visitor, {
816
+ mutable: true
817
+ });
818
+ directAncestors.delete(referencingElement);
819
+ }
656
820
 
657
- // detect second deep dive into the same fragment and avoid it
658
- if (ancestorsLineage.includes(referencedElement)) {
659
- reference.refSet.circular = true;
660
- if (this.options.dereference.circular === 'error') {
661
- throw new _apidomError.ApiDOMError('Circular reference detected');
662
- } else if (this.options.dereference.circular === 'replace') {
663
- const refElement = new _apidomDatamodel.RefElement(referencedElement.id, {
664
- type: 'json-schema',
665
- uri: reference.uri,
821
+ // Boolean JSON Schemas
822
+ if ((0, _apidomNsOpenapi.isBooleanJSONSchemaElement)(referencedElement)) {
823
+ const booleanJsonSchemaElement = (0, _apidomDatamodel.cloneDeep)(referencedElement);
824
+ // annotate referenced element with info about original referencing element
825
+ booleanJsonSchemaElement.meta.set('ref-fields', {
666
826
  $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
667
827
  });
668
- const replacer = this.options.dereference.strategyOpts['openapi-3-1']?.circularReplacer ?? this.options.dereference.circularReplacer;
669
- const replacement = replacer(refElement);
670
- this.indirections.pop();
671
- path.replaceWith(replacement);
828
+ // annotate referenced element with info about origin and type
829
+ booleanJsonSchemaElement.meta.set('ref-origin', reference.uri);
830
+ booleanJsonSchemaElement.meta.set('ref-type', referencingElement.element);
831
+ path.replaceWith(booleanJsonSchemaElement);
672
832
  return;
673
833
  }
674
- }
675
-
676
- /**
677
- * Dive deep into the fragment.
678
- *
679
- * Cases to consider:
680
- * 1. We're crossing document boundary
681
- * 2. Fragment is from non-root document
682
- * 3. Fragment is a Schema Object with $ref field. We need to follow it to get the eventual value
683
- * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
684
- */
685
- const isNonRootDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
686
- const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
687
- if ((isExternalReference || isNonRootDocument || (0, _apidomNsOpenapi.isSchemaElement)(referencedElement) && (0, _apidomDatamodel.isStringElement)(referencedElement.$ref) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
688
- // append referencing reference to ancestors lineage
689
- directAncestors.add(referencingElement);
690
- const visitor = new OpenAPI3_1DereferenceVisitor({
691
- reference,
692
- namespace: this.namespace,
693
- indirections: [...this.indirections],
694
- options: this.options,
695
- refractCache: this.refractCache,
696
- ancestors: ancestorsLineage
697
- });
698
- referencedElement = await (0, _apidomTraverse.traverseAsync)(referencedElement, visitor, {
699
- mutable: true
700
- });
701
834
 
702
- // remove referencing reference from ancestors lineage
703
- directAncestors.delete(referencingElement);
704
- }
705
- this.indirections.pop();
706
-
707
- // Boolean JSON Schemas
708
- if ((0, _apidomNsOpenapi.isBooleanJSONSchemaElement)(referencedElement)) {
709
- const booleanJsonSchemaElement = (0, _apidomDatamodel.cloneDeep)(referencedElement);
710
- // assign unique id to merged element
711
- booleanJsonSchemaElement.meta.set('id', identityManager.generateId());
712
- // annotate referenced element with info about original referencing element
713
- booleanJsonSchemaElement.meta.set('ref-fields', {
714
- $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
715
- });
716
- // annotate referenced element with info about origin
717
- booleanJsonSchemaElement.meta.set('ref-origin', reference.uri);
718
- // annotate fragment with info about referencing element
719
- booleanJsonSchemaElement.meta.set('ref-referencing-element-id', identityManager.identify(referencingElement));
720
- path.replaceWith(booleanJsonSchemaElement);
721
- return;
722
- }
723
-
724
- /**
725
- * Creating a new version of Schema Object by merging fields from referenced Schema Object with referencing one.
726
- */
727
- if ((0, _apidomNsOpenapi.isSchemaElement)(referencedElement)) {
728
- const mergedElement = (0, _apidomDatamodel.cloneShallow)(referencedElement);
729
- // assign unique id to merged element
730
- mergedElement.meta.set('id', identityManager.generateId());
731
- // existing keywords from referencing schema overrides ones from referenced schema
732
- referencingElement.forEach((value, keyElement, item) => {
733
- mergedElement.remove((0, _apidomCore.toValue)(keyElement));
734
- mergedElement.content.push(item);
735
- });
736
- mergedElement.remove('$ref');
737
- // annotate referenced element with info about original referencing element
738
- mergedElement.meta.set('ref-fields', {
739
- $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
740
- });
741
- // annotate fragment with info about origin
742
- mergedElement.meta.set('ref-origin', reference.uri);
743
- // annotate fragment with info about referencing element
744
- mergedElement.meta.set('ref-referencing-element-id', identityManager.identify(referencingElement));
745
- referencedElement = mergedElement;
835
+ /**
836
+ * Creating a new version of Schema Object by merging fields from referenced Schema Object with referencing one.
837
+ */
838
+ if ((0, _apidomNsOpenapi.isSchemaElement)(referencedElement)) {
839
+ const mergedElement = (0, _apidomDatamodel.cloneShallow)(referencedElement);
840
+ // existing keywords from referencing schema overrides ones from referenced schema
841
+ referencingElement.forEach((value, keyElement, item) => {
842
+ mergedElement.remove((0, _apidomCore.toValue)(keyElement));
843
+ mergedElement.content.push(item);
844
+ });
845
+ mergedElement.remove('$ref');
846
+ // annotate referenced element with info about original referencing element
847
+ mergedElement.meta.set('ref-fields', {
848
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
849
+ });
850
+ // annotate fragment with info about origin and type
851
+ mergedElement.meta.set('ref-origin', reference.uri);
852
+ mergedElement.meta.set('ref-type', referencingElement.element);
853
+ referencedElement = mergedElement;
854
+ }
855
+ /**
856
+ * Transclude referencing element with merged referenced element.
857
+ */
858
+ path.replaceWith(referencedElement);
859
+ } catch (error) {
860
+ const $ref = (0, _apidomCore.toValue)(referencingElement.$ref);
861
+ this.handleError(`Error while dereferencing Schema Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
862
+ } finally {
863
+ if (this.indirections.length > indirectionsSize) this.indirections.pop();
746
864
  }
747
- /**
748
- * Transclude referencing element with merged referenced element.
749
- */
750
- path.replaceWith(referencedElement);
751
865
  }
752
866
  }
753
867
  var _default = exports.default = OpenAPI3_1DereferenceVisitor;