@kubb/core 5.0.0-beta.7 → 5.0.0-beta.71

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 (49) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +20 -123
  3. package/dist/diagnostics-CJtO1uSM.d.ts +2892 -0
  4. package/dist/index.cjs +2340 -1129
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.ts +80 -289
  7. package/dist/index.js +2330 -1124
  8. package/dist/index.js.map +1 -1
  9. package/dist/memoryStorage-B4VTTIpQ.js +905 -0
  10. package/dist/memoryStorage-B4VTTIpQ.js.map +1 -0
  11. package/dist/memoryStorage-CfycFGzX.cjs +1043 -0
  12. package/dist/memoryStorage-CfycFGzX.cjs.map +1 -0
  13. package/dist/mocks.cjs +84 -24
  14. package/dist/mocks.cjs.map +1 -1
  15. package/dist/mocks.d.ts +37 -11
  16. package/dist/mocks.js +86 -28
  17. package/dist/mocks.js.map +1 -1
  18. package/package.json +9 -23
  19. package/dist/PluginDriver-BkTRD2H2.js +0 -946
  20. package/dist/PluginDriver-BkTRD2H2.js.map +0 -1
  21. package/dist/PluginDriver-Cadu4ORh.cjs +0 -1037
  22. package/dist/PluginDriver-Cadu4ORh.cjs.map +0 -1
  23. package/dist/types-ChyWgIgi.d.ts +0 -2159
  24. package/src/FileManager.ts +0 -115
  25. package/src/FileProcessor.ts +0 -86
  26. package/src/Kubb.ts +0 -300
  27. package/src/PluginDriver.ts +0 -426
  28. package/src/constants.ts +0 -35
  29. package/src/createAdapter.ts +0 -32
  30. package/src/createKubb.ts +0 -573
  31. package/src/createRenderer.ts +0 -57
  32. package/src/createStorage.ts +0 -70
  33. package/src/defineGenerator.ts +0 -87
  34. package/src/defineLogger.ts +0 -36
  35. package/src/defineMiddleware.ts +0 -62
  36. package/src/defineParser.ts +0 -44
  37. package/src/definePlugin.ts +0 -83
  38. package/src/defineResolver.ts +0 -521
  39. package/src/devtools.ts +0 -59
  40. package/src/index.ts +0 -20
  41. package/src/mocks.ts +0 -178
  42. package/src/renderNode.ts +0 -35
  43. package/src/storages/fsStorage.ts +0 -114
  44. package/src/storages/memoryStorage.ts +0 -55
  45. package/src/types.ts +0 -1305
  46. package/src/utils/diagnostics.ts +0 -18
  47. package/src/utils/isInputPath.ts +0 -10
  48. package/src/utils/packageJSON.ts +0 -99
  49. /package/dist/{chunk--u3MIqq1.js → rolldown-runtime-C0LytTxp.js} +0 -0
@@ -0,0 +1,1043 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __name = (target, value) => __defProp(target, "name", {
5
+ value,
6
+ configurable: true
7
+ });
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ //#endregion
27
+ let node_events = require("node:events");
28
+ let node_fs_promises = require("node:fs/promises");
29
+ let node_path = require("node:path");
30
+ let _kubb_ast = require("@kubb/ast");
31
+ let _kubb_ast_utils = require("@kubb/ast/utils");
32
+ //#region ../../internals/utils/src/errors.ts
33
+ /**
34
+ * Thrown when one or more errors occur during a Kubb build.
35
+ * Carries the full list of underlying errors on `errors`.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * throw new BuildError('Build failed', { errors: [err1, err2] })
40
+ * ```
41
+ */
42
+ var BuildError = class extends Error {
43
+ errors;
44
+ constructor(message, options) {
45
+ super(message, { cause: options.cause });
46
+ this.name = "BuildError";
47
+ this.errors = options.errors;
48
+ }
49
+ };
50
+ /**
51
+ * Coerces an unknown thrown value to an `Error` instance.
52
+ * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * try { ... } catch(err) {
57
+ * throw new BuildError('Build failed', { cause: toError(err), errors: [] })
58
+ * }
59
+ * ```
60
+ */
61
+ function toError(value) {
62
+ return value instanceof Error ? value : new Error(String(value));
63
+ }
64
+ /**
65
+ * Extracts a human-readable message from any thrown value.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * getErrorMessage(new Error('oops')) // 'oops'
70
+ * getErrorMessage('plain string') // 'plain string'
71
+ * ```
72
+ */
73
+ function getErrorMessage(value) {
74
+ return value instanceof Error ? value.message : String(value);
75
+ }
76
+ //#endregion
77
+ //#region ../../internals/utils/src/asyncEventEmitter.ts
78
+ /**
79
+ * Typed `EventEmitter` that awaits all async listeners before resolving.
80
+ * Wraps Node's `EventEmitter` with full TypeScript event-map inference.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
85
+ * emitter.on('build', async (name) => { console.log(name) })
86
+ * await emitter.emit('build', 'petstore') // all listeners awaited
87
+ * ```
88
+ */
89
+ var AsyncEventEmitter = class {
90
+ /**
91
+ * Maximum number of listeners per event before Node emits a memory-leak warning.
92
+ * @default 10
93
+ */
94
+ constructor(maxListener = 10) {
95
+ this.#emitter.setMaxListeners(maxListener);
96
+ }
97
+ #emitter = new node_events.EventEmitter();
98
+ /**
99
+ * Emits `eventName` and awaits all registered listeners sequentially.
100
+ * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * await emitter.emit('build', 'petstore')
105
+ * ```
106
+ */
107
+ emit(eventName, ...eventArgs) {
108
+ const listeners = this.#emitter.listeners(eventName);
109
+ if (listeners.length === 0) return;
110
+ return this.#emitAll(eventName, listeners, eventArgs);
111
+ }
112
+ async #emitAll(eventName, listeners, eventArgs) {
113
+ for (const listener of listeners) try {
114
+ await listener(...eventArgs);
115
+ } catch (err) {
116
+ let serializedArgs;
117
+ try {
118
+ serializedArgs = JSON.stringify(eventArgs);
119
+ } catch {
120
+ serializedArgs = String(eventArgs);
121
+ }
122
+ throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: toError(err) });
123
+ }
124
+ }
125
+ /**
126
+ * Registers a persistent listener for `eventName`.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * emitter.on('build', async (name) => { console.log(name) })
131
+ * ```
132
+ */
133
+ on(eventName, handler) {
134
+ this.#emitter.on(eventName, handler);
135
+ }
136
+ /**
137
+ * Registers a one-shot listener that removes itself after the first invocation.
138
+ *
139
+ * @example
140
+ * ```ts
141
+ * emitter.onOnce('build', async (name) => { console.log(name) })
142
+ * ```
143
+ */
144
+ onOnce(eventName, handler) {
145
+ const wrapper = (...args) => {
146
+ this.off(eventName, wrapper);
147
+ return handler(...args);
148
+ };
149
+ this.on(eventName, wrapper);
150
+ }
151
+ /**
152
+ * Removes a previously registered listener.
153
+ *
154
+ * @example
155
+ * ```ts
156
+ * emitter.off('build', handler)
157
+ * ```
158
+ */
159
+ off(eventName, handler) {
160
+ this.#emitter.off(eventName, handler);
161
+ }
162
+ /**
163
+ * Returns the number of listeners registered for `eventName`.
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * emitter.on('build', handler)
168
+ * emitter.listenerCount('build') // 1
169
+ * ```
170
+ */
171
+ listenerCount(eventName) {
172
+ return this.#emitter.listenerCount(eventName);
173
+ }
174
+ /**
175
+ * Raises or lowers the per-event listener ceiling before Node warns about a memory leak.
176
+ * Set this above the expected listener count when many listeners attach by design.
177
+ *
178
+ * @example
179
+ * ```ts
180
+ * emitter.setMaxListeners(40)
181
+ * ```
182
+ */
183
+ setMaxListeners(max) {
184
+ this.#emitter.setMaxListeners(max);
185
+ }
186
+ /**
187
+ * Returns the current per-event listener ceiling.
188
+ */
189
+ getMaxListeners() {
190
+ return this.#emitter.getMaxListeners();
191
+ }
192
+ /**
193
+ * Removes all listeners from every event channel.
194
+ *
195
+ * @example
196
+ * ```ts
197
+ * emitter.removeAll()
198
+ * ```
199
+ */
200
+ removeAll() {
201
+ this.#emitter.removeAllListeners();
202
+ }
203
+ };
204
+ //#endregion
205
+ //#region ../../internals/utils/src/casing.ts
206
+ /**
207
+ * Shared implementation for camelCase and PascalCase conversion.
208
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
209
+ * and capitalizes each word according to `pascal`.
210
+ *
211
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
212
+ */
213
+ function toCamelOrPascal(text, pascal) {
214
+ return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
215
+ if (word.length > 1 && word === word.toUpperCase()) return word;
216
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
217
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
218
+ }
219
+ /**
220
+ * Converts `text` to camelCase.
221
+ *
222
+ * @example Word boundaries
223
+ * `camelCase('hello-world') // 'helloWorld'`
224
+ *
225
+ * @example With a prefix
226
+ * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
227
+ */
228
+ function camelCase(text, { prefix = "", suffix = "" } = {}) {
229
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
230
+ }
231
+ /**
232
+ * Converts `text` to PascalCase.
233
+ *
234
+ * @example Word boundaries
235
+ * `pascalCase('hello-world') // 'HelloWorld'`
236
+ *
237
+ * @example With a suffix
238
+ * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
239
+ */
240
+ function pascalCase(text, { prefix = "", suffix = "" } = {}) {
241
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
242
+ }
243
+ //#endregion
244
+ //#region ../../internals/utils/src/runtime.ts
245
+ /**
246
+ * Detects the JavaScript runtime executing the current process and exposes its name and version.
247
+ *
248
+ * Prefer the shared {@link runtime} instance over constructing your own.
249
+ */
250
+ var Runtime = class {
251
+ /**
252
+ * `true` when the current process is running under Bun.
253
+ *
254
+ * Detection keys off the global `Bun` object rather than `process.versions`,
255
+ * because Bun polyfills `process.versions.node` for Node compatibility and would
256
+ * otherwise look like Node.
257
+ *
258
+ * @example
259
+ * ```ts
260
+ * if (runtime.isBun) {
261
+ * await Bun.write(path, data)
262
+ * }
263
+ * ```
264
+ */
265
+ get isBun() {
266
+ return typeof Bun !== "undefined";
267
+ }
268
+ /**
269
+ * `true` when the current process is running under Deno.
270
+ */
271
+ get isDeno() {
272
+ return typeof globalThis.Deno !== "undefined";
273
+ }
274
+ /**
275
+ * `true` when the current process is running under Node.
276
+ *
277
+ * Bun and Deno are excluded first so a polyfilled `process` does not register as Node.
278
+ */
279
+ get isNode() {
280
+ return !this.isBun && !this.isDeno && typeof process !== "undefined" && process.versions?.node != null;
281
+ }
282
+ /**
283
+ * Name of the runtime executing the current process.
284
+ *
285
+ * @example
286
+ * ```ts
287
+ * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise
288
+ * ```
289
+ */
290
+ get name() {
291
+ if (this.isBun) return "bun";
292
+ if (this.isDeno) return "deno";
293
+ return "node";
294
+ }
295
+ /**
296
+ * Version of the active runtime, or an empty string when it cannot be read.
297
+ *
298
+ * @example
299
+ * ```ts
300
+ * runtime.version // '1.3.11' under Bun, '22.22.2' under Node
301
+ * ```
302
+ */
303
+ get version() {
304
+ if (this.isBun) return process.versions.bun ?? "";
305
+ if (this.isDeno) return globalThis.Deno?.version?.deno ?? "";
306
+ return process.versions?.node ?? "";
307
+ }
308
+ };
309
+ /**
310
+ * Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.
311
+ */
312
+ const runtime = new Runtime();
313
+ //#endregion
314
+ //#region ../../internals/utils/src/fs.ts
315
+ /**
316
+ * Reads the file at `path` as a UTF-8 string.
317
+ * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.
318
+ *
319
+ * @example
320
+ * ```ts
321
+ * const source = await read('./src/Pet.ts')
322
+ * ```
323
+ */
324
+ async function read(path) {
325
+ if (runtime.isBun) return Bun.file(path).text();
326
+ return (0, node_fs_promises.readFile)(path, { encoding: "utf8" });
327
+ }
328
+ /**
329
+ * Writes `data` to `path`, trimming leading/trailing whitespace before saving.
330
+ * Skips the write when the trimmed content is empty or identical to what is already on disk.
331
+ * Creates any missing parent directories automatically.
332
+ * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.
333
+ *
334
+ * @example
335
+ * ```ts
336
+ * await write('./src/Pet.ts', source) // writes and returns trimmed content
337
+ * await write('./src/Pet.ts', source) // null — file unchanged
338
+ * await write('./src/Pet.ts', ' ') // null — empty content skipped
339
+ * ```
340
+ */
341
+ async function write(path, data, options = {}) {
342
+ const trimmed = data.trim();
343
+ if (trimmed === "") return null;
344
+ const resolved = (0, node_path.resolve)(path);
345
+ if (runtime.isBun) {
346
+ const file = Bun.file(resolved);
347
+ if ((await file.exists() ? await file.text() : null) === trimmed) return null;
348
+ await Bun.write(resolved, trimmed);
349
+ return trimmed;
350
+ }
351
+ try {
352
+ if (await (0, node_fs_promises.readFile)(resolved, { encoding: "utf-8" }) === trimmed) return null;
353
+ } catch {}
354
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(resolved), { recursive: true });
355
+ await (0, node_fs_promises.writeFile)(resolved, trimmed, { encoding: "utf-8" });
356
+ if (options.sanity) {
357
+ const savedData = await (0, node_fs_promises.readFile)(resolved, { encoding: "utf-8" });
358
+ if (savedData !== trimmed) throw new Error(`Sanity check failed for ${path}\n\nData[${data.length}]:\n${data}\n\nSaved[${savedData.length}]:\n${savedData}\n`);
359
+ return savedData;
360
+ }
361
+ return trimmed;
362
+ }
363
+ /**
364
+ * Recursively removes `path`. Silently succeeds when `path` does not exist.
365
+ *
366
+ * @example
367
+ * ```ts
368
+ * await clean('./dist')
369
+ * ```
370
+ */
371
+ async function clean(path) {
372
+ return (0, node_fs_promises.rm)(path, {
373
+ recursive: true,
374
+ force: true
375
+ });
376
+ }
377
+ /**
378
+ * Converts a filesystem path to use POSIX (`/`) separators.
379
+ *
380
+ * Most of the codebase compares and composes paths as strings (prefix matching, joining for
381
+ * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated
382
+ * paths, but on Windows it returns `\`-separated paths, which breaks every such comparison.
383
+ *
384
+ * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the
385
+ * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is
386
+ * exercisable from POSIX CI.
387
+ *
388
+ * @example
389
+ * toPosixPath('C:\\repo\\src\\pet.ts') // 'C:/repo/src/pet.ts'
390
+ */
391
+ function toPosixPath(filePath) {
392
+ return filePath.replaceAll("\\", "/");
393
+ }
394
+ /**
395
+ * Builds a nested file path from a dotted name. Splits on dots that precede a letter
396
+ * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
397
+ * every earlier segment, applies `caseLast` to the final segment, and joins with `/`.
398
+ *
399
+ * Empty segments are dropped before joining. They arise when the name starts with a dot
400
+ * followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to
401
+ * an empty string). Without this a leading `/` would form, which `path.resolve` reads as an
402
+ * absolute path, letting generated files escape the configured output directory.
403
+ *
404
+ * @example Nested path from a dotted name
405
+ * `toFilePath('pet.petId') // 'pet/petId'`
406
+ *
407
+ * @example PascalCase the final segment
408
+ * `toFilePath('pet.Pet', pascalCase) // 'pet/Pet'`
409
+ *
410
+ * @example Suffix applied to the final segment only
411
+ * `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`
412
+ */
413
+ function toFilePath(name, caseLast = camelCase) {
414
+ const parts = name.split(/\.(?=[a-zA-Z])/);
415
+ return parts.map((part, i) => i === parts.length - 1 ? caseLast(part) : camelCase(part)).filter(Boolean).join("/");
416
+ }
417
+ //#endregion
418
+ //#region src/constants.ts
419
+ /**
420
+ * Plugin `include` filter types that select operations directly. When one of these is set
421
+ * without a `schemaName` include, the generate phase pre-scans operations to compute the set
422
+ * of schemas they reach, so unreachable schemas can be pruned for that plugin.
423
+ */
424
+ const OPERATION_FILTER_TYPES = new Set([
425
+ "tag",
426
+ "operationId",
427
+ "path",
428
+ "method",
429
+ "contentType"
430
+ ]);
431
+ /**
432
+ * Stable codes Kubb attaches to a `Diagnostic`. Each maps to a known failure mode
433
+ * and stays stable so it can be referenced in tooling and (later) docs. Reference
434
+ * these instead of inlining the string at a throw site.
435
+ */
436
+ const diagnosticCode = {
437
+ /**
438
+ * Fallback for an unstructured error with no specific code.
439
+ */
440
+ unknown: "KUBB_UNKNOWN",
441
+ /**
442
+ * The `input.path` file or URL could not be read.
443
+ */
444
+ inputNotFound: "KUBB_INPUT_NOT_FOUND",
445
+ /**
446
+ * An adapter was configured without an `input`.
447
+ */
448
+ inputRequired: "KUBB_INPUT_REQUIRED",
449
+ /**
450
+ * A `$ref` (or equivalent reference) could not be resolved in the source document.
451
+ */
452
+ refNotFound: "KUBB_REF_NOT_FOUND",
453
+ /**
454
+ * A server variable value is not allowed by its `enum`.
455
+ */
456
+ invalidServerVariable: "KUBB_INVALID_SERVER_VARIABLE",
457
+ /**
458
+ * A required plugin is missing from the config.
459
+ */
460
+ pluginNotFound: "KUBB_PLUGIN_NOT_FOUND",
461
+ /**
462
+ * A plugin threw while generating.
463
+ */
464
+ pluginFailed: "KUBB_PLUGIN_FAILED",
465
+ /**
466
+ * A plugin reported a non-fatal warning through `ctx.warn`.
467
+ */
468
+ pluginWarning: "KUBB_PLUGIN_WARNING",
469
+ /**
470
+ * A plugin reported an informational message through `ctx.info`.
471
+ */
472
+ pluginInfo: "KUBB_PLUGIN_INFO",
473
+ /**
474
+ * A schema uses a `format` Kubb does not map to a specific type. Reserved for
475
+ * adapters to emit as a `warning`.
476
+ */
477
+ unsupportedFormat: "KUBB_UNSUPPORTED_FORMAT",
478
+ /**
479
+ * A referenced schema or operation is marked `deprecated`. Reserved for adapters
480
+ * to emit as an `info`.
481
+ */
482
+ deprecated: "KUBB_DEPRECATED",
483
+ /**
484
+ * An adapter is required but the config has none. The build cannot read the input
485
+ * without one.
486
+ */
487
+ adapterRequired: "KUBB_ADAPTER_REQUIRED",
488
+ /**
489
+ * A resolved output path escapes the output directory, which can stem from a path
490
+ * traversal in the spec or a misconfigured `group.name`.
491
+ */
492
+ pathTraversal: "KUBB_PATH_TRAVERSAL",
493
+ /**
494
+ * A plugin's options are invalid, for example `output.mode: 'file'` paired with a `group` option.
495
+ */
496
+ invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS",
497
+ /**
498
+ * A post-generate shell hook (`hooks.done`) exited with a failure.
499
+ */
500
+ hookFailed: "KUBB_HOOK_FAILED",
501
+ /**
502
+ * The formatter pass over the generated files failed.
503
+ */
504
+ formatFailed: "KUBB_FORMAT_FAILED",
505
+ /**
506
+ * The linter pass over the generated files failed.
507
+ */
508
+ lintFailed: "KUBB_LINT_FAILED",
509
+ /**
510
+ * Not a failure. Carries a plugin's elapsed time, summed into the run total.
511
+ */
512
+ performance: "KUBB_PERFORMANCE",
513
+ /**
514
+ * Not a failure. A newer Kubb version is available on npm.
515
+ */
516
+ updateAvailable: "KUBB_UPDATE_AVAILABLE"
517
+ };
518
+ //#endregion
519
+ //#region src/createStorage.ts
520
+ /**
521
+ * Defines a custom storage backend. The builder receives user options and
522
+ * returns a `Storage` implementation. Kubb ships with filesystem and in-memory
523
+ * storages. A custom backend writes generated files elsewhere, such as cloud
524
+ * storage or a database.
525
+ *
526
+ * @example In-memory storage (the built-in implementation)
527
+ * ```ts
528
+ * import { createStorage } from '@kubb/core'
529
+ *
530
+ * export const memoryStorage = createStorage(() => {
531
+ * const store = new Map<string, string>()
532
+ *
533
+ * return {
534
+ * name: 'memory',
535
+ * async hasItem(key) {
536
+ * return store.has(key)
537
+ * },
538
+ * async getItem(key) {
539
+ * return store.get(key) ?? null
540
+ * },
541
+ * async setItem(key, value) {
542
+ * store.set(key, value)
543
+ * },
544
+ * async removeItem(key) {
545
+ * store.delete(key)
546
+ * },
547
+ * async getKeys(base) {
548
+ * const keys = [...store.keys()]
549
+ * return base ? keys.filter((k) => k.startsWith(base)) : keys
550
+ * },
551
+ * async clear(base) {
552
+ * if (!base) store.clear()
553
+ * },
554
+ * }
555
+ * })
556
+ * ```
557
+ */
558
+ function createStorage(build) {
559
+ return (options) => build(options ?? {});
560
+ }
561
+ //#endregion
562
+ //#region src/FileManager.ts
563
+ function mergeFile(a, b) {
564
+ return {
565
+ ...a,
566
+ banner: b.banner,
567
+ footer: b.footer,
568
+ copy: b.copy ?? a.copy,
569
+ sources: a.sources.length ? b.sources.length ? [...a.sources, ...b.sources] : a.sources : b.sources,
570
+ imports: a.imports.length ? b.imports.length ? [...a.imports, ...b.imports] : a.imports : b.imports,
571
+ exports: a.exports.length ? b.exports.length ? [...a.exports, ...b.exports] : a.exports : b.exports
572
+ };
573
+ }
574
+ function isIndexPath(path) {
575
+ return path.endsWith("/index.ts") || path === "index.ts";
576
+ }
577
+ function compareFiles(a, b) {
578
+ const lenDiff = a.path.length - b.path.length;
579
+ if (lenDiff !== 0) return lenDiff;
580
+ const aIsIndex = isIndexPath(a.path);
581
+ const bIsIndex = isIndexPath(b.path);
582
+ if (aIsIndex && !bIsIndex) return 1;
583
+ if (!aIsIndex && bIsIndex) return -1;
584
+ return 0;
585
+ }
586
+ /**
587
+ * In-memory file store for generated files. Files sharing a `path` are merged
588
+ * (sources/imports/exports concatenated). The `files` getter is sorted by
589
+ * path length (barrel `index.ts` last within a bucket).
590
+ *
591
+ * @example
592
+ * ```ts
593
+ * const manager = new FileManager()
594
+ * manager.upsert(myFile)
595
+ * manager.files // sorted view
596
+ * ```
597
+ */
598
+ var FileManager = class {
599
+ /**
600
+ * Subscribe to file-store changes. Listeners on `upsert` see each resolved file as it lands
601
+ * through `add` or `upsert`.
602
+ */
603
+ hooks = new AsyncEventEmitter();
604
+ #cache = /* @__PURE__ */ new Map();
605
+ #sorted = null;
606
+ add(...files) {
607
+ return this.#store(files, false);
608
+ }
609
+ upsert(...files) {
610
+ return this.#store(files, true);
611
+ }
612
+ #store(files, mergeExisting) {
613
+ const batch = files.length > 1 ? this.#dedupe(files) : files;
614
+ const resolved = [];
615
+ for (const file of batch) {
616
+ const existing = this.#cache.get(file.path);
617
+ const merged = existing && mergeExisting ? _kubb_ast.ast.factory.createFile(mergeFile(existing, file)) : _kubb_ast.ast.factory.createFile(file);
618
+ this.#cache.set(merged.path, merged);
619
+ resolved.push(merged);
620
+ this.hooks.emit("upsert", merged);
621
+ }
622
+ if (resolved.length > 0) this.#sorted = null;
623
+ return resolved;
624
+ }
625
+ #dedupe(files) {
626
+ const seen = /* @__PURE__ */ new Map();
627
+ for (const file of files) {
628
+ const prev = seen.get(file.path);
629
+ seen.set(file.path, prev ? mergeFile(prev, file) : file);
630
+ }
631
+ return [...seen.values()];
632
+ }
633
+ getByPath(path) {
634
+ return this.#cache.get(path) ?? null;
635
+ }
636
+ deleteByPath(path) {
637
+ if (!this.#cache.delete(path)) return;
638
+ this.#sorted = null;
639
+ }
640
+ clear() {
641
+ this.#cache.clear();
642
+ this.#sorted = null;
643
+ }
644
+ /**
645
+ * Releases all stored files and clears every `hooks` listener. Called by the core after
646
+ * `kubb:build:end`.
647
+ */
648
+ dispose() {
649
+ this.clear();
650
+ this.hooks.removeAll();
651
+ }
652
+ [Symbol.dispose]() {
653
+ this.dispose();
654
+ }
655
+ /**
656
+ * All stored files in stable sort order (shortest path first, barrel files
657
+ * last within a length bucket). Returns a cached view, do not mutate.
658
+ */
659
+ get files() {
660
+ return this.#sorted ??= [...this.#cache.values()].sort(compareFiles);
661
+ }
662
+ };
663
+ //#endregion
664
+ //#region src/FileProcessor.ts
665
+ function joinSources(file) {
666
+ const sources = file.sources;
667
+ if (sources.length === 0) return "";
668
+ const parts = [];
669
+ for (const source of sources) {
670
+ const text = (0, _kubb_ast_utils.extractStringsFromNodes)(source.nodes);
671
+ if (text) parts.push(text);
672
+ }
673
+ return parts.join("\n\n");
674
+ }
675
+ async function parseCopy(file) {
676
+ let content;
677
+ try {
678
+ content = await read(file.copy);
679
+ } catch (err) {
680
+ throw new Error(`[kubb] Could not copy file into output: ${file.copy}`, { cause: err });
681
+ }
682
+ return [
683
+ file.banner,
684
+ content,
685
+ file.footer
686
+ ].filter((segment) => Boolean(segment)).map((segment) => segment.trimEnd()).join("\n");
687
+ }
688
+ /**
689
+ * Turns `FileNode`s into source strings and writes them to storage.
690
+ *
691
+ * Two modes share the same instance. Stateless mode (`parse`, `stream`, `run`) just runs the
692
+ * conversion. Queue mode (`enqueue`, `flush`, `drain`) buffers files deduped by path and
693
+ * writes each batch through storage with up to `STREAM_FLUSH_EVERY` requests in flight.
694
+ *
695
+ * `flush` does not wait for its batch to finish, so dispatch can overlap with IO. The next
696
+ * `flush` or `drain` picks the in-flight batch up. `drain` blocks until everything has been
697
+ * written and is meant for the end of a build.
698
+ *
699
+ * To surface build-level hook signals (`kubb:files:processing:*` and friends) subscribe to
700
+ * `hooks` and re-emit on the kubb bus.
701
+ */
702
+ var FileProcessor = class {
703
+ hooks = new AsyncEventEmitter();
704
+ #parsers;
705
+ #storage;
706
+ #extension;
707
+ #pending = /* @__PURE__ */ new Map();
708
+ #runningFlush = null;
709
+ constructor(options) {
710
+ this.#parsers = options.parsers ?? null;
711
+ this.#storage = options.storage;
712
+ this.#extension = options.extension ?? null;
713
+ }
714
+ /**
715
+ * Files waiting in the queue.
716
+ */
717
+ get size() {
718
+ return this.#pending.size;
719
+ }
720
+ async parse(file) {
721
+ if (file.copy) return parseCopy(file);
722
+ const parsers = this.#parsers;
723
+ const parseExtName = this.#extension?.[file.extname] || void 0;
724
+ if (!parsers || !file.extname) return joinSources(file);
725
+ const parser = parsers.get(file.extname);
726
+ if (!parser) return joinSources(file);
727
+ return parser.parse(file, { extname: parseExtName });
728
+ }
729
+ async *stream(files) {
730
+ const total = files.length;
731
+ if (total === 0) return;
732
+ let processed = 0;
733
+ for (const file of files) {
734
+ const source = await this.parse(file);
735
+ processed++;
736
+ yield {
737
+ file,
738
+ source,
739
+ processed,
740
+ total,
741
+ percentage: processed / total * 100
742
+ };
743
+ }
744
+ }
745
+ async run(files) {
746
+ await this.hooks.emit("start", files);
747
+ for await (const { file, source, processed, total, percentage } of this.stream(files)) await this.hooks.emit("update", {
748
+ file,
749
+ source,
750
+ processed,
751
+ percentage,
752
+ total
753
+ });
754
+ await this.hooks.emit("end", files);
755
+ return files;
756
+ }
757
+ /**
758
+ * Adds a file to the next flush. A later `enqueue` for the same path replaces the previous
759
+ * entry, matching `FileManager.upsert`. Fires the `enqueue` event.
760
+ */
761
+ enqueue(file) {
762
+ this.#pending.set(file.path, file);
763
+ this.hooks.emit("enqueue", file);
764
+ }
765
+ /**
766
+ * Starts processing the queued files. Waits for any previous flush to finish (so two
767
+ * batches never run together) and then returns without waiting for the new one. The next
768
+ * `flush` or `drain` picks up the in-flight task.
769
+ */
770
+ async flush() {
771
+ if (this.#runningFlush) await this.#runningFlush;
772
+ if (this.#pending.size === 0) return;
773
+ const batch = [...this.#pending.values()];
774
+ this.#pending.clear();
775
+ this.#runningFlush = this.#processAndWrite(batch).finally(() => {
776
+ this.#runningFlush = null;
777
+ });
778
+ }
779
+ /**
780
+ * Waits for the in-flight flush and writes any files still queued. Fires the `drain` event
781
+ * when both are done.
782
+ */
783
+ async drain() {
784
+ if (this.#runningFlush) await this.#runningFlush;
785
+ if (this.#pending.size > 0) {
786
+ const batch = [...this.#pending.values()];
787
+ this.#pending.clear();
788
+ await this.#processAndWrite(batch);
789
+ }
790
+ await this.hooks.emit("drain");
791
+ }
792
+ async #processAndWrite(files) {
793
+ const storage = this.#storage;
794
+ await this.hooks.emit("start", files);
795
+ const queue = [];
796
+ for await (const item of this.stream(files)) {
797
+ await this.hooks.emit("update", item);
798
+ if (item.source) {
799
+ queue.push(storage.setItem(item.file.path, item.source));
800
+ if (queue.length >= 50) await Promise.all(queue.splice(0));
801
+ }
802
+ }
803
+ await Promise.all(queue);
804
+ await this.hooks.emit("end", files);
805
+ }
806
+ /**
807
+ * Clears every listener and the pending queue.
808
+ */
809
+ dispose() {
810
+ this.hooks.removeAll();
811
+ this.#pending.clear();
812
+ }
813
+ [Symbol.dispose]() {
814
+ this.dispose();
815
+ }
816
+ };
817
+ //#endregion
818
+ //#region \0@oxc-project+runtime@0.135.0/helpers/esm/usingCtx.js
819
+ function _usingCtx() {
820
+ var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
821
+ var n = Error();
822
+ return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
823
+ };
824
+ var e = {};
825
+ var n = [];
826
+ function using(r, e) {
827
+ if (null != e) {
828
+ if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
829
+ if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
830
+ if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
831
+ if ("function" != typeof o) throw new TypeError("Object is not disposable.");
832
+ t && (o = function o() {
833
+ try {
834
+ t.call(e);
835
+ } catch (r) {
836
+ return Promise.reject(r);
837
+ }
838
+ }), n.push({
839
+ v: e,
840
+ d: o,
841
+ a: r
842
+ });
843
+ } else r && n.push({
844
+ d: e,
845
+ a: r
846
+ });
847
+ return e;
848
+ }
849
+ return {
850
+ e,
851
+ u: using.bind(null, !1),
852
+ a: using.bind(null, !0),
853
+ d: function d() {
854
+ var o;
855
+ var t = this.e;
856
+ var s = 0;
857
+ function next() {
858
+ for (; o = n.pop();) try {
859
+ if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
860
+ if (o.d) {
861
+ var r = o.d.call(o.v);
862
+ if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
863
+ } else s |= 1;
864
+ } catch (r) {
865
+ return err(r);
866
+ }
867
+ if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
868
+ if (t !== e) throw t;
869
+ }
870
+ function err(n) {
871
+ return t = t !== e ? new r(n, t) : n, next();
872
+ }
873
+ return next();
874
+ }
875
+ };
876
+ }
877
+ //#endregion
878
+ //#region src/storages/memoryStorage.ts
879
+ /**
880
+ * In-memory storage driver. Useful for testing and dry-run scenarios where
881
+ * generated output should be captured without touching the filesystem.
882
+ *
883
+ * All data lives in a `Map` scoped to the storage instance and is discarded
884
+ * when the instance is garbage-collected.
885
+ *
886
+ * @example
887
+ * ```ts
888
+ * import { memoryStorage } from '@kubb/core'
889
+ * import { defineConfig } from 'kubb'
890
+ *
891
+ * export default defineConfig({
892
+ * input: { path: './petStore.yaml' },
893
+ * output: { path: './src/gen' },
894
+ * storage: memoryStorage(),
895
+ * })
896
+ * ```
897
+ */
898
+ const memoryStorage = createStorage(() => {
899
+ const store = /* @__PURE__ */ new Map();
900
+ return {
901
+ name: "memory",
902
+ async hasItem(key) {
903
+ return store.has(key);
904
+ },
905
+ async getItem(key) {
906
+ return store.get(key) ?? null;
907
+ },
908
+ async setItem(key, value) {
909
+ store.set(key, value);
910
+ },
911
+ async removeItem(key) {
912
+ store.delete(key);
913
+ },
914
+ async getKeys(base) {
915
+ const keys = [...store.keys()];
916
+ return base ? keys.filter((k) => k.startsWith(base)) : keys;
917
+ },
918
+ async clear(base) {
919
+ if (!base) {
920
+ store.clear();
921
+ return;
922
+ }
923
+ for (const key of store.keys()) if (key.startsWith(base)) store.delete(key);
924
+ }
925
+ };
926
+ });
927
+ //#endregion
928
+ Object.defineProperty(exports, "AsyncEventEmitter", {
929
+ enumerable: true,
930
+ get: function() {
931
+ return AsyncEventEmitter;
932
+ }
933
+ });
934
+ Object.defineProperty(exports, "BuildError", {
935
+ enumerable: true,
936
+ get: function() {
937
+ return BuildError;
938
+ }
939
+ });
940
+ Object.defineProperty(exports, "FileManager", {
941
+ enumerable: true,
942
+ get: function() {
943
+ return FileManager;
944
+ }
945
+ });
946
+ Object.defineProperty(exports, "FileProcessor", {
947
+ enumerable: true,
948
+ get: function() {
949
+ return FileProcessor;
950
+ }
951
+ });
952
+ Object.defineProperty(exports, "OPERATION_FILTER_TYPES", {
953
+ enumerable: true,
954
+ get: function() {
955
+ return OPERATION_FILTER_TYPES;
956
+ }
957
+ });
958
+ Object.defineProperty(exports, "__name", {
959
+ enumerable: true,
960
+ get: function() {
961
+ return __name;
962
+ }
963
+ });
964
+ Object.defineProperty(exports, "__toESM", {
965
+ enumerable: true,
966
+ get: function() {
967
+ return __toESM;
968
+ }
969
+ });
970
+ Object.defineProperty(exports, "_usingCtx", {
971
+ enumerable: true,
972
+ get: function() {
973
+ return _usingCtx;
974
+ }
975
+ });
976
+ Object.defineProperty(exports, "camelCase", {
977
+ enumerable: true,
978
+ get: function() {
979
+ return camelCase;
980
+ }
981
+ });
982
+ Object.defineProperty(exports, "clean", {
983
+ enumerable: true,
984
+ get: function() {
985
+ return clean;
986
+ }
987
+ });
988
+ Object.defineProperty(exports, "createStorage", {
989
+ enumerable: true,
990
+ get: function() {
991
+ return createStorage;
992
+ }
993
+ });
994
+ Object.defineProperty(exports, "diagnosticCode", {
995
+ enumerable: true,
996
+ get: function() {
997
+ return diagnosticCode;
998
+ }
999
+ });
1000
+ Object.defineProperty(exports, "getErrorMessage", {
1001
+ enumerable: true,
1002
+ get: function() {
1003
+ return getErrorMessage;
1004
+ }
1005
+ });
1006
+ Object.defineProperty(exports, "memoryStorage", {
1007
+ enumerable: true,
1008
+ get: function() {
1009
+ return memoryStorage;
1010
+ }
1011
+ });
1012
+ Object.defineProperty(exports, "pascalCase", {
1013
+ enumerable: true,
1014
+ get: function() {
1015
+ return pascalCase;
1016
+ }
1017
+ });
1018
+ Object.defineProperty(exports, "runtime", {
1019
+ enumerable: true,
1020
+ get: function() {
1021
+ return runtime;
1022
+ }
1023
+ });
1024
+ Object.defineProperty(exports, "toFilePath", {
1025
+ enumerable: true,
1026
+ get: function() {
1027
+ return toFilePath;
1028
+ }
1029
+ });
1030
+ Object.defineProperty(exports, "toPosixPath", {
1031
+ enumerable: true,
1032
+ get: function() {
1033
+ return toPosixPath;
1034
+ }
1035
+ });
1036
+ Object.defineProperty(exports, "write", {
1037
+ enumerable: true,
1038
+ get: function() {
1039
+ return write;
1040
+ }
1041
+ });
1042
+
1043
+ //# sourceMappingURL=memoryStorage-CfycFGzX.cjs.map