@speclynx/apidom-reference 4.11.1 → 4.12.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 (123) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +215 -3
  3. package/dist/apidom-reference.browser.js +1339 -153
  4. package/dist/apidom-reference.browser.min.js +1 -1
  5. package/package.json +35 -30
  6. package/src/File.cjs +3 -1
  7. package/src/Reference.cjs +3 -1
  8. package/src/ReferenceSet.cjs +3 -1
  9. package/src/bundle/index.cjs +9 -1
  10. package/src/bundle/index.mjs +6 -0
  11. package/src/bundle/strategies/BundleStrategy.cjs +3 -1
  12. package/src/bundle/strategies/openapi-3-0/index.cjs +94 -0
  13. package/src/bundle/strategies/openapi-3-0/index.mjs +81 -0
  14. package/src/bundle/strategies/openapi-3-0/visitor.cjs +650 -0
  15. package/src/bundle/strategies/openapi-3-0/visitor.mjs +642 -0
  16. package/src/bundle/strategies/openapi-3-1/index.cjs +3 -1
  17. package/src/bundle/util.cjs +42 -0
  18. package/src/bundle/util.mjs +33 -0
  19. package/src/configuration/empty.cjs +9 -2
  20. package/src/configuration/saturated.cjs +19 -11
  21. package/src/configuration/saturated.mjs +2 -1
  22. package/src/dereference/index.cjs +3 -1
  23. package/src/dereference/strategies/DereferenceStrategy.cjs +3 -1
  24. package/src/dereference/strategies/apidom/index.cjs +9 -2
  25. package/src/dereference/strategies/apidom/selectors/element-id.cjs +9 -2
  26. package/src/dereference/strategies/apidom/visitor.cjs +3 -1
  27. package/src/dereference/strategies/arazzo-1/index.cjs +34 -7
  28. package/src/dereference/strategies/arazzo-1/selectors/$anchor.cjs +46 -10
  29. package/src/dereference/strategies/arazzo-1/selectors/uri.cjs +22 -6
  30. package/src/dereference/strategies/arazzo-1/source-descriptions.cjs +3 -1
  31. package/src/dereference/strategies/arazzo-1/util.cjs +16 -4
  32. package/src/dereference/strategies/arazzo-1/visitor.cjs +3 -1
  33. package/src/dereference/strategies/asyncapi-2/index.cjs +9 -2
  34. package/src/dereference/strategies/asyncapi-2/visitor.cjs +3 -1
  35. package/src/dereference/strategies/openapi-2/index.cjs +9 -2
  36. package/src/dereference/strategies/openapi-2/visitor.cjs +3 -1
  37. package/src/dereference/strategies/openapi-3-0/index.cjs +9 -2
  38. package/src/dereference/strategies/openapi-3-0/visitor.cjs +3 -1
  39. package/src/dereference/strategies/openapi-3-1/index.cjs +28 -6
  40. package/src/dereference/strategies/openapi-3-1/selectors/$anchor.cjs +22 -5
  41. package/src/dereference/strategies/openapi-3-1/selectors/uri.cjs +16 -4
  42. package/src/dereference/strategies/openapi-3-1/util.cjs +3 -1
  43. package/src/dereference/strategies/openapi-3-1/visitor.cjs +3 -1
  44. package/src/dereference/strategies/overlay-1/extends.cjs +3 -1
  45. package/src/dereference/strategies/overlay-1/index.cjs +9 -2
  46. package/src/dereference/util.cjs +3 -1
  47. package/src/errors/BundleError.cjs +4 -2
  48. package/src/errors/BundleError.mjs +2 -2
  49. package/src/errors/DereferenceError.cjs +3 -1
  50. package/src/errors/EvaluationElementIdError.cjs +3 -1
  51. package/src/errors/EvaluationJsonSchema$anchorError.cjs +3 -1
  52. package/src/errors/EvaluationJsonSchemaUriError.cjs +3 -1
  53. package/src/errors/InvalidJsonSchema$anchorError.cjs +3 -1
  54. package/src/errors/JsonSchema$anchorError.cjs +3 -1
  55. package/src/errors/JsonSchemaUriError.cjs +3 -1
  56. package/src/errors/MaximumBundleDepthError.cjs +3 -1
  57. package/src/errors/MaximumDereferenceDepthError.cjs +3 -1
  58. package/src/errors/MaximumResolveDepthError.cjs +3 -1
  59. package/src/errors/ParseError.cjs +3 -1
  60. package/src/errors/ParserError.cjs +3 -1
  61. package/src/errors/PluginError.cjs +3 -1
  62. package/src/errors/ResolveError.cjs +3 -1
  63. package/src/errors/ResolverError.cjs +3 -1
  64. package/src/errors/UnmatchedBundleStrategyError.cjs +3 -1
  65. package/src/errors/UnmatchedDereferenceStrategyError.cjs +3 -1
  66. package/src/errors/UnmatchedParserError.cjs +3 -1
  67. package/src/errors/UnmatchedResolveStrategyError.cjs +3 -1
  68. package/src/errors/UnmatchedResolverError.cjs +3 -1
  69. package/src/errors/UnresolvableReferenceError.cjs +8 -3
  70. package/src/errors/UnresolvableReferenceError.mjs +5 -2
  71. package/src/index.cjs +209 -36
  72. package/src/options/index.cjs +71 -2
  73. package/src/options/index.mjs +68 -1
  74. package/src/options/util.cjs +3 -1
  75. package/src/parse/index.cjs +3 -1
  76. package/src/parse/parsers/Parser.cjs +3 -1
  77. package/src/parse/parsers/apidom-json/index.cjs +3 -1
  78. package/src/parse/parsers/arazzo-json-1/index.cjs +9 -2
  79. package/src/parse/parsers/arazzo-json-1/source-descriptions.cjs +3 -1
  80. package/src/parse/parsers/arazzo-yaml-1/index.cjs +9 -2
  81. package/src/parse/parsers/arazzo-yaml-1/source-descriptions.cjs +3 -1
  82. package/src/parse/parsers/asyncapi-json-2/index.cjs +3 -1
  83. package/src/parse/parsers/asyncapi-yaml-2/index.cjs +3 -1
  84. package/src/parse/parsers/binary/index-browser.cjs +3 -1
  85. package/src/parse/parsers/binary/index-node.cjs +3 -1
  86. package/src/parse/parsers/json/index.cjs +3 -1
  87. package/src/parse/parsers/openapi-json-2/index.cjs +3 -1
  88. package/src/parse/parsers/openapi-json-3-0/index.cjs +3 -1
  89. package/src/parse/parsers/openapi-json-3-1/index.cjs +3 -1
  90. package/src/parse/parsers/openapi-yaml-2/index.cjs +3 -1
  91. package/src/parse/parsers/openapi-yaml-3-0/index.cjs +3 -1
  92. package/src/parse/parsers/openapi-yaml-3-1/index.cjs +3 -1
  93. package/src/parse/parsers/overlay-json-1/extends.cjs +3 -1
  94. package/src/parse/parsers/overlay-json-1/index.cjs +9 -2
  95. package/src/parse/parsers/overlay-yaml-1/extends.cjs +10 -4
  96. package/src/parse/parsers/overlay-yaml-1/index.cjs +9 -2
  97. package/src/parse/parsers/yaml-1-2/index.cjs +3 -1
  98. package/src/resolve/index.cjs +3 -1
  99. package/src/resolve/resolvers/HTTPResolver.cjs +3 -1
  100. package/src/resolve/resolvers/Resolver.cjs +3 -1
  101. package/src/resolve/resolvers/file/index-browser.cjs +3 -1
  102. package/src/resolve/resolvers/file/index-node.cjs +3 -1
  103. package/src/resolve/resolvers/http-axios/cache/MemoryCache.cjs +3 -1
  104. package/src/resolve/resolvers/http-axios/index.cjs +3 -1
  105. package/src/resolve/strategies/ResolveStrategy.cjs +3 -1
  106. package/src/resolve/strategies/apidom/index.cjs +3 -1
  107. package/src/resolve/strategies/arazzo-1/index.cjs +3 -1
  108. package/src/resolve/strategies/asyncapi-2/index.cjs +3 -1
  109. package/src/resolve/strategies/openapi-2/index.cjs +3 -1
  110. package/src/resolve/strategies/openapi-3-0/index.cjs +3 -1
  111. package/src/resolve/strategies/openapi-3-1/index.cjs +3 -1
  112. package/src/resolve/strategies/overlay-1/index.cjs +3 -1
  113. package/src/resolve/util.cjs +3 -1
  114. package/src/util/plugins.cjs +3 -1
  115. package/src/util/url.cjs +3 -1
  116. package/types/apidom-reference.d.ts +41 -2
  117. package/types/bundle/strategies/openapi-3-0/index.d.ts +31 -0
  118. package/types/bundle/strategies/openapi-3-0/visitor.d.ts +131 -0
  119. package/types/bundle/util.d.ts +22 -0
  120. package/types/errors/BundleError.d.ts +2 -2
  121. package/types/errors/UnresolvableReferenceError.d.ts +5 -2
  122. package/types/index.d.ts +1 -0
  123. package/types/options/index.d.ts +33 -1
@@ -0,0 +1,650 @@
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
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.default = void 0;
9
+ var _ramda = require("ramda");
10
+ var _apidomDatamodel = require("@speclynx/apidom-datamodel");
11
+ var _apidomCore = require("@speclynx/apidom-core");
12
+ var _apidomError = require("@speclynx/apidom-error");
13
+ var _apidomTraverse = require("@speclynx/apidom-traverse");
14
+ var _apidomJsonPointer = require("@speclynx/apidom-json-pointer");
15
+ var _apidomNsOpenapi = require("@speclynx/apidom-ns-openapi-3-0");
16
+ var _BundleError = _interopRequireDefault(require("../../../errors/BundleError.cjs"));
17
+ var _UnresolvableReferenceError = _interopRequireDefault(require("../../../errors/UnresolvableReferenceError.cjs"));
18
+ var _MaximumBundleDepthError = _interopRequireDefault(require("../../../errors/MaximumBundleDepthError.cjs"));
19
+ var _MaximumResolveDepthError = _interopRequireDefault(require("../../../errors/MaximumResolveDepthError.cjs"));
20
+ var url = _interopRequireWildcard(require("../../../util/url.cjs"));
21
+ var _index = _interopRequireDefault(require("../../../parse/index.cjs"));
22
+ var _Reference = _interopRequireDefault(require("../../../Reference.cjs"));
23
+ var _util = require("../../util.cjs");
24
+ /**
25
+ * Maps the `referenced-element` meta value (set during refraction) to the
26
+ * Components Object field where the referenced element should be hoisted.
27
+ * Field names are sourced from the Components Object fixed fields so they
28
+ * cannot drift from the namespace definition.
29
+ */
30
+ const cf = (0, _apidomCore.fixedFields)(_apidomNsOpenapi.ComponentsElement, {
31
+ indexed: true
32
+ });
33
+ const componentFieldByReferencedElement = {
34
+ schema: cf.schemas.name,
35
+ response: cf.responses.name,
36
+ parameter: cf.parameters.name,
37
+ example: cf.examples.name,
38
+ requestBody: cf.requestBodies.name,
39
+ header: cf.headers.name,
40
+ securityScheme: cf.securitySchemes.name,
41
+ link: cf.links.name,
42
+ callback: cf.callbacks.name
43
+ };
44
+
45
+ /**
46
+ * Maps a Components Object field to the named-content element the namespace
47
+ * uses for it, so a bundle-created field matches a parsed/refracted one
48
+ * (e.g. carries the `components-schemas` class) rather than being a generic
49
+ * object.
50
+ */
51
+ const componentFieldElementByField = {
52
+ [cf.schemas.name]: _apidomNsOpenapi.ComponentsSchemasElement,
53
+ [cf.responses.name]: _apidomNsOpenapi.ComponentsResponsesElement,
54
+ [cf.parameters.name]: _apidomNsOpenapi.ComponentsParametersElement,
55
+ [cf.examples.name]: _apidomNsOpenapi.ComponentsExamplesElement,
56
+ [cf.requestBodies.name]: _apidomNsOpenapi.ComponentsRequestBodiesElement,
57
+ [cf.headers.name]: _apidomNsOpenapi.ComponentsHeadersElement,
58
+ [cf.securitySchemes.name]: _apidomNsOpenapi.ComponentsSecuritySchemesElement,
59
+ [cf.links.name]: _apidomNsOpenapi.ComponentsLinksElement,
60
+ [cf.callbacks.name]: _apidomNsOpenapi.ComponentsCallbacksElement
61
+ };
62
+
63
+ /**
64
+ * @public
65
+ */
66
+
67
+ /**
68
+ * @public
69
+ */
70
+ class OpenAPI3_0BundleVisitor {
71
+ reference;
72
+ options;
73
+
74
+ /**
75
+ * The base URI (without hash) of the entry document. A reference is
76
+ * considered internal when it resolves to this URI and external otherwise.
77
+ * Derived from the shared refSet's root reference.
78
+ */
79
+ get entryURI() {
80
+ return url.stripHash(this.reference.refSet?.rootRef?.uri ?? '');
81
+ }
82
+
83
+ /**
84
+ * The entry parse result. Derived from the shared refSet's root reference.
85
+ */
86
+ get entryParseResult() {
87
+ return this.reference.refSet.rootRef.value;
88
+ }
89
+
90
+ /**
91
+ * The entry document element. Hoisted external fragments are placed into its
92
+ * `components` object. The `canBundle` guard guarantees it is an
93
+ * OpenApi3_0Element.
94
+ */
95
+ get entryResult() {
96
+ return this.entryParseResult.result;
97
+ }
98
+
99
+ /**
100
+ * Shared across the entry document and every external document visitor.
101
+ * Guarantees each external fragment is hoisted exactly once and gives us a
102
+ * stable internal pointer to rewrite every referencing element to.
103
+ */
104
+ assignments;
105
+
106
+ /**
107
+ * Component names already reserved per Components Object field. Reserved
108
+ * before recursion so collision suffixing (`Pet`, `Pet-2`, ...) accounts for
109
+ * components that are still being bundled.
110
+ */
111
+ reservedNames;
112
+
113
+ /**
114
+ * Caches refracted fragments keyed by source element and target element type.
115
+ * The type is part of the key because the same source can be refracted into
116
+ * different semantic elements depending on the referencing context (e.g. a
117
+ * generic object referenced once as a Parameter and once as a Response).
118
+ */
119
+ refractCache;
120
+
121
+ /**
122
+ * Canonical URIs of Path Item Objects currently being inlined. Path Items
123
+ * are not hoisted into Components Object (no `components.pathItems` in
124
+ * OpenAPI 3.0), so the `assignments` map can't break their cycles. This
125
+ * stack guards against circular external Path Item references.
126
+ */
127
+ inlineStack;
128
+ constructor({
129
+ reference,
130
+ options,
131
+ assignments = new Map(),
132
+ reservedNames = new Map(),
133
+ refractCache = new WeakMap(),
134
+ inlineStack = new Set()
135
+ }) {
136
+ this.reference = reference;
137
+ this.options = options;
138
+ this.inlineStack = inlineStack;
139
+ this.assignments = assignments;
140
+ this.reservedNames = reservedNames;
141
+ this.refractCache = refractCache;
142
+ }
143
+ getRefracted(source, type) {
144
+ return this.refractCache.get(source)?.get(type);
145
+ }
146
+ setRefracted(source, type, refracted) {
147
+ let byType = this.refractCache.get(source);
148
+ if (byType === undefined) {
149
+ byType = new Map();
150
+ this.refractCache.set(source, byType);
151
+ }
152
+ byType.set(type, refracted);
153
+ }
154
+ toBaseURI(uri) {
155
+ return url.resolve(this.reference.uri, url.sanitize(url.stripHash(uri)));
156
+ }
157
+ async toReference(uri) {
158
+ // detect maximum depth of resolution
159
+ if (this.reference.depth >= this.options.resolve.maxDepth) {
160
+ throw new _MaximumResolveDepthError.default(`Maximum resolution depth of ${this.options.resolve.maxDepth} has been exceeded by file "${this.reference.uri}"`, {
161
+ maxDepth: this.options.resolve.maxDepth,
162
+ uri: this.reference.uri
163
+ });
164
+ }
165
+ const baseURI = this.toBaseURI(uri);
166
+ const {
167
+ refSet
168
+ } = this.reference;
169
+
170
+ // we've already processed this Reference in past
171
+ if (refSet.has(baseURI)) {
172
+ return refSet.find((0, _ramda.propEq)(baseURI, 'uri'));
173
+ }
174
+ const parseResult = await (0, _index.default)(url.unsanitize(baseURI), {
175
+ ...this.options,
176
+ parse: {
177
+ ...this.options.parse,
178
+ mediaType: 'text/plain'
179
+ }
180
+ });
181
+ const reference = new _Reference.default({
182
+ uri: baseURI,
183
+ value: parseResult,
184
+ depth: this.reference.depth + 1
185
+ });
186
+ refSet.add(reference);
187
+ return reference;
188
+ }
189
+
190
+ /**
191
+ * Normalizes a self-file reference (e.g. `./root.json#/components/schemas/Pet`)
192
+ * to a bare fragment (`#/components/schemas/Pet`) so the bundled document stays
193
+ * transferable. Bare fragments are returned unchanged.
194
+ */
195
+ normalizeSelfFileRef(ref) {
196
+ return ref.startsWith('#') ? ref : url.getHash(ref);
197
+ }
198
+
199
+ /**
200
+ * Handles an error according to the `bundle.continueOnError` option.
201
+ *
202
+ * For new errors: wraps in UnresolvableReferenceError with structured
203
+ * context. For errors already wrapped by a nested visitor: prepends the
204
+ * current hop to the trace.
205
+ *
206
+ * Inner/intermediate visitors always throw to let the trace accumulate. Only
207
+ * the entry document visitor respects continueOnError (callback/swallow/throw).
208
+ */
209
+ handleError(message, error, referencingElement, refFieldName, refFieldValue, visitorPath) {
210
+ // a collision reported as `error` is a deliberate hard stop with no
211
+ // resolution-failure analog, so pass it through unchanged. A maxDepth
212
+ // breach (MaximumBundleDepthError, which also extends BundleError) is a
213
+ // resolution failure and flows through below — wrapped and subject to
214
+ // continueOnError, like dereferencing.
215
+ if (error instanceof _BundleError.default && !(error instanceof _MaximumBundleDepthError.default)) {
216
+ throw error;
217
+ }
218
+ const {
219
+ continueOnError
220
+ } = this.options.bundle;
221
+ const isEntryDocument = url.stripHash(this.reference.refSet?.rootRef?.uri ?? '') === this.reference.uri;
222
+ const uri = this.reference.uri;
223
+ const type = referencingElement.element;
224
+ const codeFrame = (0, _apidomCore.toYAML)(referencingElement);
225
+ const location = visitorPath.formatPath();
226
+ const hop = {
227
+ uri,
228
+ type,
229
+ refFieldName,
230
+ refFieldValue,
231
+ location,
232
+ codeFrame
233
+ };
234
+ let unresolvedError;
235
+ if (error instanceof _UnresolvableReferenceError.default) {
236
+ // @ts-ignore
237
+ error.trace = [hop, ...error.trace];
238
+ unresolvedError = error;
239
+ } else {
240
+ unresolvedError = new _UnresolvableReferenceError.default(message, {
241
+ cause: error,
242
+ type,
243
+ uri,
244
+ location,
245
+ codeFrame,
246
+ refFieldName,
247
+ refFieldValue,
248
+ trace: []
249
+ });
250
+ }
251
+ if (!isEntryDocument || continueOnError === false) throw unresolvedError;
252
+ if (typeof continueOnError === 'function') continueOnError(unresolvedError);
253
+ }
254
+
255
+ /**
256
+ * Lazily creates the Components Object (and the requested field within it)
257
+ * on the entry document, returning the field where a fragment is hoisted.
258
+ */
259
+ ensureComponentsField(field) {
260
+ const entryResult = this.entryResult;
261
+ let components = entryResult.components;
262
+ if (!(0, _apidomDatamodel.isObjectElement)(components)) {
263
+ components = new _apidomNsOpenapi.ComponentsElement();
264
+ entryResult.components = components;
265
+ }
266
+ let fieldElement = components.get(field);
267
+ if (!(0, _apidomDatamodel.isObjectElement)(fieldElement)) {
268
+ const FieldElement = componentFieldElementByField[field] ?? _apidomDatamodel.ObjectElement;
269
+ fieldElement = new FieldElement();
270
+ components.set(field, fieldElement);
271
+ }
272
+ return fieldElement;
273
+ }
274
+
275
+ /**
276
+ * Derives a component name from the referenced JSON Pointer's last token,
277
+ * falling back to the referenced file's basename.
278
+ */
279
+ basenameOf(jsonPointer, baseURI) {
280
+ const tokens = (0, _apidomJsonPointer.parse)(jsonPointer).tree;
281
+ let candidate = tokens.length > 0 ? tokens[tokens.length - 1] : '';
282
+ if (candidate === '') {
283
+ const lastSlash = baseURI.lastIndexOf('/');
284
+ const lastDot = baseURI.lastIndexOf('.');
285
+ const fileName = baseURI.slice(lastSlash + 1);
286
+ // strip the extension only when the last dot belongs to the file name
287
+ candidate = lastDot > lastSlash ? baseURI.slice(lastSlash + 1, lastDot) : fileName;
288
+ }
289
+ if (candidate === '') candidate = 'Schema';
290
+ return candidate;
291
+ }
292
+
293
+ /**
294
+ * Computes the base component name (before collision suffixing) according to
295
+ * the configured naming strategy.
296
+ */
297
+ baseName(element, field, jsonPointer, baseURI) {
298
+ // strategy specific options take precedence over the top-level bundle options
299
+ const componentNamesStrategy = this.options.bundle.strategyOpts['openapi-3-0']?.componentNamesStrategy ?? this.options.bundle.componentNamesStrategy;
300
+ if (typeof componentNamesStrategy === 'function') {
301
+ const resolved = componentNamesStrategy({
302
+ element,
303
+ field,
304
+ jsonPointer,
305
+ baseURI
306
+ });
307
+ if (typeof resolved === 'string' && resolved !== '') {
308
+ return resolved;
309
+ }
310
+ return this.basenameOf(jsonPointer, baseURI);
311
+ }
312
+ if (componentNamesStrategy === 'title') {
313
+ const title = (0, _apidomDatamodel.isObjectElement)(element) ? (0, _apidomCore.toValue)(element.get('title')) : undefined;
314
+ if (typeof title === 'string' && title.trim() !== '') {
315
+ const name = (0, _util.sanitizeComponentName)((0, _util.toPascalCase)(title));
316
+ if (name !== '') return name;
317
+ }
318
+ // fall back to basename when no usable title is present
319
+ }
320
+ return this.basenameOf(jsonPointer, baseURI);
321
+ }
322
+
323
+ /**
324
+ * Computes a collision-free component name within the target field. A name is
325
+ * taken if it's already placed in components or reserved by a component that
326
+ * is still being bundled (reserved before recursion).
327
+ */
328
+ uniqueName(candidate, field) {
329
+ const fieldElement = this.ensureComponentsField(field);
330
+ const reserved = this.reservedNames.get(field) ?? new Set();
331
+ return (0, _util.uniqueName)(candidate, name => fieldElement.hasKey(name) || reserved.has(name));
332
+ }
333
+ async ReferenceElement(path) {
334
+ const referencingElement = path.node;
335
+ const $ref = (0, _apidomCore.toValue)(referencingElement.$ref);
336
+ const retrievalURI = this.toBaseURI($ref);
337
+ const isInternalReference = this.entryURI === retrievalURI;
338
+ const isExternalReference = !isInternalReference;
339
+ if (isInternalReference) {
340
+ // normalize self-file references to a bare fragment so the bundled
341
+ // document stays transferable; bare fragments are left untouched
342
+ referencingElement.set('$ref', this.normalizeSelfFileRef($ref));
343
+ path.skip();
344
+ return;
345
+ }
346
+
347
+ // honor the resolve.external switch
348
+ if (!this.options.resolve.external && isExternalReference) {
349
+ path.skip();
350
+ return;
351
+ }
352
+ const $refBaseURI = url.resolve(retrievalURI, $ref);
353
+ const jsonPointer = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference($refBaseURI);
354
+
355
+ // the target bucket depends on the referencing context, so it's part of the
356
+ // identity: the same external target referenced as e.g. both a parameter and
357
+ // a response must be hoisted into both components fields. The refractor sets
358
+ // `referenced-element` for every Reference Object position; the `schemas`
359
+ // fallback is a defensive default for the (unexpected) untagged case.
360
+ const referencedElementType = referencingElement.meta.get('referenced-element');
361
+ const field = componentFieldByReferencedElement[referencedElementType] ?? componentFieldByReferencedElement.schema;
362
+ const canonicalKey = `${field}\t${retrievalURI}#${jsonPointer}`;
363
+
364
+ // already hoisted (or being hoisted) — just rewrite the pointer.
365
+ //
366
+ // this is also how circular references terminate: the assignment is
367
+ // reserved BEFORE recursing into the fragment (see below), so a reference
368
+ // that cycles back (directly or indirectly) finds its pointer already
369
+ // reserved here and is rewritten without recursing. Cycles are deliberately
370
+ // preserved as internal `$ref`s pointing at each other — that is valid,
371
+ // serializable output; resolving the cycle (if desired) is dereferencing's
372
+ // job, not bundling's.
373
+ if (this.assignments.has(canonicalKey)) {
374
+ referencingElement.set('$ref', this.assignments.get(canonicalKey));
375
+ path.skip();
376
+ return;
377
+ }
378
+ try {
379
+ // detect maximum depth of bundling
380
+ if (this.reference.depth >= this.options.bundle.maxDepth) {
381
+ throw new _MaximumBundleDepthError.default(`Maximum bundle depth of "${this.options.bundle.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
382
+ maxDepth: this.options.bundle.maxDepth,
383
+ uri: this.reference.uri
384
+ });
385
+ }
386
+ const reference = await this.toReference($ref);
387
+
388
+ // possibly non-semantic fragment
389
+ let referencedElement = (0, _apidomJsonPointer.evaluate)(reference.value.result, jsonPointer);
390
+
391
+ // apply semantics to the fragment so nested references become Reference Objects
392
+ if (referencedElement.element !== referencedElementType && !(0, _apidomNsOpenapi.isReferenceElement)(referencedElement)) {
393
+ const cached = this.getRefracted(referencedElement, referencedElementType);
394
+ if (cached !== undefined) {
395
+ referencedElement = cached;
396
+ } else if ((0, _apidomNsOpenapi.isReferenceLikeElement)(referencedElement)) {
397
+ const sourceElement = referencedElement;
398
+ referencedElement = (0, _apidomNsOpenapi.refractReference)(referencedElement);
399
+ referencedElement.meta.set('referenced-element', referencedElementType);
400
+ this.setRefracted(sourceElement, referencedElementType, referencedElement);
401
+ } else {
402
+ const sourceElement = referencedElement;
403
+ referencedElement = (0, _apidomNsOpenapi.refract)(referencedElement, {
404
+ element: referencedElementType
405
+ });
406
+ this.setRefracted(sourceElement, referencedElementType, referencedElement);
407
+ }
408
+ }
409
+ const preferredName = this.baseName(referencedElement, field, jsonPointer, retrievalURI);
410
+ const componentName = this.uniqueName(preferredName, field);
411
+ const internalPointer = `#/components/${field}/${(0, _apidomJsonPointer.escape)(componentName)}`;
412
+
413
+ // a rename means two distinct targets resolved to the same name; each
414
+ // keeps its own component (and origin), so report the rename per severity.
415
+ // strategy specific options take precedence over the top-level bundle options
416
+ const onComponentNameCollision = this.options.bundle.strategyOpts['openapi-3-0']?.onComponentNameCollision ?? this.options.bundle.onComponentNameCollision;
417
+ if (componentName !== preferredName && onComponentNameCollision !== 'off') {
418
+ const message = `Component "${preferredName}" in components/${field} is referenced with the same name but different content. Renamed to "${componentName}".`;
419
+ if (onComponentNameCollision === 'error') {
420
+ throw new _BundleError.default(message);
421
+ }
422
+ const annotation = new _apidomDatamodel.AnnotationElement(message);
423
+ annotation.classes.push('warning');
424
+ annotation.code = 'bundle-component-name-collision';
425
+ // append (never prepend) so the result element stays ahead of annotations
426
+ this.entryParseResult.content.push(annotation);
427
+ }
428
+
429
+ // reserve the assignment and component name before recursing so cyclic
430
+ // references terminate
431
+ this.assignments.set(canonicalKey, internalPointer);
432
+ if (!this.reservedNames.has(field)) this.reservedNames.set(field, new Set());
433
+ this.reservedNames.get(field).add(componentName);
434
+
435
+ // own a copy of the fragment and bundle its own external references
436
+ const hoistedElement = (0, _apidomDatamodel.cloneDeep)(referencedElement);
437
+ const visitor = new OpenAPI3_0BundleVisitor({
438
+ reference,
439
+ options: this.options,
440
+ assignments: this.assignments,
441
+ reservedNames: this.reservedNames,
442
+ refractCache: this.refractCache,
443
+ inlineStack: this.inlineStack
444
+ });
445
+ const bundledElement = await (0, _apidomTraverse.traverseAsync)(hoistedElement, visitor, {
446
+ mutable: true
447
+ });
448
+
449
+ // annotate the hoisted fragment with info about its origin
450
+ if ((0, _apidomDatamodel.isElement)(bundledElement)) {
451
+ bundledElement.meta.set('ref-origin', reference.uri);
452
+ }
453
+
454
+ // place the bundled fragment into the entry document's components
455
+ this.ensureComponentsField(field).set(componentName, bundledElement);
456
+
457
+ // rewrite the referencing element to point at the hoisted fragment
458
+ referencingElement.set('$ref', internalPointer);
459
+ path.skip();
460
+ } catch (error) {
461
+ this.handleError(`Error while bundling Reference Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
462
+ path.skip();
463
+ }
464
+ }
465
+
466
+ /**
467
+ * Path Item Object is not a Components Object field in OpenAPI 3.0
468
+ * (unlike 3.1 which has `components.pathItems`). An external Path Item
469
+ * reference therefore cannot be hoisted; it is inlined in place instead,
470
+ * after bundling its own external references.
471
+ */
472
+ async PathItemElement(path) {
473
+ const pathItemElement = path.node;
474
+
475
+ // ignore Path Item Objects without a $ref field
476
+ if (!(0, _apidomDatamodel.isStringElement)(pathItemElement.$ref)) {
477
+ return;
478
+ }
479
+ const $ref = (0, _apidomCore.toValue)(pathItemElement.$ref);
480
+ const retrievalURI = this.toBaseURI($ref);
481
+ const isInternalReference = this.entryURI === retrievalURI;
482
+ const isExternalReference = !isInternalReference;
483
+ if (isInternalReference) {
484
+ // normalize self-file references to a bare fragment so the bundled
485
+ // document stays transferable; bare fragments are left untouched
486
+ pathItemElement.set('$ref', this.normalizeSelfFileRef($ref));
487
+ return;
488
+ }
489
+
490
+ // honor the resolve.external switch
491
+ if (!this.options.resolve.external && isExternalReference) {
492
+ return;
493
+ }
494
+ const $refBaseURI = url.resolve(retrievalURI, $ref);
495
+ const jsonPointer = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference($refBaseURI);
496
+ const canonicalKey = `${retrievalURI}#${jsonPointer}`;
497
+
498
+ // a circular external Path Item reference cannot be inlined without
499
+ // recursing forever; leave the $ref in place to break the cycle
500
+ if (this.inlineStack.has(canonicalKey)) {
501
+ return;
502
+ }
503
+ try {
504
+ // detect maximum depth of bundling
505
+ if (this.reference.depth >= this.options.bundle.maxDepth) {
506
+ throw new _MaximumBundleDepthError.default(`Maximum bundle depth of "${this.options.bundle.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
507
+ maxDepth: this.options.bundle.maxDepth,
508
+ uri: this.reference.uri
509
+ });
510
+ }
511
+ const reference = await this.toReference($ref);
512
+ let referencedElement = (0, _apidomJsonPointer.evaluate)(reference.value.result, jsonPointer);
513
+
514
+ // apply Path Item semantics to the referenced fragment
515
+ if (!(0, _apidomNsOpenapi.isPathItemElement)(referencedElement)) {
516
+ const cached = this.getRefracted(referencedElement, 'pathItem');
517
+ if (cached !== undefined) {
518
+ referencedElement = cached;
519
+ } else {
520
+ const sourceElement = referencedElement;
521
+ referencedElement = (0, _apidomNsOpenapi.refractPathItem)(referencedElement);
522
+ this.setRefracted(sourceElement, 'pathItem', referencedElement);
523
+ }
524
+ }
525
+
526
+ // own a copy and bundle the external references it contains
527
+ const inlinedElement = (0, _apidomDatamodel.cloneDeep)(referencedElement);
528
+ this.inlineStack.add(canonicalKey);
529
+ const visitor = new OpenAPI3_0BundleVisitor({
530
+ reference,
531
+ options: this.options,
532
+ assignments: this.assignments,
533
+ reservedNames: this.reservedNames,
534
+ refractCache: this.refractCache,
535
+ inlineStack: this.inlineStack
536
+ });
537
+ let bundledElement;
538
+ try {
539
+ bundledElement = await (0, _apidomTraverse.traverseAsync)(inlinedElement, visitor, {
540
+ mutable: true
541
+ });
542
+ } finally {
543
+ this.inlineStack.delete(canonicalKey);
544
+ }
545
+
546
+ // merge sibling fields from the referencing Path Item over the referenced
547
+ // one. The referencing `$ref` is being resolved away and is skipped; the
548
+ // referenced element keeps its own `$ref` if one survived (i.e. it was
549
+ // left in place to break a circular external Path Item chain).
550
+ pathItemElement.forEach((_value, keyElement, item) => {
551
+ const key = (0, _apidomCore.toValue)(keyElement);
552
+ if (key === '$ref') return;
553
+ bundledElement.remove(key);
554
+ bundledElement.content.push(item);
555
+ });
556
+ bundledElement.meta.set('ref-origin', reference.uri);
557
+ path.replaceWith(bundledElement);
558
+ } catch (error) {
559
+ this.handleError(`Error while bundling Path Item Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, pathItemElement, '$ref', $ref, path);
560
+ }
561
+ }
562
+
563
+ /**
564
+ * Example Object `externalValue` points at arbitrary external content that
565
+ * has no place in the Components Object. The referenced value is inlined into
566
+ * the Example's `value` field.
567
+ */
568
+ async ExampleElement(path) {
569
+ const exampleElement = path.node;
570
+
571
+ // ignore Example Objects without an externalValue field
572
+ if (!(0, _apidomDatamodel.isStringElement)(exampleElement.externalValue)) {
573
+ return;
574
+ }
575
+
576
+ // value and externalValue fields are mutually exclusive
577
+ if (exampleElement.hasKey('value') && (0, _apidomDatamodel.isStringElement)(exampleElement.externalValue)) {
578
+ throw new _apidomError.ApiDOMStructuredError('ExampleElement value and externalValue fields are mutually exclusive', {
579
+ value: (0, _apidomCore.toValue)(exampleElement.value),
580
+ externalValue: (0, _apidomCore.toValue)(exampleElement.externalValue)
581
+ });
582
+ }
583
+ const externalValue = (0, _apidomCore.toValue)(exampleElement.externalValue);
584
+ const retrievalURI = this.toBaseURI(externalValue);
585
+ const isInternalReference = this.entryURI === retrievalURI;
586
+ const isExternalReference = !isInternalReference;
587
+
588
+ // honor the resolve.external switch
589
+ if (!this.options.resolve.external && isExternalReference) {
590
+ return;
591
+ }
592
+ try {
593
+ const reference = await this.toReference(externalValue);
594
+ const valueElement = (0, _apidomDatamodel.cloneShallow)(reference.value.result);
595
+ valueElement.meta.set('ref-origin', reference.uri);
596
+ const exampleElementCopy = (0, _apidomDatamodel.cloneShallow)(exampleElement);
597
+ exampleElementCopy.value = valueElement;
598
+ exampleElementCopy.remove('externalValue');
599
+ path.replaceWith(exampleElementCopy);
600
+ } catch (error) {
601
+ this.handleError(`Error while bundling Example Object. Cannot resolve externalValue "${externalValue}": ${error.message}`, error, exampleElement, 'externalValue', externalValue, path);
602
+ }
603
+ }
604
+
605
+ /**
606
+ * Link Object `operationRef` points at an Operation Object, which has no
607
+ * Components Object field in OpenAPI 3.0 and therefore cannot be hoisted or
608
+ * inlined. To keep the link resolvable from the bundled document, an external
609
+ * `operationRef` is rewritten to its absolute URI. Internal `operationRef`
610
+ * values and `operationId` links are left untouched.
611
+ */
612
+ async LinkElement(path) {
613
+ const linkElement = path.node;
614
+
615
+ // operationRef and operationId fields are mutually exclusive
616
+ if ((0, _apidomDatamodel.isStringElement)(linkElement.operationRef) && (0, _apidomDatamodel.isStringElement)(linkElement.operationId)) {
617
+ throw new _apidomError.ApiDOMStructuredError('LinkElement operationRef and operationId fields are mutually exclusive', {
618
+ operationRef: (0, _apidomCore.toValue)(linkElement.operationRef),
619
+ operationId: (0, _apidomCore.toValue)(linkElement.operationId)
620
+ });
621
+ }
622
+
623
+ // only external operationRef links need adjusting
624
+ if (!(0, _apidomDatamodel.isStringElement)(linkElement.operationRef)) {
625
+ return;
626
+ }
627
+ const operationRef = (0, _apidomCore.toValue)(linkElement.operationRef);
628
+ const retrievalURI = this.toBaseURI(operationRef);
629
+ const isInternalReference = this.entryURI === retrievalURI;
630
+ if (isInternalReference) {
631
+ // normalize self-file operationRef to a bare fragment so the bundled
632
+ // document stays transferable; bare fragments are left untouched
633
+ linkElement.set('operationRef', this.normalizeSelfFileRef(operationRef));
634
+ return;
635
+ }
636
+
637
+ // honor the resolve.external switch
638
+ if (!this.options.resolve.external) {
639
+ return;
640
+ }
641
+
642
+ // rewrite to an absolute URI so the link keeps resolving once the document
643
+ // is treated as self-contained
644
+ const absoluteURI = url.resolve(this.reference.uri, operationRef);
645
+ if (absoluteURI !== operationRef) {
646
+ linkElement.set('operationRef', absoluteURI);
647
+ }
648
+ }
649
+ }
650
+ var _default = exports.default = OpenAPI3_0BundleVisitor;