@scalar/openapi-parser 0.14.0 → 0.15.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 (83) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +24 -1
  3. package/dist/index.d.ts +2 -1
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +3 -3
  6. package/dist/index.js.map +2 -2
  7. package/dist/utils/bundle/bundle.d.ts +94 -8
  8. package/dist/utils/bundle/bundle.d.ts.map +1 -1
  9. package/dist/utils/bundle/bundle.js +24 -6
  10. package/dist/utils/bundle/bundle.js.map +2 -2
  11. package/dist/utils/bundle/index.d.ts +2 -2
  12. package/dist/utils/bundle/index.js +2 -2
  13. package/dist/utils/bundle/plugins/{fetch-urls.d.ts → fetch-urls/index.d.ts} +3 -2
  14. package/dist/utils/bundle/plugins/fetch-urls/index.d.ts.map +1 -0
  15. package/dist/utils/bundle/plugins/{fetch-urls.js → fetch-urls/index.js} +6 -5
  16. package/dist/utils/bundle/plugins/fetch-urls/index.js.map +7 -0
  17. package/dist/utils/bundle/plugins/{read-files.d.ts → read-files/index.d.ts} +2 -2
  18. package/dist/utils/bundle/plugins/read-files/index.d.ts.map +1 -0
  19. package/dist/utils/bundle/plugins/{read-files.js → read-files/index.js} +4 -4
  20. package/dist/utils/bundle/plugins/read-files/index.js.map +7 -0
  21. package/dist/utils/openapi/actions/details.d.ts +7 -0
  22. package/dist/utils/openapi/actions/details.d.ts.map +1 -0
  23. package/dist/utils/openapi/actions/details.js +11 -0
  24. package/dist/utils/openapi/actions/details.js.map +7 -0
  25. package/dist/utils/openapi/actions/files.d.ts +6 -0
  26. package/dist/utils/openapi/actions/files.d.ts.map +1 -0
  27. package/dist/utils/openapi/actions/files.js +9 -0
  28. package/dist/utils/openapi/actions/files.js.map +7 -0
  29. package/dist/utils/openapi/actions/get.d.ts +6 -0
  30. package/dist/utils/openapi/actions/get.d.ts.map +1 -0
  31. package/dist/utils/openapi/actions/get.js +11 -0
  32. package/dist/utils/openapi/actions/get.js.map +7 -0
  33. package/dist/utils/openapi/actions/toJson.d.ts +6 -0
  34. package/dist/utils/openapi/actions/toJson.d.ts.map +1 -0
  35. package/dist/utils/openapi/actions/toJson.js +11 -0
  36. package/dist/utils/openapi/actions/toJson.js.map +7 -0
  37. package/dist/utils/openapi/actions/toYaml.d.ts +6 -0
  38. package/dist/utils/openapi/actions/toYaml.d.ts.map +1 -0
  39. package/dist/utils/openapi/actions/toYaml.js +11 -0
  40. package/dist/utils/openapi/actions/toYaml.js.map +7 -0
  41. package/dist/utils/openapi/commands/dereferenceCommand.d.ts +27 -0
  42. package/dist/utils/openapi/commands/dereferenceCommand.d.ts.map +1 -0
  43. package/dist/utils/openapi/commands/dereferenceCommand.js +27 -0
  44. package/dist/utils/openapi/commands/dereferenceCommand.js.map +7 -0
  45. package/dist/utils/openapi/commands/filterCommand.d.ts +41 -0
  46. package/dist/utils/openapi/commands/filterCommand.d.ts.map +1 -0
  47. package/dist/utils/openapi/commands/filterCommand.js +26 -0
  48. package/dist/utils/openapi/commands/filterCommand.js.map +7 -0
  49. package/dist/utils/openapi/commands/loadCommand.d.ts +8321 -0
  50. package/dist/utils/openapi/commands/loadCommand.d.ts.map +1 -0
  51. package/dist/utils/openapi/commands/loadCommand.js +42 -0
  52. package/dist/utils/openapi/commands/loadCommand.js.map +7 -0
  53. package/dist/utils/openapi/commands/upgradeCommand.d.ts +3406 -0
  54. package/dist/utils/openapi/commands/upgradeCommand.d.ts.map +1 -0
  55. package/dist/utils/openapi/commands/upgradeCommand.js +29 -0
  56. package/dist/utils/openapi/commands/upgradeCommand.js.map +7 -0
  57. package/dist/utils/openapi/commands/validateCommand.d.ts +3451 -0
  58. package/dist/utils/openapi/commands/validateCommand.d.ts.map +1 -0
  59. package/dist/utils/openapi/commands/validateCommand.js +33 -0
  60. package/dist/utils/openapi/commands/validateCommand.js.map +7 -0
  61. package/dist/utils/openapi/openapi.d.ts +1272 -0
  62. package/dist/utils/openapi/openapi.d.ts.map +1 -0
  63. package/dist/utils/openapi/openapi.js +15 -0
  64. package/dist/utils/openapi/openapi.js.map +7 -0
  65. package/dist/utils/openapi/openapi.test-d.d.ts +2 -0
  66. package/dist/utils/openapi/openapi.test-d.d.ts.map +1 -0
  67. package/dist/utils/openapi/openapi.test-d.js +14 -0
  68. package/dist/utils/openapi/openapi.test-d.js.map +7 -0
  69. package/dist/utils/openapi/utils/queueTask.d.ts +6 -0
  70. package/dist/utils/openapi/utils/queueTask.d.ts.map +1 -0
  71. package/dist/utils/openapi/utils/queueTask.js +10 -0
  72. package/dist/utils/openapi/utils/queueTask.js.map +7 -0
  73. package/dist/utils/openapi/utils/workThroughQueue.d.ts +6 -0
  74. package/dist/utils/openapi/utils/workThroughQueue.d.ts.map +1 -0
  75. package/dist/utils/openapi/utils/workThroughQueue.js +52 -0
  76. package/dist/utils/openapi/utils/workThroughQueue.js.map +7 -0
  77. package/dist/utils/upgrade-from-two-to-three.js +45 -1
  78. package/dist/utils/upgrade-from-two-to-three.js.map +2 -2
  79. package/package.json +15 -5
  80. package/dist/utils/bundle/plugins/fetch-urls.d.ts.map +0 -1
  81. package/dist/utils/bundle/plugins/fetch-urls.js.map +0 -7
  82. package/dist/utils/bundle/plugins/read-files.d.ts.map +0 -1
  83. package/dist/utils/bundle/plugins/read-files.js.map +0 -7
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @scalar/openapi-parser
2
2
 
3
+ ## 0.15.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b9dacba: fix(openapi-parser): multi entry build for bundler plugins
8
+ - a73e9be: chore(openapi-parser): bring back pipeline syntax
9
+ - f4332eb: feat: external reference resolution and partial bundle of the openapi document
10
+
11
+ ### Patch Changes
12
+
13
+ - 17bc0d8: fix: collectionFormat is not migrated to new style and explode keywords
14
+ - 49c04cf: fix(openapi-parser): use dynamic imports inside the plugin
15
+
3
16
  ## 0.14.0
4
17
 
5
18
  ### Minor Changes
package/README.md CHANGED
@@ -65,7 +65,8 @@ The OpenAPI specification allows to point to external files (URLs or files). But
65
65
  This plugins handles all external urls. It works for both node.js and browser environment
66
66
 
67
67
  ```ts
68
- import { bundle, fetchUrls } from '@scalar/openapi-parser'
68
+ import { bundle } from '@scalar/openapi-parser'
69
+ import { fetchUrls } from '@scalar/openapi-parser/utils/bundle/plugins/fetch-urls'
69
70
 
70
71
  const document = {
71
72
  openapi: '3.1.0',
@@ -128,6 +129,28 @@ await bundle(
128
129
  )
129
130
  ```
130
131
 
132
+ ###### Custom fetch function
133
+ For advanced use cases like proxying requests or implementing custom network logic, you can provide your own fetch implementation. This allows you to handle things like CORS restrictions, custom authentication flows, or request/response transformations.
134
+
135
+ ```ts
136
+ await bundle(
137
+ document,
138
+ {
139
+ plugins: [
140
+ fetchUrls({
141
+ // Custom fetcher function
142
+ fetch: async (input, init) => {
143
+ console.log('Custom fetch logic')
144
+ return fetch(input, init)
145
+ },
146
+ })
147
+ readFiles(),
148
+ ],
149
+ treeShake: false
150
+ },
151
+ )
152
+ ```
153
+
131
154
  ###### Bundle from remote url
132
155
 
133
156
  ```ts
package/dist/index.d.ts CHANGED
@@ -14,6 +14,7 @@ export { upgrade } from './utils/upgrade.js';
14
14
  export { upgradeFromThreeToThreeOne } from './utils/upgrade-from-three-to-three-one.js';
15
15
  export { upgradeFromTwoToThree } from './utils/upgrade-from-two-to-three.js';
16
16
  export { validate } from './utils/validate.js';
17
- export { bundle, fetchUrls, readFiles } from './utils/bundle/index.js';
17
+ export { bundle } from './utils/bundle/index.js';
18
18
  export type { LoadResult, Filesystem, AnyObject, ErrorObject } from './types/index.js';
19
+ export { openapi } from './utils/openapi/openapi.js';
19
20
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAA;AACjD,OAAO,EAAE,iBAA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A;AACxC,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAA;AACnC,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAA;AAC7C,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAA;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAA;AACnE,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAE,0BAA0B,EAAE,MAAM,yCAAyC,CAAA;AACpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAA;AACzE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AACvC,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAC7E,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAA"}
package/dist/index.js CHANGED
@@ -14,18 +14,18 @@ import { upgrade } from "./utils/upgrade.js";
14
14
  import { upgradeFromThreeToThreeOne } from "./utils/upgrade-from-three-to-three-one.js";
15
15
  import { upgradeFromTwoToThree } from "./utils/upgrade-from-two-to-three.js";
16
16
  import { validate } from "./utils/validate.js";
17
- import { bundle, fetchUrls, readFiles } from "./utils/bundle/index.js";
17
+ import { bundle } from "./utils/bundle/index.js";
18
+ import { openapi } from "./utils/openapi/openapi.js";
18
19
  export {
19
20
  bundle,
20
21
  dereference,
21
22
  escapeJsonPointer,
22
- fetchUrls,
23
23
  filter,
24
24
  isJson,
25
25
  isYaml,
26
26
  load,
27
27
  normalize,
28
- readFiles,
28
+ openapi,
29
29
  sanitize,
30
30
  toJson,
31
31
  toYaml,
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["export { dereference } from './utils/dereference'\nexport { escapeJsonPointer } from './utils/escape-json-pointer'\nexport { filter } from './utils/filter'\nexport { isJson } from './utils/is-json'\nexport { isYaml } from './utils/is-yaml'\nexport { load } from './utils/load'\nexport { normalize } from './utils/normalize'\nexport { sanitize } from './utils/transform/sanitize'\nexport { toJson } from './utils/to-json'\nexport { toYaml } from './utils/to-yaml'\nexport { traverse } from './utils/traverse'\nexport { unescapeJsonPointer } from './utils/unescape-json-pointer'\nexport { upgrade } from './utils/upgrade'\nexport { upgradeFromThreeToThreeOne } from './utils/upgrade-from-three-to-three-one'\nexport { upgradeFromTwoToThree } from './utils/upgrade-from-two-to-three'\nexport { validate } from './utils/validate'\nexport { bundle, fetchUrls, readFiles } from './utils/bundle'\nexport type { LoadResult, Filesystem, AnyObject, ErrorObject } from './types'\n"],
5
- "mappings": "AAAA,SAAS,mBAAmB;AAC5B,SAAS,yBAAyB;AAClC,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,gBAAgB;AACzB,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,gBAAgB;AACzB,SAAS,2BAA2B;AACpC,SAAS,eAAe;AACxB,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,gBAAgB;AACzB,SAAS,QAAQ,WAAW,iBAAiB;",
4
+ "sourcesContent": ["export { dereference } from './utils/dereference'\nexport { escapeJsonPointer } from './utils/escape-json-pointer'\nexport { filter } from './utils/filter'\nexport { isJson } from './utils/is-json'\nexport { isYaml } from './utils/is-yaml'\nexport { load } from './utils/load'\nexport { normalize } from './utils/normalize'\nexport { sanitize } from './utils/transform/sanitize'\nexport { toJson } from './utils/to-json'\nexport { toYaml } from './utils/to-yaml'\nexport { traverse } from './utils/traverse'\nexport { unescapeJsonPointer } from './utils/unescape-json-pointer'\nexport { upgrade } from './utils/upgrade'\nexport { upgradeFromThreeToThreeOne } from './utils/upgrade-from-three-to-three-one'\nexport { upgradeFromTwoToThree } from './utils/upgrade-from-two-to-three'\nexport { validate } from './utils/validate'\nexport { bundle } from './utils/bundle'\nexport type { LoadResult, Filesystem, AnyObject, ErrorObject } from './types'\nexport { openapi } from './utils/openapi/openapi'\n"],
5
+ "mappings": "AAAA,SAAS,mBAAmB;AAC5B,SAAS,yBAAyB;AAClC,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,gBAAgB;AACzB,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,gBAAgB;AACzB,SAAS,2BAA2B;AACpC,SAAS,eAAe;AACxB,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,gBAAgB;AACzB,SAAS,cAAc;AAEvB,SAAS,eAAe;",
6
6
  "names": []
7
7
  }
@@ -46,6 +46,10 @@ export declare function getNestedValue(target: Record<string, any>, segments: st
46
46
  * or arrays based on the path segments. If the next segment is a numeric string, it creates
47
47
  * an array instead of an object.
48
48
  *
49
+ * ⚠️ Warning: Be careful with object keys that look like numbers (e.g. "123") as this function
50
+ * will interpret them as array indices and create arrays instead of objects. If you need to
51
+ * use numeric-looking keys, consider prefixing them with a non-numeric character.
52
+ *
49
53
  * @param obj - The target object to set the value in
50
54
  * @param path - The JSON pointer path where the value should be set
51
55
  * @param value - The value to set at the specified path
@@ -70,6 +74,19 @@ export declare function getNestedValue(target: Record<string, any>, segments: st
70
74
  * // path: 'new'
71
75
  * // }
72
76
  * // }
77
+ *
78
+ * @example
79
+ * // ⚠️ Warning: This will create an array instead of an object with key "123"
80
+ * setValueAtPath(obj, '/foo/123/bar', 'value')
81
+ * // Result:
82
+ * // {
83
+ * // foo: [
84
+ * // undefined,
85
+ * // undefined,
86
+ * // undefined,
87
+ * // { bar: 'value' }
88
+ * // ]
89
+ * // }
73
90
  */
74
91
  export declare function setValueAtPath(obj: any, path: string, value: any): void;
75
92
  /**
@@ -116,12 +133,13 @@ export declare function prefixInternalRefRecursive(input: unknown, prefix: strin
116
133
  * This function is used to create unique identifiers for external references
117
134
  * while keeping the hash length manageable. It uses the Web Crypto API to
118
135
  * generate a SHA-1 hash and returns the first 7 characters of the hex string.
136
+ * If the hash would be all numbers, it ensures at least one letter is included.
119
137
  *
120
138
  * @param value - The string to hash
121
- * @returns A 7-character hexadecimal hash
139
+ * @returns A 7-character hexadecimal hash with at least one letter
122
140
  * @example
123
- * // Returns "a1b2c3d"
124
- * getHash("https://example.com/schema.json")
141
+ * // Returns "2ae91d7"
142
+ * await getHash("https://example.com/schema.json")
125
143
  */
126
144
  export declare function getHash(value: string): Promise<string>;
127
145
  /**
@@ -138,12 +156,59 @@ export type Plugin = {
138
156
  validate: (value: string) => boolean;
139
157
  exec: (value: string) => Promise<ResolveResult>;
140
158
  };
159
+ /**
160
+ * Configuration options for the bundler.
161
+ * Controls how external references are resolved and processed during bundling.
162
+ */
141
163
  type Config = {
164
+ /**
165
+ * Array of plugins that handle resolving references from different sources.
166
+ * Each plugin is responsible for fetching and processing data from specific sources
167
+ * like URLs or the filesystem.
168
+ */
142
169
  plugins: Plugin[];
170
+ /**
171
+ * Optional root object that serves as the base document when bundling a subpart.
172
+ * This allows resolving references relative to the root document's location,
173
+ * ensuring proper path resolution for nested references.
174
+ */
143
175
  root?: UnknownObject;
176
+ /**
177
+ * Optional cache to store promises of resolved references.
178
+ * Helps avoid duplicate fetches/reads of the same resource by storing
179
+ * the resolution promises for reuse.
180
+ */
144
181
  cache?: Map<string, Promise<ResolveResult>>;
182
+ /**
183
+ * Cache of visited nodes during partial bundling.
184
+ * Used to prevent re-bundling the same tree multiple times when doing partial bundling,
185
+ * improving performance by avoiding redundant processing of already bundled sections.
186
+ */
187
+ visitedNodes?: Set<unknown>;
188
+ /**
189
+ * Enable tree shaking to optimize the bundle size.
190
+ * When enabled, only the parts of external documents that are actually referenced
191
+ * will be included in the final bundle.
192
+ */
145
193
  treeShake: boolean;
194
+ /**
195
+ * Optional flag to generate a URL map.
196
+ * When enabled, tracks the original source URLs of bundled references
197
+ * in an x-ext-urls section for reference mapping.
198
+ */
146
199
  urlMap?: boolean;
200
+ /**
201
+ * Optional hooks to monitor the bundler's lifecycle.
202
+ * Allows tracking the progress and status of reference resolution.
203
+ */
204
+ hooks?: Partial<{
205
+ /** Called when starting to resolve a reference */
206
+ onResolveStart: (node: Record<string, unknown> & Record<'$ref', unknown>) => void;
207
+ /** Called when a reference resolution fails */
208
+ onResolveError: (node: Record<string, unknown> & Record<'$ref', unknown>) => void;
209
+ /** Called when a reference is successfully resolved */
210
+ onResolveSuccess: (node: Record<string, unknown> & Record<'$ref', unknown>) => void;
211
+ }>;
147
212
  };
148
213
  /**
149
214
  * Bundles an OpenAPI specification by resolving all external references.
@@ -156,7 +221,7 @@ type Config = {
156
221
  * @param input - The OpenAPI specification object or string to bundle. If a string is provided,
157
222
  * it should be a URL or file path that points to an OpenAPI specification.
158
223
  * The string will be resolved using the provided plugins before bundling.
159
- * @param config - Configuration object containing plugins for resolving references
224
+ * @param config - Configuration object containing plugins and options for bundling OpenAPI specifications
160
225
  * @returns A promise that resolves to the bundled specification with all references embedded
161
226
  * @example
162
227
  * // Example with object input
@@ -168,23 +233,44 @@ type Config = {
168
233
  * }
169
234
  * }
170
235
  *
171
- * const bundled = await bundle(spec, { plugins: [fetchUrls()] })
236
+ * const bundled = await bundle(spec, {
237
+ * plugins: [fetchUrls()],
238
+ * treeShake: true,
239
+ * urlMap: true,
240
+ * hooks: {
241
+ * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),
242
+ * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),
243
+ * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)
244
+ * }
245
+ * })
172
246
  * // Result:
173
247
  * // {
174
248
  * // paths: {
175
249
  * // '/users': {
176
- * // $ref: '#/x-ext/https~1~1example.com~1schemas~1users.yaml'
250
+ * // $ref: '#/x-ext/abc123'
177
251
  * // }
178
252
  * // },
179
253
  * // 'x-ext': {
180
- * // 'https~1~1example.com~1schemas~1users.yaml': {
254
+ * // 'abc123': {
181
255
  * // // Resolved content from users.yaml
182
256
  * // }
257
+ * // },
258
+ * // 'x-ext-urls': {
259
+ * // 'https://example.com/schemas/users.yaml': 'abc123'
183
260
  * // }
184
261
  * // }
185
262
  *
186
263
  * // Example with URL input
187
- * const bundledFromUrl = await bundle('https://example.com/openapi.yaml', { plugins: [fetchUrls()] })
264
+ * const bundledFromUrl = await bundle('https://example.com/openapi.yaml', {
265
+ * plugins: [fetchUrls()],
266
+ * treeShake: true,
267
+ * urlMap: true,
268
+ * hooks: {
269
+ * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),
270
+ * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),
271
+ * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)
272
+ * }
273
+ * })
188
274
  * // The function will first fetch the OpenAPI spec from the URL,
189
275
  * // then bundle all its external references into the x-ext section
190
276
  */
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.d.ts","sourceRoot":"","sources":["../../../src/utils/bundle/bundle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAM5C;;;;;;;;;;;GAWG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAElD;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEjD;AAED,MAAM,MAAM,aAAa,GAAG;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,OAAO,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAA;CAAE,CAAA;AA2BvE;;;;;;;;GA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CAChD,CAAA;AAED;;;GAGG;AACH,KAAK,MAAM,GAAG;IACZ;;;;OAIG;IACH,OAAO,EAAE,MAAM,EAAE,CAAA;IAEjB;;;;OAIG;IACH,IAAI,CAAC,EAAE,aAAa,CAAA;IAEpB;;;;OAIG;IACH,KAAK,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC,CAAA;IAE3C;;;;OAIG;IACH,YAAY,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,CAAA;IAE3B;;;;OAIG;IACH,SAAS,EAAE,OAAO,CAAA;IAElB;;;;OAIG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;IAEhB;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;QACd,kDAAkD;QAClD,cAAc,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAA;QACjF,+CAA+C;QAC/C,cAAc,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAA;QACjF,uDAAuD;QACvD,gBAAgB,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAA;KACpF,CAAC,CAAA;CACH,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+DG;AACH,wBAAsB,MAAM,CAAC,KAAK,EAAE,aAAa,GAAG,MAAM,EAAE,MAAM,EAAE,MAAM,oBAmLzE"}
@@ -111,7 +111,8 @@ async function getHash(value) {
111
111
  const hashBuffer = await crypto.subtle.digest("SHA-1", data);
112
112
  const hashArray = Array.from(new Uint8Array(hashBuffer));
113
113
  const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
114
- return hashHex.slice(0, 7);
114
+ const hash = hashHex.substring(0, 7);
115
+ return hash.match(/^\d+$/) ? "a" + hash.substring(1) : hash;
115
116
  }
116
117
  async function bundle(input, config) {
117
118
  const cache = config.cache ?? /* @__PURE__ */ new Map();
@@ -123,19 +124,31 @@ async function bundle(input, config) {
123
124
  if (result.ok) {
124
125
  return result.data;
125
126
  }
126
- throw "Please provide a valid string value or pass a loader to process the input";
127
+ throw new Error(
128
+ "Failed to resolve input: Please provide a valid string value or pass a loader to process the input"
129
+ );
127
130
  };
128
131
  const rawSpecification = await resolveInput();
129
132
  const documentRoot = config.root ?? rawSpecification;
130
133
  const EXTERNAL_KEY = "x-ext";
131
134
  const EXTERNAL_URL_MAPPING = "x-ext-urls";
132
- const bundler = async (root, origin = typeof input === "string" ? input : "") => {
135
+ const isPartialBundling = config.root !== void 0 && config.root !== rawSpecification;
136
+ const processedNodes = config.visitedNodes ?? /* @__PURE__ */ new Set();
137
+ const bundler = async (root, origin = typeof input === "string" ? input : "", isChunkParent = false) => {
133
138
  if (!isObject(root) && !Array.isArray(root)) {
134
139
  return;
135
140
  }
141
+ if (processedNodes.has(root)) {
142
+ return;
143
+ }
144
+ processedNodes.add(root);
136
145
  if (typeof root === "object" && "$ref" in root && typeof root["$ref"] === "string") {
137
146
  const ref = root["$ref"];
147
+ const isChunk = "$global" in root && typeof root["$global"] === "boolean" && root["$global"];
138
148
  if (isLocalRef(ref)) {
149
+ if (isPartialBundling) {
150
+ await bundler(getNestedValue(documentRoot, getSegmentsFromPath(ref.substring(1))), origin, isChunkParent);
151
+ }
139
152
  return;
140
153
  }
141
154
  const [prefix, path2 = ""] = ref.split("#", 2);
@@ -145,11 +158,14 @@ async function bundle(input, config) {
145
158
  if (!seen) {
146
159
  cache.set(resolvedPath, resolveContents(resolvedPath, config.plugins));
147
160
  }
161
+ config?.hooks?.onResolveStart?.(root);
148
162
  const result = await cache.get(resolvedPath);
149
163
  if (result.ok) {
150
164
  if (!seen) {
151
- prefixInternalRefRecursive(result.data, [EXTERNAL_KEY, hashPath]);
152
- await bundler(result.data, resolvedPath);
165
+ if (!isChunk) {
166
+ prefixInternalRefRecursive(result.data, [EXTERNAL_KEY, hashPath]);
167
+ }
168
+ await bundler(result.data, isChunk ? origin : resolvedPath, isChunk);
153
169
  if (config.urlMap) {
154
170
  setValueAtPath(documentRoot, `/${EXTERNAL_URL_MAPPING}/${escapeJsonPointer(resolvedPath)}`, hashPath);
155
171
  }
@@ -166,8 +182,10 @@ async function bundle(input, config) {
166
182
  setValueAtPath(documentRoot, `/${EXTERNAL_KEY}/${hashPath}`, result.data);
167
183
  }
168
184
  root.$ref = prefixInternalRef(`#${path2}`, [EXTERNAL_KEY, hashPath]);
185
+ config?.hooks?.onResolveSuccess?.(root);
169
186
  return;
170
187
  }
188
+ config?.hooks?.onResolveError?.(root);
171
189
  return console.warn(
172
190
  `Failed to resolve external reference "${prefix}". The reference may be invalid, inaccessible, or missing a loader for this type of reference.`
173
191
  );
@@ -177,7 +195,7 @@ async function bundle(input, config) {
177
195
  if (key === EXTERNAL_KEY) {
178
196
  return;
179
197
  }
180
- await bundler(value, origin);
198
+ await bundler(value, origin, isChunkParent);
181
199
  })
182
200
  );
183
201
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/utils/bundle/bundle.ts"],
4
- "sourcesContent": ["import type { UnknownObject } from '@/types'\nimport { escapeJsonPointer } from '@/utils/escape-json-pointer'\nimport path from '@/polyfills/path'\nimport { getSegmentsFromPath } from '@/utils/get-segments-from-path'\nimport { isObject } from '@/utils/is-object'\n\n/**\n * Checks if a string is a remote URL (starts with http:// or https://)\n * @param value - The URL string to check\n * @returns true if the string is a remote URL, false otherwise\n * @example\n * ```ts\n * isRemoteUrl('https://example.com/schema.json') // true\n * isRemoteUrl('http://api.example.com/schemas/user.json') // true\n * isRemoteUrl('#/components/schemas/User') // false\n * isRemoteUrl('./local-schema.json') // false\n * ```\n */\nexport function isRemoteUrl(value: string): boolean {\n return value.startsWith('http://') || value.startsWith('https://')\n}\n\n/**\n * Checks if a string is a local reference (starts with #)\n * @param value - The reference string to check\n * @returns true if the string is a local reference, false otherwise\n * @example\n * ```ts\n * isLocalRef('#/components/schemas/User') // true\n * isLocalRef('https://example.com/schema.json') // false\n * isLocalRef('./local-schema.json') // false\n * ```\n */\nexport function isLocalRef(value: string): boolean {\n return value.startsWith('#')\n}\n\nexport type ResolveResult = { ok: true; data: unknown } | { ok: false }\n\n/**\n * Resolves a string by finding and executing the appropriate plugin.\n * @param value - The string to resolve (URL, file path, etc)\n * @param plugins - Array of plugins that can handle different types of strings\n * @returns A promise that resolves to either the content or an error result\n * @example\n * // Using a URL plugin\n * await resolveContents('https://example.com/schema.json', [urlPlugin])\n * // Using a file plugin\n * await resolveContents('./schemas/user.json', [filePlugin])\n * // No matching plugin returns { ok: false }\n * await resolveContents('#/components/schemas/User', [urlPlugin, filePlugin])\n */\nasync function resolveContents(value: string, plugins: Plugin[]): Promise<ResolveResult> {\n const plugin = plugins.find((p) => p.validate(value))\n\n if (plugin) {\n return plugin.exec(value)\n }\n\n return {\n ok: false,\n }\n}\n\n/**\n * Retrieves a nested value from an object using an array of property segments.\n * @param target - The target object to traverse\n * @param segments - Array of property names representing the path to the desired value\n * @returns The value at the specified path, or undefined if the path doesn't exist\n * @example\n * const obj = { foo: { bar: { baz: 42 } } };\n * getNestedValue(obj, ['foo', 'bar', 'baz']); // returns 42\n */\nexport function getNestedValue(target: Record<string, any>, segments: string[]) {\n return segments.reduce<any>((acc, key) => {\n if (acc === undefined) {\n return undefined\n }\n return acc[key]\n }, target)\n}\n\n/**\n * Sets a value at a specified path in an object, creating intermediate objects/arrays as needed.\n * This function traverses the object structure and creates any missing intermediate objects\n * or arrays based on the path segments. If the next segment is a numeric string, it creates\n * an array instead of an object.\n *\n * @param obj - The target object to set the value in\n * @param path - The JSON pointer path where the value should be set\n * @param value - The value to set at the specified path\n * @throws {Error} If attempting to set a value at the root path ('')\n *\n * @example\n * const obj = {}\n * setValueAtPath(obj, '/foo/bar/0', 'value')\n * // Result:\n * // {\n * // foo: {\n * // bar: ['value']\n * // }\n * // }\n *\n * @example\n * const obj = { existing: { path: 'old' } }\n * setValueAtPath(obj, '/existing/path', 'new')\n * // Result:\n * // {\n * // existing: {\n * // path: 'new'\n * // }\n * // }\n */\nexport function setValueAtPath(obj: any, path: string, value: any): void {\n if (path === '') {\n throw new Error(\"Cannot set value at root ('') pointer\")\n }\n\n const parts = getSegmentsFromPath(path)\n\n let current = obj\n\n for (let i = 0; i < parts.length; i++) {\n const key = parts[i]\n const isLast = i === parts.length - 1\n\n const nextKey = parts[i + 1]\n const shouldBeArray = /^\\d+$/.test(nextKey ?? '')\n\n if (isLast) {\n current[key] = value\n } else {\n if (!(key in current) || typeof current[key] !== 'object') {\n current[key] = shouldBeArray ? [] : {}\n }\n current = current[key]\n }\n }\n}\n\n/**\n * Resolves a reference path by combining a base path with a relative path.\n * Handles both remote URLs and local file paths.\n *\n * @param base - The base path (can be a URL or local file path)\n * @param relativePath - The relative path to resolve against the base\n * @returns The resolved absolute path\n * @example\n * // Resolve remote URL\n * resolveReferencePath('https://example.com/api/schema.json', 'user.json')\n * // Returns: 'https://example.com/api/user.json'\n *\n * // Resolve local path\n * resolveReferencePath('/path/to/schema.json', 'user.json')\n * // Returns: '/path/to/user.json'\n */\nfunction resolveReferencePath(base: string, relativePath: string) {\n if (isRemoteUrl(relativePath)) {\n return relativePath\n }\n\n if (isRemoteUrl(base)) {\n const url = new URL(base)\n\n const mergedPath = path.join(path.dirname(url.pathname), relativePath)\n return new URL(mergedPath, base).toString()\n }\n\n return path.join(path.dirname(base), relativePath)\n}\n\n/**\n * Prefixes an internal JSON reference with a given path prefix.\n * Takes a local reference (starting with #) and prepends the provided prefix segments.\n *\n * @param input - The internal reference string to prefix (must start with #)\n * @param prefix - Array of path segments to prepend to the reference\n * @returns The prefixed reference string\n * @throws Error if input is not a local reference\n * @example\n * prefixInternalRef('#/components/schemas/User', ['definitions'])\n * // Returns: '#/definitions/components/schemas/User'\n */\nexport function prefixInternalRef(input: string, prefix: string[]) {\n if (!isLocalRef(input)) {\n throw 'Please provide an internal ref'\n }\n\n return `#/${prefix.map(escapeJsonPointer).join('/')}${input.substring(1)}`\n}\n\n/**\n * Updates internal references in an object by adding a prefix to their paths.\n * Recursively traverses the input object and modifies any local $ref references\n * by prepending the given prefix to their paths. This is used when embedding external\n * documents to maintain correct reference paths relative to the main document.\n *\n * @param input - The object to update references in\n * @param prefix - Array of path segments to prepend to internal reference paths\n * @returns void\n * @example\n * ```ts\n * const input = {\n * foo: {\n * $ref: '#/components/schemas/User'\n * }\n * }\n * prefixInternalRefRecursive(input, ['definitions'])\n * // Result:\n * // {\n * // foo: {\n * // $ref: '#/definitions/components/schemas/User'\n * // }\n * // }\n * ```\n */\nexport function prefixInternalRefRecursive(input: unknown, prefix: string[]) {\n if (!isObject(input)) {\n return\n }\n\n Object.values(input).forEach((el) => prefixInternalRefRecursive(el, prefix))\n\n if (typeof input === 'object' && '$ref' in input && typeof input['$ref'] === 'string') {\n const ref = input['$ref']\n\n if (!isLocalRef(ref)) {\n return\n }\n\n return (input['$ref'] = prefixInternalRef(ref, prefix))\n }\n}\n\n/**\n * Resolves and copies referenced values from a source document to a target document.\n * This function traverses the document and copies referenced values to the target document,\n * while tracking processed references to avoid duplicates. It only processes references\n * that belong to the same external document.\n *\n * @param targetDocument - The document to copy referenced values to\n * @param sourceDocument - The source document containing the references\n * @param referencePath - The JSON pointer path to the reference\n * @param externalRefsKey - The key used for external references (e.g. 'x-ext')\n * @param documentKey - The key identifying the external document\n * @param processedNodes - Set of already processed nodes to prevent duplicates\n * @example\n * ```ts\n * const source = {\n * components: {\n * schemas: {\n * User: {\n * $ref: '#/x-ext/users~1schema/definitions/Person'\n * }\n * }\n * }\n * }\n *\n * const target = {}\n * resolveAndCopyReferences(\n * target,\n * source,\n * '/components/schemas/User',\n * 'x-ext',\n * 'users/schema'\n * )\n * // Result: target will contain the User schema with resolved references\n * ```\n */\nconst resolveAndCopyReferences = (\n targetDocument: unknown,\n sourceDocument: unknown,\n referencePath: string,\n externalRefsKey: string,\n documentKey: string,\n processedNodes = new Set(),\n) => {\n const referencedValue = getNestedValue(sourceDocument, getSegmentsFromPath(referencePath))\n\n if (processedNodes.has(referencedValue)) {\n return\n }\n processedNodes.add(referencedValue)\n\n setValueAtPath(targetDocument, referencePath, referencedValue)\n\n // Do the same for each local ref\n const traverse = (node: unknown) => {\n if (!node || typeof node !== 'object') {\n return\n }\n\n if ('$ref' in node && typeof node['$ref'] === 'string') {\n // We only process references from the same external document because:\n // 1. Other documents will be handled in separate recursive branches\n // 2. The source document only contains the current document's content\n // This prevents undefined behavior and maintains proper document boundaries\n if (node['$ref'].startsWith(`#/${externalRefsKey}/${escapeJsonPointer(documentKey)}`)) {\n resolveAndCopyReferences(\n targetDocument,\n sourceDocument,\n node['$ref'].substring(1),\n documentKey,\n externalRefsKey,\n processedNodes,\n )\n }\n }\n\n for (const value of Object.values(node)) {\n traverse(value)\n }\n }\n\n traverse(referencedValue)\n}\n\n/**\n * Generates a short SHA-1 hash from a string value.\n * This function is used to create unique identifiers for external references\n * while keeping the hash length manageable. It uses the Web Crypto API to\n * generate a SHA-1 hash and returns the first 7 characters of the hex string.\n *\n * @param value - The string to hash\n * @returns A 7-character hexadecimal hash\n * @example\n * // Returns \"a1b2c3d\"\n * getHash(\"https://example.com/schema.json\")\n */\nexport async function getHash(value: string) {\n // Convert string to ArrayBuffer\n const encoder = new TextEncoder()\n const data = encoder.encode(value)\n\n // Hash the data\n const hashBuffer = await crypto.subtle.digest('SHA-1', data)\n\n // Convert buffer to hex string\n const hashArray = Array.from(new Uint8Array(hashBuffer))\n const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')\n\n return hashHex.slice(0, 7)\n}\n\n/**\n * Represents a plugin that handles resolving references from external sources.\n * Plugins are responsible for fetching and processing data from different sources\n * like URLs or the filesystem. Each plugin must implement validation to determine\n * if it can handle a specific reference, and an execution function to perform\n * the actual resolution.\n *\n * @property validate - Determines if this plugin can handle the given reference\n * @property exec - Fetches and processes the reference, returning the resolved data\n */\nexport type Plugin = {\n // Determines if this plugin can handle the given reference value\n validate: (value: string) => boolean\n // Fetches and processes the reference, returning the resolved data\n exec: (value: string) => Promise<ResolveResult>\n}\n\ntype Config = {\n // Array of plugins that handle resolving references from different sources (URLs, files, etc.)\n plugins: Plugin[]\n // Optional root object that serves as the base document when bundling a subpart of the document\n // This allows resolving references relative to the root document's location\n root?: UnknownObject\n // Optional cache to store promises of resolved references to avoid duplicate fetches/reads\n cache?: Map<string, Promise<ResolveResult>>\n // Enable tree shaking, which removes unused references from the final bundle\n treeShake: boolean\n // Optional flag to generate a URL map that tracks the original source URLs of bundled references\n urlMap?: boolean\n}\n\n/**\n * Bundles an OpenAPI specification by resolving all external references.\n * This function traverses the input object recursively and embeds external $ref\n * references into an x-ext section. External references can be URLs or local files.\n * The original $refs are updated to point to their embedded content in the x-ext section.\n * If the input is an object, it will be modified in place by adding an x-ext\n * property to store resolved external references.\n *\n * @param input - The OpenAPI specification object or string to bundle. If a string is provided,\n * it should be a URL or file path that points to an OpenAPI specification.\n * The string will be resolved using the provided plugins before bundling.\n * @param config - Configuration object containing plugins for resolving references\n * @returns A promise that resolves to the bundled specification with all references embedded\n * @example\n * // Example with object input\n * const spec = {\n * paths: {\n * '/users': {\n * $ref: 'https://example.com/schemas/users.yaml'\n * }\n * }\n * }\n *\n * const bundled = await bundle(spec, { plugins: [fetchUrls()] })\n * // Result:\n * // {\n * // paths: {\n * // '/users': {\n * // $ref: '#/x-ext/https~1~1example.com~1schemas~1users.yaml'\n * // }\n * // },\n * // 'x-ext': {\n * // 'https~1~1example.com~1schemas~1users.yaml': {\n * // // Resolved content from users.yaml\n * // }\n * // }\n * // }\n *\n * // Example with URL input\n * const bundledFromUrl = await bundle('https://example.com/openapi.yaml', { plugins: [fetchUrls()] })\n * // The function will first fetch the OpenAPI spec from the URL,\n * // then bundle all its external references into the x-ext section\n */\nexport async function bundle(input: UnknownObject | string, config: Config) {\n // Cache for storing promises of resolved external references (URLs and local files)\n // to avoid duplicate fetches/reads of the same resource\n const cache = config.cache ?? new Map<string, Promise<ResolveResult>>()\n\n /**\n * Resolves the input value by either returning it directly if it's not a string,\n * or attempting to resolve it using the provided plugins if it is a string.\n * @returns The resolved input data or throws an error if resolution fails\n */\n const resolveInput = async () => {\n if (typeof input !== 'string') {\n return input\n }\n const result = await resolveContents(input, config.plugins)\n\n if (result.ok) {\n return result.data\n }\n\n throw 'Please provide a valid string value or pass a loader to process the input'\n }\n\n const rawSpecification = await resolveInput()\n\n // Document root used to write all external documents\n // We need this when we want to do a partial bundle of a document\n const documentRoot = config.root ?? rawSpecification\n\n // Custom OpenAPI extension key used to store external references\n // This key will contain all bundled external documents\n const EXTERNAL_KEY = 'x-ext'\n\n // Custom OpenAPI extension key used to maintain a mapping between\n // original URLs and their corresponding hashed keys in x-ext\n const EXTERNAL_URL_MAPPING = 'x-ext-urls'\n\n const bundler = async (root: any, origin: string = typeof input === 'string' ? input : '') => {\n if (!isObject(root) && !Array.isArray(root)) {\n return\n }\n\n if (typeof root === 'object' && '$ref' in root && typeof root['$ref'] === 'string') {\n const ref = root['$ref']\n\n if (isLocalRef(ref)) {\n return\n }\n\n const [prefix, path = ''] = ref.split('#', 2)\n\n // Combine the current origin with the new path to resolve relative references\n // correctly within the context of the external file being processed\n const resolvedPath = resolveReferencePath(origin, prefix)\n const hashPath = await getHash(resolvedPath)\n\n const seen = cache.has(resolvedPath)\n\n if (!seen) {\n cache.set(resolvedPath, resolveContents(resolvedPath, config.plugins))\n }\n\n // Resolve the remote document\n const result = await cache.get(resolvedPath)\n\n if (result.ok) {\n // Process the result only once to avoid duplicate processing and prevent multiple prefixing\n // of internal references, which would corrupt the reference paths\n if (!seen) {\n // Update internal references in the resolved document to use the correct base path.\n // When we embed external documents, their internal references need to be updated to\n // maintain the correct path context relative to the main document. This is crucial\n // because internal references in the external document are relative to its original\n // location, but when embedded, they need to be relative to their new location in\n // the main document's x-ext section. Without this update, internal references\n // would point to incorrect locations and break the document structure.\n prefixInternalRefRecursive(result.data, [EXTERNAL_KEY, hashPath])\n\n // Recursively process the resolved content\n // to handle any nested references it may contain. We pass the resolvedPath as the new origin\n // to ensure any relative references within this content are resolved correctly relative to\n // their new location in the bundled document.\n await bundler(result.data, resolvedPath)\n\n // Store the mapping between original URLs and their hashed keys in x-ext-urls\n // This allows tracking which external URLs were bundled and their corresponding locations\n if (config.urlMap) {\n setValueAtPath(documentRoot, `/${EXTERNAL_URL_MAPPING}/${escapeJsonPointer(resolvedPath)}`, hashPath)\n }\n }\n\n if (config.treeShake === true) {\n // Store only the subtree that is actually used\n // This optimizes the bundle size by only including the parts of the external document\n // that are referenced, rather than the entire document\n resolveAndCopyReferences(\n documentRoot,\n { [EXTERNAL_KEY]: { [hashPath]: result.data } },\n prefixInternalRef(`#${path}`, [EXTERNAL_KEY, hashPath]).substring(1),\n EXTERNAL_KEY,\n hashPath,\n )\n } else if (!seen) {\n // Store the external document in the main document's x-ext key\n // When tree shaking is disabled, we include the entire external document\n // This preserves all content and is faster since we don't need to analyze and copy\n // specific parts. This approach is ideal when storing the result in memory\n // as it avoids the overhead of tree shaking operations\n setValueAtPath(documentRoot, `/${EXTERNAL_KEY}/${hashPath}`, result.data)\n }\n\n // Update the $ref to point to the embedded document in x-ext\n // This is necessary because we need to maintain the correct path context\n // for the embedded document while preserving its internal structure\n root.$ref = prefixInternalRef(`#${path}`, [EXTERNAL_KEY, hashPath])\n return\n }\n\n return console.warn(\n `Failed to resolve external reference \"${prefix}\". The reference may be invalid, inaccessible, or missing a loader for this type of reference.`,\n )\n }\n\n // Recursively process all child objects to handle nested references\n // This ensures we catch and resolve any $refs that exist deeper in the object tree\n // We skip EXTERNAL_KEY to avoid processing already bundled content\n await Promise.all(\n Object.entries(root).map(async ([key, value]) => {\n if (key === EXTERNAL_KEY) {\n return\n }\n\n await bundler(value, origin)\n }),\n )\n }\n\n await bundler(rawSpecification)\n return rawSpecification\n}\n"],
5
- "mappings": "AACA,SAAS,yBAAyB;AAClC,OAAO,UAAU;AACjB,SAAS,2BAA2B;AACpC,SAAS,gBAAgB;AAclB,SAAS,YAAY,OAAwB;AAClD,SAAO,MAAM,WAAW,SAAS,KAAK,MAAM,WAAW,UAAU;AACnE;AAaO,SAAS,WAAW,OAAwB;AACjD,SAAO,MAAM,WAAW,GAAG;AAC7B;AAiBA,eAAe,gBAAgB,OAAe,SAA2C;AACvF,QAAM,SAAS,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,KAAK,CAAC;AAEpD,MAAI,QAAQ;AACV,WAAO,OAAO,KAAK,KAAK;AAAA,EAC1B;AAEA,SAAO;AAAA,IACL,IAAI;AAAA,EACN;AACF;AAWO,SAAS,eAAe,QAA6B,UAAoB;AAC9E,SAAO,SAAS,OAAY,CAAC,KAAK,QAAQ;AACxC,QAAI,QAAQ,QAAW;AACrB,aAAO;AAAA,IACT;AACA,WAAO,IAAI,GAAG;AAAA,EAChB,GAAG,MAAM;AACX;AAiCO,SAAS,eAAe,KAAUA,OAAc,OAAkB;AACvE,MAAIA,UAAS,IAAI;AACf,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AAEA,QAAM,QAAQ,oBAAoBA,KAAI;AAEtC,MAAI,UAAU;AAEd,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,UAAM,MAAM,MAAM,CAAC;AACnB,UAAM,SAAS,MAAM,MAAM,SAAS;AAEpC,UAAM,UAAU,MAAM,IAAI,CAAC;AAC3B,UAAM,gBAAgB,QAAQ,KAAK,WAAW,EAAE;AAEhD,QAAI,QAAQ;AACV,cAAQ,GAAG,IAAI;AAAA,IACjB,OAAO;AACL,UAAI,EAAE,OAAO,YAAY,OAAO,QAAQ,GAAG,MAAM,UAAU;AACzD,gBAAQ,GAA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IAAI,YAAY,IAAI,QAAQ,IAAI,OAAO,IAAI;AAAA,QAC1E;AAKA,aAAK,OAAO,kBAAkB,IAAIA,KAAI,IAAI,CAAC,cAAc,QAAQ,CAAC;AAClE;AAAA,MACF;AAEA,aAAO,QAAQ;AAAA,QACb,yCAAyC,MAAM;AAAA,MACjD;AAAA,IACF;AAKA,UAAM,QAAQ;AAAA,MACZ,OAAO,QAAQ,IAAI,EAAE,IAAI,OAAO,CAAC,KAAK,KAAK,MAAM;AAC/C,YAAI,QAAQ,cAAc;AACxB;AAAA,QACF;AAEA,cAAM,QAAQ,OAAO,MAAM;AAAA,MAC7B,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,QAAQ,gBAAgB;AAC9B,SAAO;AACT;",
4
+ "sourcesContent": ["import type { UnknownObject } from '@/types'\nimport { escapeJsonPointer } from '@/utils/escape-json-pointer'\nimport path from '@/polyfills/path'\nimport { getSegmentsFromPath } from '@/utils/get-segments-from-path'\nimport { isObject } from '@/utils/is-object'\n\n/**\n * Checks if a string is a remote URL (starts with http:// or https://)\n * @param value - The URL string to check\n * @returns true if the string is a remote URL, false otherwise\n * @example\n * ```ts\n * isRemoteUrl('https://example.com/schema.json') // true\n * isRemoteUrl('http://api.example.com/schemas/user.json') // true\n * isRemoteUrl('#/components/schemas/User') // false\n * isRemoteUrl('./local-schema.json') // false\n * ```\n */\nexport function isRemoteUrl(value: string): boolean {\n return value.startsWith('http://') || value.startsWith('https://')\n}\n\n/**\n * Checks if a string is a local reference (starts with #)\n * @param value - The reference string to check\n * @returns true if the string is a local reference, false otherwise\n * @example\n * ```ts\n * isLocalRef('#/components/schemas/User') // true\n * isLocalRef('https://example.com/schema.json') // false\n * isLocalRef('./local-schema.json') // false\n * ```\n */\nexport function isLocalRef(value: string): boolean {\n return value.startsWith('#')\n}\n\nexport type ResolveResult = { ok: true; data: unknown } | { ok: false }\n\n/**\n * Resolves a string by finding and executing the appropriate plugin.\n * @param value - The string to resolve (URL, file path, etc)\n * @param plugins - Array of plugins that can handle different types of strings\n * @returns A promise that resolves to either the content or an error result\n * @example\n * // Using a URL plugin\n * await resolveContents('https://example.com/schema.json', [urlPlugin])\n * // Using a file plugin\n * await resolveContents('./schemas/user.json', [filePlugin])\n * // No matching plugin returns { ok: false }\n * await resolveContents('#/components/schemas/User', [urlPlugin, filePlugin])\n */\nasync function resolveContents(value: string, plugins: Plugin[]): Promise<ResolveResult> {\n const plugin = plugins.find((p) => p.validate(value))\n\n if (plugin) {\n return plugin.exec(value)\n }\n\n return {\n ok: false,\n }\n}\n\n/**\n * Retrieves a nested value from an object using an array of property segments.\n * @param target - The target object to traverse\n * @param segments - Array of property names representing the path to the desired value\n * @returns The value at the specified path, or undefined if the path doesn't exist\n * @example\n * const obj = { foo: { bar: { baz: 42 } } };\n * getNestedValue(obj, ['foo', 'bar', 'baz']); // returns 42\n */\nexport function getNestedValue(target: Record<string, any>, segments: string[]) {\n return segments.reduce<any>((acc, key) => {\n if (acc === undefined) {\n return undefined\n }\n return acc[key]\n }, target)\n}\n\n/**\n * Sets a value at a specified path in an object, creating intermediate objects/arrays as needed.\n * This function traverses the object structure and creates any missing intermediate objects\n * or arrays based on the path segments. If the next segment is a numeric string, it creates\n * an array instead of an object.\n *\n * \u26A0\uFE0F Warning: Be careful with object keys that look like numbers (e.g. \"123\") as this function\n * will interpret them as array indices and create arrays instead of objects. If you need to\n * use numeric-looking keys, consider prefixing them with a non-numeric character.\n *\n * @param obj - The target object to set the value in\n * @param path - The JSON pointer path where the value should be set\n * @param value - The value to set at the specified path\n * @throws {Error} If attempting to set a value at the root path ('')\n *\n * @example\n * const obj = {}\n * setValueAtPath(obj, '/foo/bar/0', 'value')\n * // Result:\n * // {\n * // foo: {\n * // bar: ['value']\n * // }\n * // }\n *\n * @example\n * const obj = { existing: { path: 'old' } }\n * setValueAtPath(obj, '/existing/path', 'new')\n * // Result:\n * // {\n * // existing: {\n * // path: 'new'\n * // }\n * // }\n *\n * @example\n * // \u26A0\uFE0F Warning: This will create an array instead of an object with key \"123\"\n * setValueAtPath(obj, '/foo/123/bar', 'value')\n * // Result:\n * // {\n * // foo: [\n * // undefined,\n * // undefined,\n * // undefined,\n * // { bar: 'value' }\n * // ]\n * // }\n */\nexport function setValueAtPath(obj: any, path: string, value: any): void {\n if (path === '') {\n throw new Error(\"Cannot set value at root ('') pointer\")\n }\n\n const parts = getSegmentsFromPath(path)\n\n let current = obj\n\n for (let i = 0; i < parts.length; i++) {\n const key = parts[i]\n const isLast = i === parts.length - 1\n\n const nextKey = parts[i + 1]\n const shouldBeArray = /^\\d+$/.test(nextKey ?? '')\n\n if (isLast) {\n current[key] = value\n } else {\n if (!(key in current) || typeof current[key] !== 'object') {\n current[key] = shouldBeArray ? [] : {}\n }\n current = current[key]\n }\n }\n}\n\n/**\n * Resolves a reference path by combining a base path with a relative path.\n * Handles both remote URLs and local file paths.\n *\n * @param base - The base path (can be a URL or local file path)\n * @param relativePath - The relative path to resolve against the base\n * @returns The resolved absolute path\n * @example\n * // Resolve remote URL\n * resolveReferencePath('https://example.com/api/schema.json', 'user.json')\n * // Returns: 'https://example.com/api/user.json'\n *\n * // Resolve local path\n * resolveReferencePath('/path/to/schema.json', 'user.json')\n * // Returns: '/path/to/user.json'\n */\nfunction resolveReferencePath(base: string, relativePath: string) {\n if (isRemoteUrl(relativePath)) {\n return relativePath\n }\n\n if (isRemoteUrl(base)) {\n const url = new URL(base)\n\n const mergedPath = path.join(path.dirname(url.pathname), relativePath)\n return new URL(mergedPath, base).toString()\n }\n\n return path.join(path.dirname(base), relativePath)\n}\n\n/**\n * Prefixes an internal JSON reference with a given path prefix.\n * Takes a local reference (starting with #) and prepends the provided prefix segments.\n *\n * @param input - The internal reference string to prefix (must start with #)\n * @param prefix - Array of path segments to prepend to the reference\n * @returns The prefixed reference string\n * @throws Error if input is not a local reference\n * @example\n * prefixInternalRef('#/components/schemas/User', ['definitions'])\n * // Returns: '#/definitions/components/schemas/User'\n */\nexport function prefixInternalRef(input: string, prefix: string[]) {\n if (!isLocalRef(input)) {\n throw 'Please provide an internal ref'\n }\n\n return `#/${prefix.map(escapeJsonPointer).join('/')}${input.substring(1)}`\n}\n\n/**\n * Updates internal references in an object by adding a prefix to their paths.\n * Recursively traverses the input object and modifies any local $ref references\n * by prepending the given prefix to their paths. This is used when embedding external\n * documents to maintain correct reference paths relative to the main document.\n *\n * @param input - The object to update references in\n * @param prefix - Array of path segments to prepend to internal reference paths\n * @returns void\n * @example\n * ```ts\n * const input = {\n * foo: {\n * $ref: '#/components/schemas/User'\n * }\n * }\n * prefixInternalRefRecursive(input, ['definitions'])\n * // Result:\n * // {\n * // foo: {\n * // $ref: '#/definitions/components/schemas/User'\n * // }\n * // }\n * ```\n */\nexport function prefixInternalRefRecursive(input: unknown, prefix: string[]) {\n if (!isObject(input)) {\n return\n }\n\n Object.values(input).forEach((el) => prefixInternalRefRecursive(el, prefix))\n\n if (typeof input === 'object' && '$ref' in input && typeof input['$ref'] === 'string') {\n const ref = input['$ref']\n\n if (!isLocalRef(ref)) {\n return\n }\n\n return (input['$ref'] = prefixInternalRef(ref, prefix))\n }\n}\n\n/**\n * Resolves and copies referenced values from a source document to a target document.\n * This function traverses the document and copies referenced values to the target document,\n * while tracking processed references to avoid duplicates. It only processes references\n * that belong to the same external document.\n *\n * @param targetDocument - The document to copy referenced values to\n * @param sourceDocument - The source document containing the references\n * @param referencePath - The JSON pointer path to the reference\n * @param externalRefsKey - The key used for external references (e.g. 'x-ext')\n * @param documentKey - The key identifying the external document\n * @param processedNodes - Set of already processed nodes to prevent duplicates\n * @example\n * ```ts\n * const source = {\n * components: {\n * schemas: {\n * User: {\n * $ref: '#/x-ext/users~1schema/definitions/Person'\n * }\n * }\n * }\n * }\n *\n * const target = {}\n * resolveAndCopyReferences(\n * target,\n * source,\n * '/components/schemas/User',\n * 'x-ext',\n * 'users/schema'\n * )\n * // Result: target will contain the User schema with resolved references\n * ```\n */\nconst resolveAndCopyReferences = (\n targetDocument: unknown,\n sourceDocument: unknown,\n referencePath: string,\n externalRefsKey: string,\n documentKey: string,\n processedNodes = new Set(),\n) => {\n const referencedValue = getNestedValue(sourceDocument, getSegmentsFromPath(referencePath))\n\n if (processedNodes.has(referencedValue)) {\n return\n }\n processedNodes.add(referencedValue)\n\n setValueAtPath(targetDocument, referencePath, referencedValue)\n\n // Do the same for each local ref\n const traverse = (node: unknown) => {\n if (!node || typeof node !== 'object') {\n return\n }\n\n if ('$ref' in node && typeof node['$ref'] === 'string') {\n // We only process references from the same external document because:\n // 1. Other documents will be handled in separate recursive branches\n // 2. The source document only contains the current document's content\n // This prevents undefined behavior and maintains proper document boundaries\n if (node['$ref'].startsWith(`#/${externalRefsKey}/${escapeJsonPointer(documentKey)}`)) {\n resolveAndCopyReferences(\n targetDocument,\n sourceDocument,\n node['$ref'].substring(1),\n documentKey,\n externalRefsKey,\n processedNodes,\n )\n }\n }\n\n for (const value of Object.values(node)) {\n traverse(value)\n }\n }\n\n traverse(referencedValue)\n}\n\n/**\n * Generates a short SHA-1 hash from a string value.\n * This function is used to create unique identifiers for external references\n * while keeping the hash length manageable. It uses the Web Crypto API to\n * generate a SHA-1 hash and returns the first 7 characters of the hex string.\n * If the hash would be all numbers, it ensures at least one letter is included.\n *\n * @param value - The string to hash\n * @returns A 7-character hexadecimal hash with at least one letter\n * @example\n * // Returns \"2ae91d7\"\n * await getHash(\"https://example.com/schema.json\")\n */\nexport async function getHash(value: string) {\n // Convert string to ArrayBuffer\n const encoder = new TextEncoder()\n const data = encoder.encode(value)\n\n // Hash the data\n const hashBuffer = await crypto.subtle.digest('SHA-1', data)\n\n // Convert buffer to hex string\n const hashArray = Array.from(new Uint8Array(hashBuffer))\n const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')\n\n // Return first 7 characters of the hash, ensuring at least one letter\n const hash = hashHex.substring(0, 7)\n return hash.match(/^\\d+$/) ? 'a' + hash.substring(1) : hash\n}\n\n/**\n * Represents a plugin that handles resolving references from external sources.\n * Plugins are responsible for fetching and processing data from different sources\n * like URLs or the filesystem. Each plugin must implement validation to determine\n * if it can handle a specific reference, and an execution function to perform\n * the actual resolution.\n *\n * @property validate - Determines if this plugin can handle the given reference\n * @property exec - Fetches and processes the reference, returning the resolved data\n */\nexport type Plugin = {\n // Determines if this plugin can handle the given reference value\n validate: (value: string) => boolean\n // Fetches and processes the reference, returning the resolved data\n exec: (value: string) => Promise<ResolveResult>\n}\n\n/**\n * Configuration options for the bundler.\n * Controls how external references are resolved and processed during bundling.\n */\ntype Config = {\n /**\n * Array of plugins that handle resolving references from different sources.\n * Each plugin is responsible for fetching and processing data from specific sources\n * like URLs or the filesystem.\n */\n plugins: Plugin[]\n\n /**\n * Optional root object that serves as the base document when bundling a subpart.\n * This allows resolving references relative to the root document's location,\n * ensuring proper path resolution for nested references.\n */\n root?: UnknownObject\n\n /**\n * Optional cache to store promises of resolved references.\n * Helps avoid duplicate fetches/reads of the same resource by storing\n * the resolution promises for reuse.\n */\n cache?: Map<string, Promise<ResolveResult>>\n\n /**\n * Cache of visited nodes during partial bundling.\n * Used to prevent re-bundling the same tree multiple times when doing partial bundling,\n * improving performance by avoiding redundant processing of already bundled sections.\n */\n visitedNodes?: Set<unknown>\n\n /**\n * Enable tree shaking to optimize the bundle size.\n * When enabled, only the parts of external documents that are actually referenced\n * will be included in the final bundle.\n */\n treeShake: boolean\n\n /**\n * Optional flag to generate a URL map.\n * When enabled, tracks the original source URLs of bundled references\n * in an x-ext-urls section for reference mapping.\n */\n urlMap?: boolean\n\n /**\n * Optional hooks to monitor the bundler's lifecycle.\n * Allows tracking the progress and status of reference resolution.\n */\n hooks?: Partial<{\n /** Called when starting to resolve a reference */\n onResolveStart: (node: Record<string, unknown> & Record<'$ref', unknown>) => void\n /** Called when a reference resolution fails */\n onResolveError: (node: Record<string, unknown> & Record<'$ref', unknown>) => void\n /** Called when a reference is successfully resolved */\n onResolveSuccess: (node: Record<string, unknown> & Record<'$ref', unknown>) => void\n }>\n}\n\n/**\n * Bundles an OpenAPI specification by resolving all external references.\n * This function traverses the input object recursively and embeds external $ref\n * references into an x-ext section. External references can be URLs or local files.\n * The original $refs are updated to point to their embedded content in the x-ext section.\n * If the input is an object, it will be modified in place by adding an x-ext\n * property to store resolved external references.\n *\n * @param input - The OpenAPI specification object or string to bundle. If a string is provided,\n * it should be a URL or file path that points to an OpenAPI specification.\n * The string will be resolved using the provided plugins before bundling.\n * @param config - Configuration object containing plugins and options for bundling OpenAPI specifications\n * @returns A promise that resolves to the bundled specification with all references embedded\n * @example\n * // Example with object input\n * const spec = {\n * paths: {\n * '/users': {\n * $ref: 'https://example.com/schemas/users.yaml'\n * }\n * }\n * }\n *\n * const bundled = await bundle(spec, {\n * plugins: [fetchUrls()],\n * treeShake: true,\n * urlMap: true,\n * hooks: {\n * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),\n * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),\n * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)\n * }\n * })\n * // Result:\n * // {\n * // paths: {\n * // '/users': {\n * // $ref: '#/x-ext/abc123'\n * // }\n * // },\n * // 'x-ext': {\n * // 'abc123': {\n * // // Resolved content from users.yaml\n * // }\n * // },\n * // 'x-ext-urls': {\n * // 'https://example.com/schemas/users.yaml': 'abc123'\n * // }\n * // }\n *\n * // Example with URL input\n * const bundledFromUrl = await bundle('https://example.com/openapi.yaml', {\n * plugins: [fetchUrls()],\n * treeShake: true,\n * urlMap: true,\n * hooks: {\n * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),\n * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),\n * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)\n * }\n * })\n * // The function will first fetch the OpenAPI spec from the URL,\n * // then bundle all its external references into the x-ext section\n */\nexport async function bundle(input: UnknownObject | string, config: Config) {\n // Cache for storing promises of resolved external references (URLs and local files)\n // to avoid duplicate fetches/reads of the same resource\n const cache = config.cache ?? new Map<string, Promise<ResolveResult>>()\n\n /**\n * Resolves the input value by either returning it directly if it's not a string,\n * or attempting to resolve it using the provided plugins if it is a string.\n * @returns The resolved input data or throws an error if resolution fails\n */\n const resolveInput = async () => {\n if (typeof input !== 'string') {\n return input\n }\n const result = await resolveContents(input, config.plugins)\n\n if (result.ok) {\n return result.data\n }\n\n throw new Error(\n 'Failed to resolve input: Please provide a valid string value or pass a loader to process the input',\n )\n }\n\n // Resolve the input specification, which could be either a direct object or a string URL/path\n const rawSpecification = await resolveInput()\n\n // Document root used to write all external documents\n // We need this when we want to do a partial bundle of a document\n const documentRoot = config.root ?? rawSpecification\n\n // Custom OpenAPI extension key used to store external references\n // This key will contain all bundled external documents\n const EXTERNAL_KEY = 'x-ext'\n\n // Custom OpenAPI extension key used to maintain a mapping between\n // original URLs and their corresponding hashed keys in x-ext\n const EXTERNAL_URL_MAPPING = 'x-ext-urls'\n\n // Indicates whether we're performing a partial bundle operation, which occurs when\n // a root document is provided that differs from the raw specification being bundled\n const isPartialBundling = config.root !== undefined && config.root !== rawSpecification\n\n // Set of nodes that have already been processed during bundling to prevent duplicate processing\n const processedNodes = config.visitedNodes ?? new Set()\n\n const bundler = async (\n root: unknown,\n origin: string = typeof input === 'string' ? input : '',\n isChunkParent = false,\n ) => {\n if (!isObject(root) && !Array.isArray(root)) {\n return\n }\n\n // Skip if this node has already been processed to prevent infinite recursion\n // and duplicate processing of the same node\n if (processedNodes.has(root)) {\n return\n }\n // Mark this node as processed before continuing\n processedNodes.add(root)\n\n if (typeof root === 'object' && '$ref' in root && typeof root['$ref'] === 'string') {\n const ref = root['$ref']\n const isChunk = '$global' in root && typeof root['$global'] === 'boolean' && root['$global']\n\n if (isLocalRef(ref)) {\n if (isPartialBundling) {\n // When doing partial bundling, we need to recursively bundle all dependencies\n // referenced by this local reference to ensure the partial bundle is complete.\n // This includes not just the direct reference but also all its dependencies,\n // creating a complete and self-contained partial bundle.\n await bundler(getNestedValue(documentRoot, getSegmentsFromPath(ref.substring(1))), origin, isChunkParent)\n }\n return\n }\n\n const [prefix, path = ''] = ref.split('#', 2)\n\n // Combine the current origin with the new path to resolve relative references\n // correctly within the context of the external file being processed\n const resolvedPath = resolveReferencePath(origin, prefix)\n const hashPath = await getHash(resolvedPath)\n\n const seen = cache.has(resolvedPath)\n\n if (!seen) {\n cache.set(resolvedPath, resolveContents(resolvedPath, config.plugins))\n }\n\n config?.hooks?.onResolveStart?.(root)\n\n // Resolve the remote document\n const result = await cache.get(resolvedPath)\n\n if (result.ok) {\n // Process the result only once to avoid duplicate processing and prevent multiple prefixing\n // of internal references, which would corrupt the reference paths\n if (!seen) {\n // Skip prefixing for chunks since they are meant to be self-contained and their\n // internal references should remain relative to their original location. Chunks\n // are typically used for modular components that need to maintain their own\n // reference context without being affected by the main document's structure.\n if (!isChunk) {\n // Update internal references in the resolved document to use the correct base path.\n // When we embed external documents, their internal references need to be updated to\n // maintain the correct path context relative to the main document. This is crucial\n // because internal references in the external document are relative to its original\n // location, but when embedded, they need to be relative to their new location in\n // the main document's x-ext section. Without this update, internal references\n // would point to incorrect locations and break the document structure.\n prefixInternalRefRecursive(result.data, [EXTERNAL_KEY, hashPath])\n }\n\n // Recursively process the resolved content\n // to handle any nested references it may contain. We pass the resolvedPath as the new origin\n // to ensure any relative references within this content are resolved correctly relative to\n // their new location in the bundled document.\n await bundler(result.data, isChunk ? origin : resolvedPath, isChunk)\n\n // Store the mapping between original URLs and their hashed keys in x-ext-urls\n // This allows tracking which external URLs were bundled and their corresponding locations\n if (config.urlMap) {\n setValueAtPath(documentRoot, `/${EXTERNAL_URL_MAPPING}/${escapeJsonPointer(resolvedPath)}`, hashPath)\n }\n }\n\n if (config.treeShake === true) {\n // Store only the subtree that is actually used\n // This optimizes the bundle size by only including the parts of the external document\n // that are referenced, rather than the entire document\n resolveAndCopyReferences(\n documentRoot,\n { [EXTERNAL_KEY]: { [hashPath]: result.data } },\n prefixInternalRef(`#${path}`, [EXTERNAL_KEY, hashPath]).substring(1),\n EXTERNAL_KEY,\n hashPath,\n )\n } else if (!seen) {\n // Store the external document in the main document's x-ext key\n // When tree shaking is disabled, we include the entire external document\n // This preserves all content and is faster since we don't need to analyze and copy\n // specific parts. This approach is ideal when storing the result in memory\n // as it avoids the overhead of tree shaking operations\n setValueAtPath(documentRoot, `/${EXTERNAL_KEY}/${hashPath}`, result.data)\n }\n\n // Update the $ref to point to the embedded document in x-ext\n // This is necessary because we need to maintain the correct path context\n // for the embedded document while preserving its internal structure\n root.$ref = prefixInternalRef(`#${path}`, [EXTERNAL_KEY, hashPath])\n config?.hooks?.onResolveSuccess?.(root)\n return\n }\n\n config?.hooks?.onResolveError?.(root)\n return console.warn(\n `Failed to resolve external reference \"${prefix}\". The reference may be invalid, inaccessible, or missing a loader for this type of reference.`,\n )\n }\n\n // Recursively process all child objects to handle nested references\n // This ensures we catch and resolve any $refs that exist deeper in the object tree\n // We skip EXTERNAL_KEY to avoid processing already bundled content\n await Promise.all(\n Object.entries(root).map(async ([key, value]) => {\n if (key === EXTERNAL_KEY) {\n return\n }\n\n await bundler(value, origin, isChunkParent)\n }),\n )\n }\n\n await bundler(rawSpecification)\n return rawSpecification\n}\n"],
5
+ "mappings": "AACA,SAAS,yBAAyB;AAClC,OAAO,UAAU;AACjB,SAAS,2BAA2B;AACpC,SAAS,gBAAgB;AAclB,SAAS,YAAY,OAAwB;AAClD,SAAO,MAAM,WAAW,SAAS,KAAK,MAAM,WAAW,UAAU;AACnE;AAaO,SAAS,WAAW,OAAwB;AACjD,SAAO,MAAM,WAAW,GAAG;AAC7B;AAiBA,eAAe,gBAAgB,OAAe,SAA2C;AACvF,QAAM,SAAS,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,KAAK,CAAC;AAEpD,MAAI,QAAQ;AACV,WAAO,OAAO,KAAK,KAAK;AAAA,EAC1B;AAEA,SAAO;AAAA,IACL,IAAI;AAAA,EACN;AACF;AAWO,SAAS,eAAe,QAA6B,UAAoB;AAC9E,SAAO,SAAS,OAAY,CAAC,KAAK,QAAQ;AACx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KA,aAAK,OAAO,kBAAkB,IAAIA,KAAI,IAAI,CAAC,cAAc,QAAQ,CAAC;AAClE,gBAAQ,OAAO,mBAAmB,IAAI;AACtC;AAAA,MACF;AAEA,cAAQ,OAAO,iBAAiB,IAAI;AACpC,aAAO,QAAQ;AAAA,QACb,yCAAyC,MAAM;AAAA,MACjD;AAAA,IACF;AAKA,UAAM,QAAQ;AAAA,MACZ,OAAO,QAAQ,IAAI,EAAE,IAAI,OAAO,CAAC,KAAK,KAAK,MAAM;AAC/C,YAAI,QAAQ,cAAc;AACxB;AAAA,QACF;AAEA,cAAM,QAAQ,OAAO,QAAQ,aAAa;AAAA,MAC5C,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,QAAQ,gBAAgB;AAC9B,SAAO;AACT;",
6
6
  "names": ["path"]
7
7
  }
@@ -1,4 +1,4 @@
1
1
  export { bundle } from './bundle.js';
2
- export { fetchUrls } from './plugins/fetch-urls.js';
3
- export { readFiles } from './plugins/read-files.js';
2
+ export { fetchUrls } from './plugins/fetch-urls/index.js';
3
+ export { readFiles } from './plugins/read-files/index.js';
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -1,6 +1,6 @@
1
1
  import { bundle } from "./bundle.js";
2
- import { fetchUrls } from "./plugins/fetch-urls.js";
3
- import { readFiles } from "./plugins/read-files.js";
2
+ import { fetchUrls } from "./plugins/fetch-urls/index.js";
3
+ import { readFiles } from "./plugins/read-files/index.js";
4
4
  export {
5
5
  bundle,
6
6
  fetchUrls,
@@ -1,9 +1,10 @@
1
- import { type Plugin, type ResolveResult } from '../../../utils/bundle/bundle.js';
1
+ import { type Plugin, type ResolveResult } from '../../../../utils/bundle/bundle.js';
2
2
  type FetchConfig = Partial<{
3
3
  headers: {
4
4
  headers: HeadersInit;
5
5
  domains: string[];
6
6
  }[];
7
+ fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response>;
7
8
  }>;
8
9
  /**
9
10
  * Fetches and normalizes data from a remote URL
@@ -35,4 +36,4 @@ export declare function fetchUrls(config?: FetchConfig & Partial<{
35
36
  limit: number | null;
36
37
  }>): Plugin;
37
38
  export {};
38
- //# sourceMappingURL=fetch-urls.d.ts.map
39
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/utils/bundle/plugins/fetch-urls/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,KAAK,MAAM,EAAE,KAAK,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAGpF,KAAK,WAAW,GAAG,OAAO,CAAC;IACzB,OAAO,EAAE;QAAE,OAAO,EAAE,WAAW,CAAC;QAAC,OAAO,EAAE,MAAM,EAAE,CAAA;KAAE,EAAE,CAAA;IACtD,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAA;CAC3F,CAAC,CAAA;AAEF;;;;;;;;;;;;;GAaG;AACH,wBAAsB,QAAQ,CAC5B,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EAChD,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,aAAa,CAAC,CAgCxB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC,GAAG,MAAM,CAQ1F"}
@@ -1,12 +1,13 @@
1
- import { normalize } from "../../../utils/normalize.js";
2
- import { isRemoteUrl } from "../../../utils/bundle/bundle.js";
3
- import { createLimiter } from "../../../utils/bundle/create-limiter.js";
1
+ import { normalize } from "../../../../utils/normalize.js";
2
+ import { isRemoteUrl } from "../../../../utils/bundle/bundle.js";
3
+ import { createLimiter } from "../../../../utils/bundle/create-limiter.js";
4
4
  async function fetchUrl(url, limiter, config) {
5
5
  try {
6
6
  const domain = new URL(url).host;
7
7
  const headers = config?.headers?.find((a) => a.domains.find((d) => d === domain) !== void 0)?.headers;
8
+ const exec = config?.fetch ?? fetch;
8
9
  const result = await limiter(
9
- () => fetch(url, {
10
+ () => exec(url, {
10
11
  headers
11
12
  })
12
13
  );
@@ -37,4 +38,4 @@ export {
37
38
  fetchUrl,
38
39
  fetchUrls
39
40
  };
40
- //# sourceMappingURL=fetch-urls.js.map
41
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/utils/bundle/plugins/fetch-urls/index.ts"],
4
+ "sourcesContent": ["import { normalize } from '@/utils/normalize'\nimport { isRemoteUrl, type Plugin, type ResolveResult } from '@/utils/bundle/bundle'\nimport { createLimiter } from '@/utils/bundle/create-limiter'\n\ntype FetchConfig = Partial<{\n headers: { headers: HeadersInit; domains: string[] }[]\n fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response>\n}>\n\n/**\n * Fetches and normalizes data from a remote URL\n * @param url - The URL to fetch data from\n * @returns A promise that resolves to either the normalized data or an error result\n * @example\n * ```ts\n * const result = await fetchUrl('https://api.example.com/data.json')\n * if (result.ok) {\n * console.log(result.data) // The normalized data\n * } else {\n * console.log('Failed to fetch data')\n * }\n * ```\n */\nexport async function fetchUrl(\n url: string,\n limiter: <T>(fn: () => Promise<T>) => Promise<T>,\n config?: FetchConfig,\n): Promise<ResolveResult> {\n try {\n const domain = new URL(url).host\n\n // Get the headers that match the domain\n const headers = config?.headers?.find((a) => a.domains.find((d) => d === domain) !== undefined)?.headers\n\n const exec = config?.fetch ?? fetch\n\n const result = await limiter(() =>\n exec(url, {\n headers,\n }),\n )\n\n if (result.ok) {\n const body = await result.text()\n\n return {\n ok: true,\n data: normalize(body),\n }\n }\n\n return {\n ok: false,\n }\n } catch {\n return {\n ok: false,\n }\n }\n}\n\n/**\n * Creates a plugin for handling remote URL references.\n * This plugin validates and fetches data from HTTP/HTTPS URLs.\n *\n * @returns A plugin object with validate and exec functions\n * @example\n * const urlPlugin = fetchUrls()\n * if (urlPlugin.validate('https://example.com/schema.json')) {\n * const result = await urlPlugin.exec('https://example.com/schema.json')\n * }\n */\nexport function fetchUrls(config?: FetchConfig & Partial<{ limit: number | null }>): Plugin {\n // If there is a limit specified we limit the number of concurrent calls\n const limiter = config?.limit ? createLimiter(config.limit) : <T>(fn: () => Promise<T>) => fn()\n\n return {\n validate: (value) => isRemoteUrl(value),\n exec: (value) => fetchUrl(value, limiter, config),\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,iBAAiB;AAC1B,SAAS,mBAAoD;AAC7D,SAAS,qBAAqB;AAqB9B,eAAsB,SACpB,KACA,SACA,QACwB;AACxB,MAAI;AACF,UAAM,SAAS,IAAI,IAAI,GAAG,EAAE;AAG5B,UAAM,UAAU,QAAQ,SAAS,KAAK,CAAC,MAAM,EAAE,QAAQ,KAAK,CAAC,MAAM,MAAM,MAAM,MAAM,MAAS,GAAG;AAEjG,UAAM,OAAO,QAAQ,SAAS;AAE9B,UAAM,SAAS,MAAM;AAAA,MAAQ,MAC3B,KAAK,KAAK;AAAA,QACR;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI,OAAO,IAAI;AACb,YAAM,OAAO,MAAM,OAAO,KAAK;AAE/B,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,MAAM,UAAU,IAAI;AAAA,MACtB;AAAA,IACF;AAEA,WAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF;AACF;AAaO,SAAS,UAAU,QAAkE;AAE1F,QAAM,UAAU,QAAQ,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAI,OAAyB,GAAG;AAE9F,SAAO;AAAA,IACL,UAAU,CAAC,UAAU,YAAY,KAAK;AAAA,IACtC,MAAM,CAAC,UAAU,SAAS,OAAO,SAAS,MAAM;AAAA,EAClD;AACF;",
6
+ "names": []
7
+ }
@@ -1,4 +1,4 @@
1
- import { type Plugin, type ResolveResult } from '../../../utils/bundle/bundle.js';
1
+ import { type Plugin, type ResolveResult } from '../../../../utils/bundle/bundle.js';
2
2
  /**
3
3
  * Reads and normalizes data from a local file
4
4
  * @param path - The file path to read from
@@ -26,4 +26,4 @@ export declare function readFile(path: string): Promise<ResolveResult>;
26
26
  * }
27
27
  */
28
28
  export declare function readFiles(): Plugin;
29
- //# sourceMappingURL=read-files.d.ts.map
29
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/utils/bundle/plugins/read-files/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,KAAK,MAAM,EAAE,KAAK,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAEpF;;;;;;;;;;;;;GAaG;AACH,wBAAsB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAmBnE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,IAAI,MAAM,CAKlC"}