@speclynx/apidom-reference 4.0.2 → 4.0.4

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 (186) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/apidom-reference.browser.js +15 -15
  3. package/dist/apidom-reference.browser.min.js +1 -1
  4. package/package.json +25 -25
  5. package/src/File.cjs +50 -0
  6. package/src/File.mjs +44 -0
  7. package/src/Reference.cjs +31 -0
  8. package/src/Reference.mjs +27 -0
  9. package/src/ReferenceSet.cjs +60 -0
  10. package/src/ReferenceSet.mjs +57 -0
  11. package/src/bundle/index.cjs +61 -0
  12. package/src/bundle/index.mjs +55 -0
  13. package/src/bundle/strategies/BundleStrategy.cjs +20 -0
  14. package/src/bundle/strategies/BundleStrategy.mjs +16 -0
  15. package/src/bundle/strategies/openapi-3-1/index.cjs +35 -0
  16. package/src/bundle/strategies/openapi-3-1/index.mjs +29 -0
  17. package/src/configuration/empty.cjs +9 -0
  18. package/src/configuration/empty.mjs +1 -0
  19. package/src/configuration/saturated.cjs +88 -0
  20. package/src/configuration/saturated.mjs +80 -0
  21. package/src/dereference/index.cjs +90 -0
  22. package/src/dereference/index.mjs +83 -0
  23. package/src/dereference/strategies/DereferenceStrategy.cjs +20 -0
  24. package/src/dereference/strategies/DereferenceStrategy.mjs +16 -0
  25. package/src/dereference/strategies/apidom/index.cjs +89 -0
  26. package/src/dereference/strategies/apidom/index.mjs +83 -0
  27. package/src/dereference/strategies/apidom/selectors/element-id.cjs +47 -0
  28. package/src/dereference/strategies/apidom/selectors/element-id.mjs +41 -0
  29. package/src/dereference/strategies/apidom/visitor.cjs +266 -0
  30. package/src/dereference/strategies/apidom/visitor.mjs +259 -0
  31. package/src/dereference/strategies/arazzo-1/index.cjs +109 -0
  32. package/src/dereference/strategies/arazzo-1/index.mjs +100 -0
  33. package/src/dereference/strategies/arazzo-1/selectors/$anchor.cjs +12 -0
  34. package/src/dereference/strategies/arazzo-1/selectors/$anchor.mjs +1 -0
  35. package/src/dereference/strategies/arazzo-1/selectors/uri.cjs +8 -0
  36. package/src/dereference/strategies/arazzo-1/selectors/uri.mjs +1 -0
  37. package/src/dereference/strategies/arazzo-1/source-descriptions.cjs +248 -0
  38. package/src/dereference/strategies/arazzo-1/source-descriptions.mjs +243 -0
  39. package/src/dereference/strategies/arazzo-1/util.cjs +37 -0
  40. package/src/dereference/strategies/arazzo-1/util.mjs +29 -0
  41. package/src/dereference/strategies/arazzo-1/visitor.cjs +507 -0
  42. package/src/dereference/strategies/arazzo-1/visitor.mjs +500 -0
  43. package/src/dereference/strategies/asyncapi-2/index.cjs +94 -0
  44. package/src/dereference/strategies/asyncapi-2/index.mjs +88 -0
  45. package/src/dereference/strategies/asyncapi-2/visitor.cjs +501 -0
  46. package/src/dereference/strategies/asyncapi-2/visitor.mjs +494 -0
  47. package/src/dereference/strategies/openapi-2/index.cjs +96 -0
  48. package/src/dereference/strategies/openapi-2/index.mjs +90 -0
  49. package/src/dereference/strategies/openapi-2/visitor.cjs +629 -0
  50. package/src/dereference/strategies/openapi-2/visitor.mjs +622 -0
  51. package/src/dereference/strategies/openapi-3-0/index.cjs +96 -0
  52. package/src/dereference/strategies/openapi-3-0/index.mjs +90 -0
  53. package/src/dereference/strategies/openapi-3-0/visitor.cjs +622 -0
  54. package/src/dereference/strategies/openapi-3-0/visitor.mjs +615 -0
  55. package/src/dereference/strategies/openapi-3-1/index.cjs +99 -0
  56. package/src/dereference/strategies/openapi-3-1/index.mjs +90 -0
  57. package/src/dereference/strategies/openapi-3-1/selectors/$anchor.cjs +65 -0
  58. package/src/dereference/strategies/openapi-3-1/selectors/$anchor.mjs +54 -0
  59. package/src/dereference/strategies/openapi-3-1/selectors/uri.cjs +50 -0
  60. package/src/dereference/strategies/openapi-3-1/selectors/uri.mjs +42 -0
  61. package/src/dereference/strategies/openapi-3-1/util.cjs +68 -0
  62. package/src/dereference/strategies/openapi-3-1/util.mjs +59 -0
  63. package/src/dereference/strategies/openapi-3-1/visitor.cjs +874 -0
  64. package/src/dereference/strategies/openapi-3-1/visitor.mjs +867 -0
  65. package/src/dereference/util.cjs +31 -0
  66. package/src/dereference/util.mjs +27 -0
  67. package/src/errors/BundleError.cjs +10 -0
  68. package/src/errors/BundleError.mjs +7 -0
  69. package/src/errors/DereferenceError.cjs +10 -0
  70. package/src/errors/DereferenceError.mjs +7 -0
  71. package/src/errors/EvaluationElementIdError.cjs +10 -0
  72. package/src/errors/EvaluationElementIdError.mjs +7 -0
  73. package/src/errors/EvaluationJsonSchema$anchorError.cjs +11 -0
  74. package/src/errors/EvaluationJsonSchema$anchorError.mjs +6 -0
  75. package/src/errors/EvaluationJsonSchemaUriError.cjs +11 -0
  76. package/src/errors/EvaluationJsonSchemaUriError.mjs +6 -0
  77. package/src/errors/InvalidJsonSchema$anchorError.cjs +15 -0
  78. package/src/errors/InvalidJsonSchema$anchorError.mjs +10 -0
  79. package/src/errors/JsonSchema$anchorError.cjs +10 -0
  80. package/src/errors/JsonSchema$anchorError.mjs +7 -0
  81. package/src/errors/JsonSchemaUriError.cjs +10 -0
  82. package/src/errors/JsonSchemaUriError.mjs +7 -0
  83. package/src/errors/MaximumBundleDepthError.cjs +11 -0
  84. package/src/errors/MaximumBundleDepthError.mjs +6 -0
  85. package/src/errors/MaximumDereferenceDepthError.cjs +11 -0
  86. package/src/errors/MaximumDereferenceDepthError.mjs +6 -0
  87. package/src/errors/MaximumResolveDepthError.cjs +11 -0
  88. package/src/errors/MaximumResolveDepthError.mjs +6 -0
  89. package/src/errors/ParseError.cjs +10 -0
  90. package/src/errors/ParseError.mjs +7 -0
  91. package/src/errors/ParserError.cjs +11 -0
  92. package/src/errors/ParserError.mjs +6 -0
  93. package/src/errors/PluginError.cjs +18 -0
  94. package/src/errors/PluginError.mjs +15 -0
  95. package/src/errors/ResolveError.cjs +10 -0
  96. package/src/errors/ResolveError.mjs +7 -0
  97. package/src/errors/ResolverError.cjs +11 -0
  98. package/src/errors/ResolverError.mjs +6 -0
  99. package/src/errors/UnmatchedBundleStrategyError.cjs +11 -0
  100. package/src/errors/UnmatchedBundleStrategyError.mjs +6 -0
  101. package/src/errors/UnmatchedDereferenceStrategyError.cjs +11 -0
  102. package/src/errors/UnmatchedDereferenceStrategyError.mjs +6 -0
  103. package/src/errors/UnmatchedParserError.cjs +11 -0
  104. package/src/errors/UnmatchedParserError.mjs +6 -0
  105. package/src/errors/UnmatchedResolveStrategyError.cjs +11 -0
  106. package/src/errors/UnmatchedResolveStrategyError.mjs +6 -0
  107. package/src/errors/UnmatchedResolverError.cjs +11 -0
  108. package/src/errors/UnmatchedResolverError.mjs +6 -0
  109. package/src/errors/UnresolvableReferenceError.cjs +11 -0
  110. package/src/errors/UnresolvableReferenceError.mjs +6 -0
  111. package/src/index.cjs +146 -0
  112. package/src/index.mjs +103 -0
  113. package/src/options/index.cjs +194 -0
  114. package/src/options/index.mjs +191 -0
  115. package/src/options/util.cjs +24 -0
  116. package/src/options/util.mjs +19 -0
  117. package/src/parse/index.cjs +69 -0
  118. package/src/parse/index.mjs +63 -0
  119. package/src/parse/parsers/Parser.cjs +62 -0
  120. package/src/parse/parsers/Parser.mjs +58 -0
  121. package/src/parse/parsers/apidom-json/index.cjs +70 -0
  122. package/src/parse/parsers/apidom-json/index.mjs +64 -0
  123. package/src/parse/parsers/arazzo-json-1/index.cjs +62 -0
  124. package/src/parse/parsers/arazzo-json-1/index.mjs +56 -0
  125. package/src/parse/parsers/arazzo-json-1/source-descriptions.cjs +221 -0
  126. package/src/parse/parsers/arazzo-json-1/source-descriptions.mjs +214 -0
  127. package/src/parse/parsers/arazzo-yaml-1/index.cjs +62 -0
  128. package/src/parse/parsers/arazzo-yaml-1/index.mjs +56 -0
  129. package/src/parse/parsers/arazzo-yaml-1/source-descriptions.cjs +12 -0
  130. package/src/parse/parsers/arazzo-yaml-1/source-descriptions.mjs +7 -0
  131. package/src/parse/parsers/asyncapi-json-2/index.cjs +54 -0
  132. package/src/parse/parsers/asyncapi-json-2/index.mjs +48 -0
  133. package/src/parse/parsers/asyncapi-yaml-2/index.cjs +54 -0
  134. package/src/parse/parsers/asyncapi-yaml-2/index.mjs +48 -0
  135. package/src/parse/parsers/binary/index-browser.cjs +56 -0
  136. package/src/parse/parsers/binary/index-browser.mjs +50 -0
  137. package/src/parse/parsers/binary/index-node.cjs +51 -0
  138. package/src/parse/parsers/binary/index-node.mjs +45 -0
  139. package/src/parse/parsers/json/index.cjs +53 -0
  140. package/src/parse/parsers/json/index.mjs +47 -0
  141. package/src/parse/parsers/openapi-json-2/index.cjs +54 -0
  142. package/src/parse/parsers/openapi-json-2/index.mjs +48 -0
  143. package/src/parse/parsers/openapi-json-3-0/index.cjs +54 -0
  144. package/src/parse/parsers/openapi-json-3-0/index.mjs +48 -0
  145. package/src/parse/parsers/openapi-json-3-1/index.cjs +54 -0
  146. package/src/parse/parsers/openapi-json-3-1/index.mjs +48 -0
  147. package/src/parse/parsers/openapi-yaml-2/index.cjs +54 -0
  148. package/src/parse/parsers/openapi-yaml-2/index.mjs +48 -0
  149. package/src/parse/parsers/openapi-yaml-3-0/index.cjs +54 -0
  150. package/src/parse/parsers/openapi-yaml-3-0/index.mjs +48 -0
  151. package/src/parse/parsers/openapi-yaml-3-1/index.cjs +54 -0
  152. package/src/parse/parsers/openapi-yaml-3-1/index.mjs +48 -0
  153. package/src/parse/parsers/yaml-1-2/index.cjs +56 -0
  154. package/src/parse/parsers/yaml-1-2/index.mjs +50 -0
  155. package/src/resolve/index.cjs +67 -0
  156. package/src/resolve/index.mjs +60 -0
  157. package/src/resolve/resolvers/HTTPResolver.cjs +45 -0
  158. package/src/resolve/resolvers/HTTPResolver.mjs +37 -0
  159. package/src/resolve/resolvers/Resolver.cjs +20 -0
  160. package/src/resolve/resolvers/Resolver.mjs +16 -0
  161. package/src/resolve/resolvers/file/index-browser.cjs +24 -0
  162. package/src/resolve/resolvers/file/index-browser.mjs +19 -0
  163. package/src/resolve/resolvers/file/index-node.cjs +49 -0
  164. package/src/resolve/resolvers/file/index-node.mjs +42 -0
  165. package/src/resolve/resolvers/http-axios/cache/MemoryCache.cjs +41 -0
  166. package/src/resolve/resolvers/http-axios/cache/MemoryCache.mjs +37 -0
  167. package/src/resolve/resolvers/http-axios/index.cjs +113 -0
  168. package/src/resolve/resolvers/http-axios/index.mjs +105 -0
  169. package/src/resolve/strategies/ResolveStrategy.cjs +20 -0
  170. package/src/resolve/strategies/ResolveStrategy.mjs +16 -0
  171. package/src/resolve/strategies/apidom/index.cjs +49 -0
  172. package/src/resolve/strategies/apidom/index.mjs +43 -0
  173. package/src/resolve/strategies/asyncapi-2/index.cjs +49 -0
  174. package/src/resolve/strategies/asyncapi-2/index.mjs +43 -0
  175. package/src/resolve/strategies/openapi-2/index.cjs +49 -0
  176. package/src/resolve/strategies/openapi-2/index.mjs +43 -0
  177. package/src/resolve/strategies/openapi-3-0/index.cjs +49 -0
  178. package/src/resolve/strategies/openapi-3-0/index.mjs +43 -0
  179. package/src/resolve/strategies/openapi-3-1/index.cjs +49 -0
  180. package/src/resolve/strategies/openapi-3-1/index.mjs +43 -0
  181. package/src/resolve/util.cjs +37 -0
  182. package/src/resolve/util.mjs +30 -0
  183. package/src/util/plugins.cjs +39 -0
  184. package/src/util/plugins.mjs +34 -0
  185. package/src/util/url.cjs +288 -0
  186. package/src/util/url.mjs +274 -0
@@ -0,0 +1,867 @@
1
+ import { propEq, none } from 'ramda';
2
+ import { isUndefined } from 'ramda-adjunct';
3
+ import { isElement, isStringElement, isObjectElement, RefElement, cloneShallow, cloneDeep } from '@speclynx/apidom-datamodel';
4
+ import { toValue, fixedFields, toYAML } from '@speclynx/apidom-core';
5
+ import { ApiDOMStructuredError } from '@speclynx/apidom-error';
6
+ import { traverse, traverseAsync, find } from '@speclynx/apidom-traverse';
7
+ import { evaluate as jsonPointerEvaluate, URIFragmentIdentifier } from '@speclynx/apidom-json-pointer';
8
+ import { isReferenceLikeElement, isPathItemElement, isReferenceElement, isSchemaElement, isOperationElement, isBooleanJSONSchemaElement, refract, refractReference, refractPathItem, refractOperation } from '@speclynx/apidom-ns-openapi-3-1';
9
+ import { isAnchor, uriToAnchor, evaluate as $anchorEvaluate } from "./selectors/$anchor.mjs";
10
+ import { evaluate as uriEvaluate } from "./selectors/uri.mjs";
11
+ import MaximumDereferenceDepthError from "../../../errors/MaximumDereferenceDepthError.mjs";
12
+ import MaximumResolveDepthError from "../../../errors/MaximumResolveDepthError.mjs";
13
+ import UnresolvableReferenceError from "../../../errors/UnresolvableReferenceError.mjs";
14
+ import EvaluationJsonSchemaUriError from "../../../errors/EvaluationJsonSchemaUriError.mjs";
15
+ import * as url from "../../../util/url.mjs";
16
+ import parse from "../../../parse/index.mjs";
17
+ import Reference from "../../../Reference.mjs";
18
+ import File from "../../../File.mjs";
19
+ import { resolveSchema$refField, maybeRefractToSchemaElement } from "./util.mjs";
20
+ import { AncestorLineage } from "../../util.mjs";
21
+ /**
22
+ * @public
23
+ */
24
+ /**
25
+ * @public
26
+ */
27
+ class OpenAPI3_1DereferenceVisitor {
28
+ indirections;
29
+ reference;
30
+ options;
31
+ refractCache;
32
+
33
+ /**
34
+ * Tracks element ancestors across dive-deep traversal boundaries.
35
+ * Used for cycle detection: if a referenced element is found in
36
+ * the ancestor lineage, a circular reference is detected.
37
+ */
38
+ ancestors;
39
+ constructor({
40
+ reference,
41
+ options,
42
+ indirections = [],
43
+ refractCache = new WeakMap(),
44
+ ancestors = new AncestorLineage()
45
+ }) {
46
+ this.indirections = indirections;
47
+ this.reference = reference;
48
+ this.options = options;
49
+ this.refractCache = refractCache;
50
+ this.ancestors = new AncestorLineage(...ancestors);
51
+ }
52
+ toAncestorLineage(path) {
53
+ const ancestorNodes = path.getAncestorNodes();
54
+ const directAncestors = new Set(ancestorNodes.filter(isElement));
55
+ const ancestorsLineage = new AncestorLineage(...this.ancestors, directAncestors);
56
+ return [ancestorsLineage, directAncestors];
57
+ }
58
+ toBaseURI(uri) {
59
+ return url.resolve(this.reference.uri, url.sanitize(url.stripHash(uri)));
60
+ }
61
+ async toReference(uri) {
62
+ // detect maximum depth of resolution
63
+ if (this.reference.depth >= this.options.resolve.maxDepth) {
64
+ throw new MaximumResolveDepthError(`Maximum resolution depth of ${this.options.resolve.maxDepth} has been exceeded by file "${this.reference.uri}"`, {
65
+ maxDepth: this.options.resolve.maxDepth,
66
+ uri: this.reference.uri
67
+ });
68
+ }
69
+ const baseURI = this.toBaseURI(uri);
70
+ const {
71
+ refSet
72
+ } = this.reference;
73
+
74
+ // we've already processed this Reference in past
75
+ if (refSet.has(baseURI)) {
76
+ return refSet.find(propEq(baseURI, 'uri'));
77
+ }
78
+ const parseResult = await parse(url.unsanitize(baseURI), {
79
+ ...this.options,
80
+ parse: {
81
+ ...this.options.parse,
82
+ mediaType: 'text/plain'
83
+ }
84
+ });
85
+
86
+ // register new mutable reference with a refSet
87
+ //
88
+ // NOTE(known limitation): the mutable reference is mutated in place during traversal
89
+ // (via `{ mutable: true }`). When an external document evaluates a JSON pointer back
90
+ // into this document, it may receive an already-resolved element instead of the original
91
+ // $ref. That resolved element was produced using the entry document's resolution context
92
+ // (ancestors, indirections), which may differ from the external document's context.
93
+ // This can affect cycle detection in rare cross-document circular reference patterns.
94
+ //
95
+ // Remediation: evaluate JSON pointers against the immutable (original) parse tree
96
+ // instead of the mutable working copy. The `immutable://` reference below preserves
97
+ // the original tree and could be used for pointer evaluation, ensuring every resolution
98
+ // context always sees raw, unresolved elements and processes them with its own
99
+ // ancestors/indirections. The trade-off is that elements referenced by multiple
100
+ // documents would be resolved once per context instead of being reused.
101
+ const mutableReference = new Reference({
102
+ uri: baseURI,
103
+ value: this.options.dereference.immutable ? cloneDeep(parseResult) : parseResult,
104
+ depth: this.reference.depth + 1
105
+ });
106
+ refSet.add(mutableReference);
107
+ if (this.options.dereference.immutable) {
108
+ // register new immutable reference with original parseResult
109
+ const immutableReference = new Reference({
110
+ uri: `immutable://${baseURI}`,
111
+ value: parseResult,
112
+ depth: this.reference.depth + 1
113
+ });
114
+ refSet.add(immutableReference);
115
+ }
116
+ return mutableReference;
117
+ }
118
+
119
+ /**
120
+ * Handles an error according to the continueOnError option.
121
+ *
122
+ * For new errors: wraps in UnresolvableReferenceError with structured context
123
+ * (type, uri, location, codeFrame, refFieldName, refFieldValue, trace).
124
+ * For errors already wrapped by a nested visitor: prepends the current hop to the trace.
125
+ *
126
+ * Inner/intermediate visitors always throw to let the trace accumulate.
127
+ * Only the entry document visitor respects continueOnError (callback/swallow/throw).
128
+ */
129
+ handleError(message, error, referencingElement, refFieldName, refFieldValue, visitorPath) {
130
+ const {
131
+ continueOnError
132
+ } = this.options.dereference;
133
+ const isEntryDocument = url.stripHash(this.reference.refSet?.rootRef?.uri ?? '') === this.reference.uri;
134
+ const uri = this.reference.uri;
135
+ const type = referencingElement.element;
136
+ const codeFrame = toYAML(referencingElement);
137
+
138
+ // find element location by identity in the document tree.
139
+ // guarded: this.reference.value may not be a ParseResultElement or may lack a result.
140
+ // falls back to visitorPath which may produce an incomplete path when
141
+ // dereferenceApiDOM is called with a fragment (cloneShallow creates a new root identity).
142
+ let location;
143
+ const root = this.reference.value.result;
144
+ if (isElement(root)) {
145
+ traverse(root, {
146
+ enter: p => {
147
+ if (p.node === referencingElement || this.refractCache.get(p.node) === referencingElement) {
148
+ location = p.formatPath();
149
+ p.stop();
150
+ }
151
+ }
152
+ });
153
+ }
154
+ location ??= visitorPath.formatPath();
155
+ const hop = {
156
+ uri,
157
+ type,
158
+ refFieldName,
159
+ refFieldValue,
160
+ location,
161
+ codeFrame
162
+ };
163
+
164
+ // enrich existing error from nested visitor or create new one
165
+ let unresolvedError;
166
+ if (error instanceof UnresolvableReferenceError) {
167
+ // prefix relative locations for entries belonging to the referenced document
168
+ const refBaseURI = this.toBaseURI(refFieldValue);
169
+ const fragment = URIFragmentIdentifier.fromURIReference(refFieldValue);
170
+ if (fragment) {
171
+ if (refBaseURI === error.uri && error.location) {
172
+ error.location = fragment + error.location;
173
+ }
174
+ for (const h of error.trace) {
175
+ if (h.uri === refBaseURI && h.location) h.location = fragment + h.location;
176
+ }
177
+ }
178
+ // @ts-ignore
179
+ error.trace = [hop, ...error.trace];
180
+ unresolvedError = error;
181
+ } else {
182
+ unresolvedError = new UnresolvableReferenceError(message, {
183
+ cause: error,
184
+ type,
185
+ uri,
186
+ location,
187
+ codeFrame,
188
+ refFieldName,
189
+ refFieldValue,
190
+ trace: []
191
+ });
192
+ }
193
+ if (!isEntryDocument || continueOnError === false) throw unresolvedError;
194
+ if (typeof continueOnError === 'function') continueOnError(unresolvedError);
195
+ }
196
+ async ReferenceElement(path) {
197
+ const referencingElement = path.node;
198
+
199
+ // skip current referencing element as it's already been accessed
200
+ if (this.indirections.includes(referencingElement)) {
201
+ path.skip();
202
+ return;
203
+ }
204
+ const retrievalURI = this.toBaseURI(toValue(referencingElement.$ref));
205
+ const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
206
+ const isExternalReference = !isInternalReference;
207
+
208
+ // ignore resolving internal Reference Objects
209
+ if (!this.options.resolve.internal && isInternalReference) {
210
+ // skip traversing this reference element and all it's child elements
211
+ path.skip();
212
+ return;
213
+ }
214
+ // ignore resolving external Reference Objects
215
+ if (!this.options.resolve.external && isExternalReference) {
216
+ // skip traversing this reference element and all it's child elements
217
+ path.skip();
218
+ return;
219
+ }
220
+ const $refBaseURI = url.resolve(retrievalURI, toValue(referencingElement.$ref));
221
+ const indirectionsSize = this.indirections.length;
222
+ try {
223
+ const reference = await this.toReference(toValue(referencingElement.$ref));
224
+ this.indirections.push(referencingElement);
225
+ const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
226
+
227
+ // possibly non-semantic fragment
228
+ let referencedElement = jsonPointerEvaluate(reference.value.result, jsonPointer);
229
+
230
+ // applying semantics to a fragment
231
+ const referencedElementType = referencingElement.meta.get('referenced-element');
232
+ if (referencedElement.element !== referencedElementType && !isReferenceElement(referencedElement)) {
233
+ if (this.refractCache.has(referencedElement)) {
234
+ referencedElement = this.refractCache.get(referencedElement);
235
+ } else if (isReferenceLikeElement(referencedElement)) {
236
+ // handling generic indirect references
237
+ const sourceElement = referencedElement;
238
+ referencedElement = refractReference(referencedElement);
239
+ referencedElement.meta.set('referenced-element', referencedElementType);
240
+ this.refractCache.set(sourceElement, referencedElement);
241
+ } else {
242
+ // handling direct references
243
+ const sourceElement = referencedElement;
244
+ referencedElement = refract(referencedElement, {
245
+ element: referencedElementType
246
+ });
247
+ this.refractCache.set(sourceElement, referencedElement);
248
+ }
249
+ }
250
+
251
+ // detect direct or indirect reference
252
+ if (referencingElement === referencedElement) {
253
+ throw new ApiDOMStructuredError('Recursive Reference Object detected', {
254
+ $ref: toValue(referencingElement.$ref)
255
+ });
256
+ }
257
+
258
+ // detect maximum depth of dereferencing
259
+ if (this.indirections.length > this.options.dereference.maxDepth) {
260
+ throw new MaximumDereferenceDepthError(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
261
+ maxDepth: this.options.dereference.maxDepth,
262
+ uri: this.reference.uri
263
+ });
264
+ }
265
+
266
+ // detect cross-boundary cycle
267
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
268
+ if (ancestorsLineage.includes(referencedElement)) {
269
+ reference.refSet.circular = true;
270
+ if (this.options.dereference.circular === 'error') {
271
+ throw new ApiDOMStructuredError('Circular reference detected', {
272
+ $ref: toValue(referencingElement.$ref)
273
+ });
274
+ } else if (this.options.dereference.circular === 'replace') {
275
+ const refElement = new RefElement($refBaseURI, {
276
+ type: referencingElement.element,
277
+ uri: reference.uri,
278
+ $ref: toValue(referencingElement.$ref)
279
+ });
280
+ const replacer = this.options.dereference.strategyOpts['openapi-3-1']?.circularReplacer ?? this.options.dereference.circularReplacer;
281
+ const replacement = replacer(refElement);
282
+ path.replaceWith(replacement);
283
+ return;
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Dive deep into the fragment.
289
+ *
290
+ * Cases to consider:
291
+ * 1. We're crossing document boundary
292
+ * 2. Fragment is from non-entry document
293
+ * 3. Fragment is a Reference Object. We need to follow it to get the eventual value
294
+ * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
295
+ */
296
+ const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
297
+ const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
298
+ if ((isExternalReference || isNonEntryDocument || isReferenceElement(referencedElement) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
299
+ directAncestors.add(referencingElement);
300
+ const visitor = new OpenAPI3_1DereferenceVisitor({
301
+ reference,
302
+ indirections: [...this.indirections],
303
+ options: this.options,
304
+ refractCache: this.refractCache,
305
+ ancestors: ancestorsLineage
306
+ });
307
+ referencedElement = await traverseAsync(referencedElement, visitor, {
308
+ mutable: true
309
+ });
310
+ directAncestors.delete(referencingElement);
311
+ }
312
+
313
+ /**
314
+ * Creating a new version of referenced element to avoid modifying the original one.
315
+ */
316
+ const mergedElement = cloneShallow(referencedElement);
317
+ // annotate fragment with info about original Reference element
318
+ mergedElement.meta.set('ref-fields', {
319
+ $ref: toValue(referencingElement.$ref),
320
+ // @ts-ignore
321
+ description: toValue(referencingElement.description),
322
+ // @ts-ignore
323
+ summary: toValue(referencingElement.summary)
324
+ });
325
+ // annotate fragment with info about origin and type
326
+ mergedElement.meta.set('ref-origin', reference.uri);
327
+ mergedElement.meta.set('ref-type', referencingElement.element);
328
+
329
+ // override description and summary (outer has higher priority then inner)
330
+ if (isObjectElement(referencedElement) && isObjectElement(mergedElement)) {
331
+ const fields = fixedFields(referencedElement, {
332
+ indexed: true
333
+ });
334
+ if (referencingElement.hasKey('description') && Object.hasOwn(fields, 'description')) {
335
+ mergedElement.remove('description');
336
+ mergedElement.set('description', referencingElement.get('description'));
337
+ }
338
+ if (referencingElement.hasKey('summary') && Object.hasOwn(fields, 'summary')) {
339
+ mergedElement.remove('summary');
340
+ mergedElement.set('summary', referencingElement.get('summary'));
341
+ }
342
+ }
343
+
344
+ /**
345
+ * Transclude referencing element with merged referenced element.
346
+ */
347
+ path.replaceWith(mergedElement);
348
+ } catch (error) {
349
+ const $ref = toValue(referencingElement.$ref);
350
+ this.handleError(`Error while dereferencing Reference Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
351
+ } finally {
352
+ if (this.indirections.length > indirectionsSize) this.indirections.pop();
353
+ }
354
+ }
355
+ async PathItemElement(path) {
356
+ const referencingElement = path.node;
357
+
358
+ // ignore PathItemElement without $ref field
359
+ if (!isStringElement(referencingElement.$ref)) {
360
+ return;
361
+ }
362
+
363
+ // skip current referencing element as it's already been accessed
364
+ if (this.indirections.includes(referencingElement)) {
365
+ path.skip();
366
+ return;
367
+ }
368
+ const retrievalURI = this.toBaseURI(toValue(referencingElement.$ref));
369
+ const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
370
+ const isExternalReference = !isInternalReference;
371
+
372
+ // ignore resolving internal Path Item Objects
373
+ if (!this.options.resolve.internal && isInternalReference) {
374
+ // skip traversing this Path Item element but traverse all it's child elements
375
+ return;
376
+ }
377
+ // ignore resolving external Path Item Objects
378
+ if (!this.options.resolve.external && isExternalReference) {
379
+ // skip traversing this Path Item element but traverse all it's child elements
380
+ return;
381
+ }
382
+ const $refBaseURI = url.resolve(retrievalURI, toValue(referencingElement.$ref));
383
+ const indirectionsSize = this.indirections.length;
384
+ try {
385
+ const reference = await this.toReference(toValue(referencingElement.$ref));
386
+ this.indirections.push(referencingElement);
387
+ const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
388
+
389
+ // possibly non-semantic referenced element
390
+ let referencedElement = jsonPointerEvaluate(reference.value.result, jsonPointer);
391
+
392
+ // applying semantics to a referenced element
393
+ if (!isPathItemElement(referencedElement)) {
394
+ if (this.refractCache.has(referencedElement)) {
395
+ referencedElement = this.refractCache.get(referencedElement);
396
+ } else {
397
+ const sourceElement = referencedElement;
398
+ referencedElement = refractPathItem(referencedElement);
399
+ this.refractCache.set(sourceElement, referencedElement);
400
+ }
401
+ }
402
+
403
+ // detect direct or indirect reference
404
+ if (referencingElement === referencedElement) {
405
+ throw new ApiDOMStructuredError('Recursive Path Item Object reference detected', {
406
+ $ref: toValue(referencingElement.$ref)
407
+ });
408
+ }
409
+
410
+ // detect maximum depth of dereferencing
411
+ if (this.indirections.length > this.options.dereference.maxDepth) {
412
+ throw new MaximumDereferenceDepthError(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
413
+ maxDepth: this.options.dereference.maxDepth,
414
+ uri: this.reference.uri
415
+ });
416
+ }
417
+
418
+ // detect cross-boundary cycle
419
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
420
+ if (ancestorsLineage.includes(referencedElement)) {
421
+ reference.refSet.circular = true;
422
+ if (this.options.dereference.circular === 'error') {
423
+ throw new ApiDOMStructuredError('Circular reference detected', {
424
+ $ref: toValue(referencingElement.$ref)
425
+ });
426
+ } else if (this.options.dereference.circular === 'replace') {
427
+ const refElement = new RefElement($refBaseURI, {
428
+ type: referencingElement.element,
429
+ uri: reference.uri,
430
+ $ref: toValue(referencingElement.$ref)
431
+ });
432
+ const replacer = this.options.dereference.strategyOpts['openapi-3-1']?.circularReplacer ?? this.options.dereference.circularReplacer;
433
+ const replacement = replacer(refElement);
434
+ path.replaceWith(replacement);
435
+ return;
436
+ }
437
+ }
438
+
439
+ /**
440
+ * Dive deep into the fragment.
441
+ *
442
+ * Cases to consider:
443
+ * 1. We're crossing document boundary
444
+ * 2. Fragment is from non-entry document
445
+ * 3. Fragment is a Path Item Object with $ref field. We need to follow it to get the eventual value
446
+ * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
447
+ */
448
+ const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
449
+ const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
450
+ if ((isExternalReference || isNonEntryDocument || isPathItemElement(referencedElement) && isStringElement(referencedElement.$ref) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
451
+ directAncestors.add(referencingElement);
452
+ const visitor = new OpenAPI3_1DereferenceVisitor({
453
+ reference,
454
+ indirections: [...this.indirections],
455
+ options: this.options,
456
+ refractCache: this.refractCache,
457
+ ancestors: ancestorsLineage
458
+ });
459
+ referencedElement = await traverseAsync(referencedElement, visitor, {
460
+ mutable: true
461
+ });
462
+ directAncestors.delete(referencingElement);
463
+ }
464
+
465
+ /**
466
+ * Creating a new version of Path Item by merging fields from referenced Path Item with referencing one.
467
+ */
468
+ if (isPathItemElement(referencedElement)) {
469
+ const mergedElement = cloneShallow(referencedElement);
470
+ // existing keywords from referencing PathItemElement overrides ones from referenced element
471
+ referencingElement.forEach((value, keyElement, item) => {
472
+ mergedElement.remove(toValue(keyElement));
473
+ mergedElement.content.push(item);
474
+ });
475
+ mergedElement.remove('$ref');
476
+
477
+ // annotate referenced element with info about original referencing element
478
+ mergedElement.meta.set('ref-fields', {
479
+ $ref: toValue(referencingElement.$ref)
480
+ });
481
+ // annotate referenced element with info about origin and type
482
+ mergedElement.meta.set('ref-origin', reference.uri);
483
+ mergedElement.meta.set('ref-type', referencingElement.element);
484
+ referencedElement = mergedElement;
485
+ }
486
+
487
+ /**
488
+ * Transclude referencing element with merged referenced element.
489
+ */
490
+ path.replaceWith(referencedElement);
491
+ } catch (error) {
492
+ const $ref = toValue(referencingElement.$ref);
493
+ this.handleError(`Error while dereferencing Path Item Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
494
+ } finally {
495
+ if (this.indirections.length > indirectionsSize) this.indirections.pop();
496
+ }
497
+ }
498
+ async LinkElement(path) {
499
+ const linkElement = path.node;
500
+
501
+ // ignore LinkElement without operationRef or operationId field
502
+ if (!isStringElement(linkElement.operationRef) && !isStringElement(linkElement.operationId)) {
503
+ return;
504
+ }
505
+
506
+ // operationRef and operationId fields are mutually exclusive
507
+ if (isStringElement(linkElement.operationRef) && isStringElement(linkElement.operationId)) {
508
+ throw new ApiDOMStructuredError('LinkElement operationRef and operationId fields are mutually exclusive', {
509
+ operationRef: toValue(linkElement.operationRef),
510
+ operationId: toValue(linkElement.operationId)
511
+ });
512
+ }
513
+ try {
514
+ let operationElement;
515
+ if (isStringElement(linkElement.operationRef)) {
516
+ // possibly non-semantic referenced element
517
+ const jsonPointer = URIFragmentIdentifier.fromURIReference(toValue(linkElement.operationRef));
518
+ const retrievalURI = this.toBaseURI(toValue(linkElement.operationRef));
519
+ const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
520
+ const isExternalReference = !isInternalReference;
521
+
522
+ // ignore resolving internal Operation Object reference
523
+ if (!this.options.resolve.internal && isInternalReference) {
524
+ // skip traversing this Link element but traverse all it's child elements
525
+ return;
526
+ }
527
+ // ignore resolving external Operation Object reference
528
+ if (!this.options.resolve.external && isExternalReference) {
529
+ // skip traversing this Link element but traverse all it's child elements
530
+ return;
531
+ }
532
+ const reference = await this.toReference(toValue(linkElement.operationRef));
533
+ operationElement = jsonPointerEvaluate(reference.value.result, jsonPointer);
534
+ // applying semantics to a referenced element
535
+ if (!isOperationElement(operationElement)) {
536
+ if (this.refractCache.has(operationElement)) {
537
+ operationElement = this.refractCache.get(operationElement);
538
+ } else {
539
+ const sourceElement = operationElement;
540
+ operationElement = refractOperation(operationElement);
541
+ this.refractCache.set(sourceElement, operationElement);
542
+ }
543
+ }
544
+ // create shallow clone to be able to annotate with metadata
545
+ operationElement = cloneShallow(operationElement);
546
+ // annotate operation element with info about origin and type
547
+ operationElement.meta.set('ref-origin', reference.uri);
548
+ operationElement.meta.set('ref-type', linkElement.element);
549
+ const linkElementCopy = cloneShallow(linkElement);
550
+ linkElementCopy.operationRef?.meta.set('operation', operationElement);
551
+
552
+ /**
553
+ * Transclude Link Object containing Operation Object in its meta.
554
+ */
555
+ path.replaceWith(linkElementCopy);
556
+ return;
557
+ }
558
+ if (isStringElement(linkElement.operationId)) {
559
+ const operationId = toValue(linkElement.operationId);
560
+ const reference = await this.toReference(url.unsanitize(this.reference.uri));
561
+ const operationPath = find(reference.value.result, path => isOperationElement(path.node) && isElement(path.node.operationId) && path.node.operationId.equals(operationId));
562
+ operationElement = operationPath?.node;
563
+ // OperationElement not found by its operationId
564
+ if (isUndefined(operationElement)) {
565
+ throw new ApiDOMStructuredError(`OperationElement(operationId=${operationId}) not found`, {
566
+ operationId
567
+ });
568
+ }
569
+ const linkElementCopy = cloneShallow(linkElement);
570
+ linkElementCopy.operationId?.meta.set('operation', operationElement);
571
+
572
+ /**
573
+ * Transclude Link Object containing Operation Object in its meta.
574
+ */
575
+ path.replaceWith(linkElementCopy);
576
+ }
577
+ } catch (error) {
578
+ const refFieldName = isStringElement(linkElement.operationRef) ? 'operationRef' : 'operationId';
579
+ const refFieldValue = isStringElement(linkElement.operationRef) ? toValue(linkElement.operationRef) : toValue(linkElement.operationId);
580
+ this.handleError(`Error while dereferencing Link Object. Cannot resolve ${refFieldName} "${refFieldValue}": ${error.message}`, error, linkElement, refFieldName, refFieldValue, path);
581
+ }
582
+ }
583
+ async ExampleElement(path) {
584
+ const exampleElement = path.node;
585
+
586
+ // ignore ExampleElement without externalValue field
587
+ if (!isStringElement(exampleElement.externalValue)) {
588
+ return;
589
+ }
590
+
591
+ // value and externalValue fields are mutually exclusive
592
+ if (exampleElement.hasKey('value') && isStringElement(exampleElement.externalValue)) {
593
+ throw new ApiDOMStructuredError('ExampleElement value and externalValue fields are mutually exclusive', {
594
+ value: toValue(exampleElement.value),
595
+ externalValue: toValue(exampleElement.externalValue)
596
+ });
597
+ }
598
+ const retrievalURI = this.toBaseURI(toValue(exampleElement.externalValue));
599
+ const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
600
+ const isExternalReference = !isInternalReference;
601
+
602
+ // ignore resolving internal Example Objects
603
+ if (!this.options.resolve.internal && isInternalReference) {
604
+ // skip traversing this Example element but traverse all it's child elements
605
+ return;
606
+ }
607
+ // ignore resolving external Example Objects
608
+ if (!this.options.resolve.external && isExternalReference) {
609
+ // skip traversing this Example element but traverse all it's child elements
610
+ return;
611
+ }
612
+ try {
613
+ const reference = await this.toReference(toValue(exampleElement.externalValue));
614
+
615
+ // shallow clone of the referenced element
616
+ const valueElement = 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 = 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 = toValue(exampleElement.externalValue);
629
+ this.handleError(`Error while dereferencing Example Object. Cannot resolve externalValue "${externalValue}": ${error.message}`, error, exampleElement, 'externalValue', externalValue, path);
630
+ }
631
+ }
632
+ async SchemaElement(path) {
633
+ const referencingElement = path.node;
634
+
635
+ // skip current referencing schema as $ref keyword was not defined
636
+ if (!isStringElement(referencingElement.$ref)) {
637
+ return;
638
+ }
639
+
640
+ // skip current referencing element as it's already been accessed
641
+ if (this.indirections.includes(referencingElement)) {
642
+ path.skip();
643
+ return;
644
+ }
645
+ const indirectionsSize = this.indirections.length;
646
+ try {
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 = resolveSchema$refField(retrievalURI, referencingElement);
653
+ const $refBaseURIStrippedHash = url.stripHash($refBaseURI);
654
+ const file = new File({
655
+ uri: $refBaseURIStrippedHash
656
+ });
657
+ const isUnknownURI = 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 = maybeRefractToSchemaElement(reference.value.result);
670
+ referencedElement = uriEvaluate(selector, referenceAsSchema);
671
+ referencedElement = maybeRefractToSchemaElement(referencedElement);
672
+
673
+ // ignore resolving internal Schema Objects
674
+ if (!this.options.resolve.internal && isInternalReference) {
675
+ // skip traversing this schema element but traverse all it's child elements
676
+ return;
677
+ }
678
+ // ignore resolving external Schema Objects
679
+ if (!this.options.resolve.external && isExternalReference) {
680
+ // skip traversing this schema element but traverse all it's child elements
681
+ return;
682
+ }
683
+ } else {
684
+ // we're assuming here that we're dealing with JSON Pointer here
685
+ retrievalURI = this.toBaseURI($refBaseURI);
686
+ isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
687
+ isExternalReference = !isInternalReference;
688
+
689
+ // ignore resolving internal Schema Objects
690
+ if (!this.options.resolve.internal && isInternalReference) {
691
+ // skip traversing this schema element but traverse all it's child elements
692
+ return;
693
+ }
694
+ // ignore resolving external Schema Objects
695
+ if (!this.options.resolve.external && isExternalReference) {
696
+ // skip traversing this schema element but traverse all it's child elements
697
+ return;
698
+ }
699
+ reference = await this.toReference(url.unsanitize($refBaseURI));
700
+ const selector = URIFragmentIdentifier.fromURIReference($refBaseURI);
701
+ const referenceAsSchema = maybeRefractToSchemaElement(reference.value.result);
702
+ referencedElement = jsonPointerEvaluate(referenceAsSchema, selector);
703
+ referencedElement = maybeRefractToSchemaElement(referencedElement);
704
+ }
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) {
711
+ if (isAnchor(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 = uriToAnchor($refBaseURI);
728
+ const referenceAsSchema = maybeRefractToSchemaElement(reference.value.result);
729
+ referencedElement = $anchorEvaluate(selector, referenceAsSchema);
730
+ referencedElement = 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 = URIFragmentIdentifier.fromURIReference($refBaseURI);
749
+ const referenceAsSchema = maybeRefractToSchemaElement(reference.value.result);
750
+ referencedElement = jsonPointerEvaluate(referenceAsSchema, selector);
751
+ referencedElement = maybeRefractToSchemaElement(referencedElement);
752
+ }
753
+ } else {
754
+ throw error;
755
+ }
756
+ }
757
+ this.indirections.push(referencingElement);
758
+
759
+ // detect direct or indirect reference
760
+ if (referencingElement === referencedElement) {
761
+ throw new ApiDOMStructuredError('Recursive Schema Object reference detected', {
762
+ $ref: toValue(referencingElement.$ref)
763
+ });
764
+ }
765
+
766
+ // detect maximum depth of dereferencing
767
+ if (this.indirections.length > this.options.dereference.maxDepth) {
768
+ throw new MaximumDereferenceDepthError(`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 ApiDOMStructuredError('Circular reference detected', {
780
+ $ref: toValue(referencingElement.$ref)
781
+ });
782
+ } else if (this.options.dereference.circular === 'replace') {
783
+ const refElement = new RefElement($refBaseURI, {
784
+ type: referencingElement.element,
785
+ uri: reference.uri,
786
+ $ref: 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 || isSchemaElement(referencedElement) && 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 traverseAsync(referencedElement, visitor, {
816
+ mutable: true
817
+ });
818
+ directAncestors.delete(referencingElement);
819
+ }
820
+
821
+ // Boolean JSON Schemas
822
+ if (isBooleanJSONSchemaElement(referencedElement)) {
823
+ const booleanJsonSchemaElement = cloneDeep(referencedElement);
824
+ // annotate referenced element with info about original referencing element
825
+ booleanJsonSchemaElement.meta.set('ref-fields', {
826
+ $ref: toValue(referencingElement.$ref)
827
+ });
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);
832
+ return;
833
+ }
834
+
835
+ /**
836
+ * Creating a new version of Schema Object by merging fields from referenced Schema Object with referencing one.
837
+ */
838
+ if (isSchemaElement(referencedElement)) {
839
+ const mergedElement = cloneShallow(referencedElement);
840
+ // existing keywords from referencing schema overrides ones from referenced schema
841
+ referencingElement.forEach((value, keyElement, item) => {
842
+ mergedElement.remove(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: 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 = 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();
864
+ }
865
+ }
866
+ }
867
+ export default OpenAPI3_1DereferenceVisitor;