@kubb/core 5.0.0-beta.75 → 5.0.0-beta.76

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