@speclynx/apidom-reference 2.3.0 → 2.5.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 (31) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +23 -1
  3. package/dist/apidom-reference.browser.js +3313 -620
  4. package/dist/apidom-reference.browser.min.js +1 -1
  5. package/package.json +32 -25
  6. package/src/configuration/saturated.cjs +11 -10
  7. package/src/configuration/saturated.mjs +2 -1
  8. package/src/dereference/strategies/arazzo-1/index.cjs +101 -0
  9. package/src/dereference/strategies/arazzo-1/index.mjs +91 -0
  10. package/src/dereference/strategies/arazzo-1/selectors/$anchor.cjs +12 -0
  11. package/src/dereference/strategies/arazzo-1/selectors/$anchor.mjs +1 -0
  12. package/src/dereference/strategies/arazzo-1/selectors/uri.cjs +8 -0
  13. package/src/dereference/strategies/arazzo-1/selectors/uri.mjs +1 -0
  14. package/src/dereference/strategies/arazzo-1/util.cjs +37 -0
  15. package/src/dereference/strategies/arazzo-1/util.mjs +29 -0
  16. package/src/dereference/strategies/arazzo-1/visitor.cjs +411 -0
  17. package/src/dereference/strategies/arazzo-1/visitor.mjs +405 -0
  18. package/src/dereference/strategies/asyncapi-2/visitor.cjs +1 -1
  19. package/src/dereference/strategies/asyncapi-2/visitor.mjs +2 -2
  20. package/src/dereference/strategies/openapi-3-1/selectors/$anchor.cjs +2 -2
  21. package/src/dereference/strategies/openapi-3-1/selectors/$anchor.mjs +2 -2
  22. package/src/dereference/strategies/openapi-3-1/selectors/uri.cjs +3 -3
  23. package/src/dereference/strategies/openapi-3-1/selectors/uri.mjs +3 -3
  24. package/src/dereference/strategies/openapi-3-1/visitor.cjs +8 -5
  25. package/src/dereference/strategies/openapi-3-1/visitor.mjs +10 -7
  26. package/types/dereference/strategies/arazzo-1/index.d.ts +32 -0
  27. package/types/dereference/strategies/arazzo-1/selectors/$anchor.d.ts +1 -0
  28. package/types/dereference/strategies/arazzo-1/selectors/uri.d.ts +1 -0
  29. package/types/dereference/strategies/arazzo-1/util.d.ts +13 -0
  30. package/types/dereference/strategies/arazzo-1/visitor.d.ts +32 -0
  31. package/types/dereference/strategies/openapi-3-1/util.d.ts +3 -3
@@ -0,0 +1,411 @@
1
+ "use strict";
2
+
3
+ var _interopRequireWildcard = require("@babel/runtime-corejs3/helpers/interopRequireWildcard").default;
4
+ var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default;
5
+ exports.__esModule = true;
6
+ exports.default = void 0;
7
+ var _ramda = require("ramda");
8
+ var _apidomDatamodel = require("@speclynx/apidom-datamodel");
9
+ var _apidomCore = require("@speclynx/apidom-core");
10
+ var _apidomError = require("@speclynx/apidom-error");
11
+ var _apidomTraverse = require("@speclynx/apidom-traverse");
12
+ var _apidomJsonPointer = require("@speclynx/apidom-json-pointer");
13
+ var _apidomNsArazzo = require("@speclynx/apidom-ns-arazzo-1");
14
+ var _arazzoRuntimeExpression = require("@swaggerexpert/arazzo-runtime-expression");
15
+ var _$anchor = require("./selectors/$anchor.cjs");
16
+ var _uri = require("./selectors/uri.cjs");
17
+ var _util = require("../openapi-3-1/util.cjs");
18
+ var _util2 = require("./util.cjs");
19
+ var _MaximumDereferenceDepthError = _interopRequireDefault(require("../../../errors/MaximumDereferenceDepthError.cjs"));
20
+ var _MaximumResolveDepthError = _interopRequireDefault(require("../../../errors/MaximumResolveDepthError.cjs"));
21
+ var url = _interopRequireWildcard(require("../../../util/url.cjs"));
22
+ var _index = _interopRequireDefault(require("../../../parse/index.cjs"));
23
+ var _Reference = _interopRequireDefault(require("../../../Reference.cjs"));
24
+ var _File = _interopRequireDefault(require("../../../File.cjs"));
25
+ var _util3 = require("../../util.cjs");
26
+ var _EvaluationJsonSchemaUriError = _interopRequireDefault(require("../../../errors/EvaluationJsonSchemaUriError.cjs"));
27
+ // initialize element identity manager
28
+ const identityManager = new _apidomCore.IdentityManager();
29
+
30
+ /**
31
+ * @public
32
+ */
33
+
34
+ /**
35
+ * @public
36
+ */
37
+ class Arazzo1DereferenceVisitor {
38
+ indirections;
39
+ namespace;
40
+ reference;
41
+ options;
42
+ ancestors;
43
+ constructor({
44
+ reference,
45
+ namespace,
46
+ options,
47
+ indirections = [],
48
+ ancestors = new _util3.AncestorLineage()
49
+ }) {
50
+ this.indirections = indirections;
51
+ this.namespace = namespace;
52
+ this.reference = reference;
53
+ this.options = options;
54
+ this.ancestors = new _util3.AncestorLineage(...ancestors);
55
+ }
56
+ toBaseURI(uri) {
57
+ return url.resolve(this.reference.uri, url.sanitize(url.stripHash(uri)));
58
+ }
59
+ async toReference(uri) {
60
+ // detect maximum depth of resolution
61
+ if (this.reference.depth >= this.options.resolve.maxDepth) {
62
+ throw new _MaximumResolveDepthError.default(`Maximum resolution depth of ${this.options.resolve.maxDepth} has been exceeded by file "${this.reference.uri}"`);
63
+ }
64
+ const baseURI = this.toBaseURI(uri);
65
+ const {
66
+ refSet
67
+ } = this.reference;
68
+
69
+ // we've already processed this Reference in past
70
+ if (refSet.has(baseURI)) {
71
+ return refSet.find((0, _ramda.propEq)(baseURI, 'uri'));
72
+ }
73
+ const parseResult = await (0, _index.default)(url.unsanitize(baseURI), {
74
+ ...this.options,
75
+ parse: {
76
+ ...this.options.parse,
77
+ mediaType: 'text/plain'
78
+ }
79
+ });
80
+
81
+ // register new mutable reference with a refSet
82
+ const mutableReference = new _Reference.default({
83
+ uri: baseURI,
84
+ value: (0, _apidomDatamodel.cloneDeep)(parseResult),
85
+ depth: this.reference.depth + 1
86
+ });
87
+ refSet.add(mutableReference);
88
+ if (this.options.dereference.immutable) {
89
+ // register new immutable reference with a refSet
90
+ const immutableReference = new _Reference.default({
91
+ uri: `immutable://${baseURI}`,
92
+ value: parseResult,
93
+ depth: this.reference.depth + 1
94
+ });
95
+ refSet.add(immutableReference);
96
+ }
97
+ return mutableReference;
98
+ }
99
+ toAncestorLineage(path) {
100
+ /**
101
+ * Compute full ancestors lineage.
102
+ * Ancestors are flatten to unwrap all Element instances.
103
+ */
104
+ const ancestorNodes = path.getAncestorNodes();
105
+ const directAncestors = new Set(ancestorNodes.filter(_apidomDatamodel.isElement));
106
+ const ancestorsLineage = new _util3.AncestorLineage(...this.ancestors, directAncestors);
107
+ return [ancestorsLineage, directAncestors];
108
+ }
109
+ ReusableElement(path) {
110
+ const referencingElement = path.node;
111
+
112
+ // skip current Reusable Object if reference field is not defined as a string
113
+ if (!(0, _apidomDatamodel.isStringElement)(referencingElement.reference)) {
114
+ path.skip();
115
+ return;
116
+ }
117
+
118
+ // ignore if resolve.internal is false (Reusable Objects are internal references only)
119
+ if (!this.options.resolve.internal) {
120
+ path.skip();
121
+ return;
122
+ }
123
+ const runtimeExpression = (0, _apidomCore.toValue)(referencingElement.reference);
124
+
125
+ // parse the runtime expression
126
+ const {
127
+ result,
128
+ tree
129
+ } = (0, _arazzoRuntimeExpression.parse)(runtimeExpression);
130
+ if (!result.success) {
131
+ throw new _apidomError.ApiDOMError(`Invalid Reusable Object reference format: "${runtimeExpression}"`);
132
+ }
133
+
134
+ // ReusableElement can only reference components
135
+ if (tree.type !== 'ComponentsExpression') {
136
+ throw new _apidomError.ApiDOMError(`Reusable Object reference "${runtimeExpression}" must be a components expression`);
137
+ }
138
+
139
+ // evaluate runtime expression as JSON Pointer to get the referenced element
140
+ const jsonPointer = (0, _apidomJsonPointer.compile)(['components', tree.field, tree.subField]);
141
+ let referencedElement;
142
+ try {
143
+ referencedElement = (0, _apidomJsonPointer.evaluate)(this.reference.value.result, jsonPointer);
144
+ } catch {
145
+ throw new _apidomError.ApiDOMError(`Reusable Object reference "${runtimeExpression}" cannot be resolved`);
146
+ }
147
+
148
+ /**
149
+ * Create a shallow clone of the referenced element to avoid modifying the original.
150
+ */
151
+ const mergedElement = (0, _apidomDatamodel.cloneShallow)(referencedElement);
152
+ // assign unique id to merged element
153
+ mergedElement.meta.set('id', identityManager.generateId());
154
+ // annotate with info about original referencing element
155
+ mergedElement.meta.set('ref-fields', {
156
+ reference: runtimeExpression,
157
+ value: (0, _apidomCore.toValue)(referencingElement.value)
158
+ });
159
+ // annotate with info about origin
160
+ mergedElement.meta.set('ref-origin', this.reference.uri);
161
+ // annotate with info about referencing element
162
+ mergedElement.meta.set('ref-referencing-element-id', identityManager.identify(referencingElement));
163
+
164
+ // override value field if present for Parameter Objects
165
+ if ((0, _apidomNsArazzo.isParameterElement)(mergedElement) && referencingElement.hasKey('value')) {
166
+ mergedElement.remove('value');
167
+ mergedElement.set('value', referencingElement.get('value'));
168
+ }
169
+
170
+ /**
171
+ * Transclude referencing element with merged referenced element.
172
+ */
173
+ path.replaceWith(mergedElement);
174
+ }
175
+ async JSONSchemaElement(path) {
176
+ const referencingElement = path.node;
177
+
178
+ // skip current referencing schema as $ref keyword was not defined
179
+ if (!(0, _apidomDatamodel.isStringElement)(referencingElement.$ref)) {
180
+ return;
181
+ }
182
+
183
+ // skip current referencing element as it's already been accessed
184
+ if (this.indirections.includes(referencingElement)) {
185
+ path.skip();
186
+ return;
187
+ }
188
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
189
+
190
+ // compute baseURI using rules around $id and $ref keywords
191
+ let reference = await this.toReference(url.unsanitize(this.reference.uri));
192
+ let {
193
+ uri: retrievalURI
194
+ } = reference;
195
+ const $refBaseURI = (0, _util.resolveSchema$refField)(retrievalURI, referencingElement);
196
+ const $refBaseURIStrippedHash = url.stripHash($refBaseURI);
197
+ const file = new _File.default({
198
+ uri: $refBaseURIStrippedHash
199
+ });
200
+ const isUnknownURI = (0, _ramda.none)(r => r.canRead(file), this.options.resolve.resolvers);
201
+ const isURL = !isUnknownURI;
202
+ let isInternalReference = url.stripHash(this.reference.uri) === $refBaseURI;
203
+ let isExternalReference = !isInternalReference;
204
+
205
+ // determining reference, proper evaluation and selection mechanism
206
+ let referencedElement;
207
+ try {
208
+ if (isUnknownURI || isURL) {
209
+ // we're dealing with canonical URI or URL with possible fragment
210
+ retrievalURI = this.toBaseURI($refBaseURI);
211
+ const selector = $refBaseURI;
212
+ const referenceAsSchema = (0, _util2.maybeRefractToJSONSchemaElement)(reference.value.result);
213
+ referencedElement = (0, _uri.evaluate)(selector, referenceAsSchema);
214
+ referencedElement = (0, _util2.maybeRefractToJSONSchemaElement)(referencedElement);
215
+ referencedElement.id = identityManager.identify(referencedElement);
216
+
217
+ // ignore resolving internal Schema Objects
218
+ if (!this.options.resolve.internal && isInternalReference) {
219
+ // skip traversing this schema element but traverse all its child elements
220
+ return;
221
+ }
222
+ // ignore resolving external Schema Objects
223
+ if (!this.options.resolve.external && isExternalReference) {
224
+ // skip traversing this schema element but traverse all its child elements
225
+ return;
226
+ }
227
+ } else {
228
+ // we're assuming here that we're dealing with JSON Pointer here
229
+ retrievalURI = this.toBaseURI($refBaseURI);
230
+ isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
231
+ isExternalReference = !isInternalReference;
232
+
233
+ // ignore resolving internal Schema Objects
234
+ if (!this.options.resolve.internal && isInternalReference) {
235
+ // skip traversing this schema element but traverse all its child elements
236
+ return;
237
+ }
238
+ // ignore resolving external Schema Objects
239
+ if (!this.options.resolve.external && isExternalReference) {
240
+ // skip traversing this schema element but traverse all its child elements
241
+ return;
242
+ }
243
+ reference = await this.toReference(url.unsanitize($refBaseURI));
244
+ const selector = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference($refBaseURI);
245
+ const referenceAsSchema = (0, _util2.maybeRefractToJSONSchemaElement)(reference.value.result);
246
+ referencedElement = (0, _apidomJsonPointer.evaluate)(referenceAsSchema, selector);
247
+ referencedElement = (0, _util2.maybeRefractToJSONSchemaElement)(referencedElement);
248
+ referencedElement.id = identityManager.identify(referencedElement);
249
+ }
250
+ } catch (error) {
251
+ /**
252
+ * JSONSchemaElement($id=URL) was not found, so we're going to try to resolve
253
+ * the URL and assume the returned response is a JSON Schema.
254
+ */
255
+ if (isURL && error instanceof _EvaluationJsonSchemaUriError.default) {
256
+ if ((0, _$anchor.isAnchor)((0, _$anchor.uriToAnchor)($refBaseURI))) {
257
+ // we're dealing with JSON Schema $anchor here
258
+ isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
259
+ isExternalReference = !isInternalReference;
260
+
261
+ // ignore resolving internal Schema Objects
262
+ if (!this.options.resolve.internal && isInternalReference) {
263
+ // skip traversing this schema element but traverse all its child elements
264
+ return;
265
+ }
266
+ // ignore resolving external Schema Objects
267
+ if (!this.options.resolve.external && isExternalReference) {
268
+ // skip traversing this schema element but traverse all its child elements
269
+ return;
270
+ }
271
+ reference = await this.toReference(url.unsanitize($refBaseURI));
272
+ const selector = (0, _$anchor.uriToAnchor)($refBaseURI);
273
+ const referenceAsSchema = (0, _util2.maybeRefractToJSONSchemaElement)(reference.value.result);
274
+ referencedElement = (0, _$anchor.evaluate)(selector, referenceAsSchema);
275
+ referencedElement = (0, _util2.maybeRefractToJSONSchemaElement)(referencedElement);
276
+ referencedElement.id = identityManager.identify(referencedElement);
277
+ } else {
278
+ // we're assuming here that we're dealing with JSON Pointer here
279
+ retrievalURI = this.toBaseURI($refBaseURI);
280
+ isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
281
+ isExternalReference = !isInternalReference;
282
+
283
+ // ignore resolving internal Schema Objects
284
+ if (!this.options.resolve.internal && isInternalReference) {
285
+ // skip traversing this schema element but traverse all its child elements
286
+ return;
287
+ }
288
+ // ignore resolving external Schema Objects
289
+ if (!this.options.resolve.external && isExternalReference) {
290
+ // skip traversing this schema element but traverse all its child elements
291
+ return;
292
+ }
293
+ reference = await this.toReference(url.unsanitize($refBaseURI));
294
+ const selector = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference($refBaseURI);
295
+ const referenceAsSchema = (0, _util2.maybeRefractToJSONSchemaElement)(reference.value.result);
296
+ referencedElement = (0, _apidomJsonPointer.evaluate)(referenceAsSchema, selector);
297
+ referencedElement = (0, _util2.maybeRefractToJSONSchemaElement)(referencedElement);
298
+ referencedElement.id = identityManager.identify(referencedElement);
299
+ }
300
+ } else {
301
+ throw error;
302
+ }
303
+ }
304
+ this.indirections.push(referencingElement);
305
+
306
+ // detect direct or indirect reference
307
+ if (referencingElement === referencedElement) {
308
+ throw new _apidomError.ApiDOMError('Recursive JSON Schema reference detected');
309
+ }
310
+
311
+ // detect maximum depth of dereferencing
312
+ if (this.indirections.length > this.options.dereference.maxDepth) {
313
+ throw new _MaximumDereferenceDepthError.default(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`);
314
+ }
315
+
316
+ // detect second deep dive into the same fragment and avoid it
317
+ if (ancestorsLineage.includes(referencedElement)) {
318
+ reference.refSet.circular = true;
319
+ if (this.options.dereference.circular === 'error') {
320
+ throw new _apidomError.ApiDOMError('Circular reference detected');
321
+ } else if (this.options.dereference.circular === 'replace') {
322
+ const refElement = new _apidomDatamodel.RefElement(referencedElement.id, {
323
+ type: 'json-schema',
324
+ uri: reference.uri,
325
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
326
+ });
327
+ const replacer = this.options.dereference.strategyOpts['arazzo-1']?.circularReplacer ?? this.options.dereference.circularReplacer;
328
+ const replacement = replacer(refElement);
329
+ this.indirections.pop();
330
+ path.replaceWith(replacement);
331
+ return;
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Dive deep into the fragment.
337
+ *
338
+ * Cases to consider:
339
+ * 1. We're crossing document boundary
340
+ * 2. Fragment is from non-root document
341
+ * 3. Fragment is a JSON Schema with $ref field. We need to follow it to get the eventual value
342
+ * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
343
+ */
344
+ const isNonRootDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
345
+ const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
346
+ if ((isExternalReference || isNonRootDocument || (0, _apidomNsArazzo.isJSONSchemaElement)(referencedElement) && (0, _apidomDatamodel.isStringElement)(referencedElement.$ref) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
347
+ // append referencing reference to ancestors lineage
348
+ directAncestors.add(referencingElement);
349
+ const visitor = new Arazzo1DereferenceVisitor({
350
+ reference,
351
+ namespace: this.namespace,
352
+ indirections: [...this.indirections],
353
+ options: this.options,
354
+ ancestors: ancestorsLineage
355
+ });
356
+ referencedElement = await (0, _apidomTraverse.traverseAsync)(referencedElement, visitor, {
357
+ mutable: true
358
+ });
359
+
360
+ // remove referencing reference from ancestors lineage
361
+ directAncestors.delete(referencingElement);
362
+ }
363
+ this.indirections.pop();
364
+
365
+ // Boolean JSON Schemas
366
+ if ((0, _apidomNsArazzo.isBooleanJSONSchemaElement)(referencedElement)) {
367
+ const booleanJsonSchemaElement = (0, _apidomDatamodel.cloneDeep)(referencedElement);
368
+ // assign unique id to merged element
369
+ booleanJsonSchemaElement.meta.set('id', identityManager.generateId());
370
+ // annotate referenced element with info about original referencing element
371
+ booleanJsonSchemaElement.meta.set('ref-fields', {
372
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
373
+ });
374
+ // annotate referenced element with info about origin
375
+ booleanJsonSchemaElement.meta.set('ref-origin', reference.uri);
376
+ // annotate fragment with info about referencing element
377
+ booleanJsonSchemaElement.meta.set('ref-referencing-element-id', (0, _apidomDatamodel.cloneDeep)(identityManager.identify(referencingElement)));
378
+ path.replaceWith(booleanJsonSchemaElement);
379
+ return;
380
+ }
381
+
382
+ /**
383
+ * Creating a new version of JSON Schema by merging fields from referenced Schema with referencing one.
384
+ */
385
+ if ((0, _apidomNsArazzo.isJSONSchemaElement)(referencedElement)) {
386
+ const mergedElement = (0, _apidomDatamodel.cloneShallow)(referencedElement);
387
+ // assign unique id to merged element
388
+ mergedElement.meta.set('id', identityManager.generateId());
389
+ // existing keywords from referencing schema overrides ones from referenced schema
390
+ referencingElement.forEach((value, keyElement, item) => {
391
+ mergedElement.remove((0, _apidomCore.toValue)(keyElement));
392
+ mergedElement.content.push(item);
393
+ });
394
+ mergedElement.remove('$ref');
395
+ // annotate referenced element with info about original referencing element
396
+ mergedElement.meta.set('ref-fields', {
397
+ $ref: (0, _apidomCore.toValue)(referencingElement.$ref)
398
+ });
399
+ // annotate fragment with info about origin
400
+ mergedElement.meta.set('ref-origin', reference.uri);
401
+ // annotate fragment with info about referencing element
402
+ mergedElement.meta.set('ref-referencing-element-id', (0, _apidomDatamodel.cloneDeep)(identityManager.identify(referencingElement)));
403
+ referencedElement = mergedElement;
404
+ }
405
+ /**
406
+ * Transclude referencing element with merged referenced element.
407
+ */
408
+ path.replaceWith(referencedElement);
409
+ }
410
+ }
411
+ var _default = exports.default = Arazzo1DereferenceVisitor;