@kubb/core 5.0.0-beta.36 → 5.0.0-beta.38

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.
package/dist/index.js CHANGED
@@ -1,26 +1,10 @@
1
1
  import "./chunk-C0LytTxp.js";
2
- import { a as FileManager, c as DEFAULT_BANNER, d as logLevel, f as URLPath, i as FileProcessor, l as DEFAULT_EXTENSION, m as BuildError, o as defineResolver, p as AsyncEventEmitter, r as _usingCtx, s as definePlugin, t as KubbDriver, u as DEFAULT_STUDIO_URL } from "./KubbDriver-DrG5-FFe.js";
2
+ import { _ as URLPath, a as defineResolver, c as Diagnostics, d as isProblemDiagnostic, f as isUpdateDiagnostic, g as logLevel, h as diagnosticCode, i as FileManager, l as diagnosticCatalog, m as DEFAULT_STUDIO_URL, n as _usingCtx, o as definePlugin, p as narrowDiagnostic, r as FileProcessor, s as DiagnosticError, t as KubbDriver, u as isPerformanceDiagnostic, v as AsyncEventEmitter, y as BuildError } from "./KubbDriver-CyNF-NIb.js";
3
3
  import { access, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import * as ast from "@kubb/ast";
6
- import { version } from "node:process";
7
6
  //#region ../../internals/utils/src/fs.ts
8
7
  /**
9
- * Resolves to `true` when the file or directory at `path` exists.
10
- * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.
11
- *
12
- * @example
13
- * ```ts
14
- * if (await exists('./kubb.config.ts')) {
15
- * const content = await read('./kubb.config.ts')
16
- * }
17
- * ```
18
- */
19
- async function exists(path) {
20
- if (typeof Bun !== "undefined") return Bun.file(path).exists();
21
- return access(path).then(() => true, () => false);
22
- }
23
- /**
24
8
  * Writes `data` to `path`, trimming leading/trailing whitespace before saving.
25
9
  * Skips the write when the trimmed content is empty or identical to what is already on disk.
26
10
  * Creates any missing parent directories automatically.
@@ -105,14 +89,11 @@ function createAdapter(build) {
105
89
  return (options) => build(options ?? {});
106
90
  }
107
91
  //#endregion
108
- //#region package.json
109
- var version$1 = "5.0.0-beta.36";
110
- //#endregion
111
92
  //#region src/createStorage.ts
112
93
  /**
113
94
  * Defines a custom storage backend. The builder receives user options and
114
95
  * returns a `Storage` implementation. Kubb ships with filesystem and
115
- * in-memory storages reach for this when you need to write generated files
96
+ * in-memory storages, reach for this when you need to write generated files
116
97
  * elsewhere (cloud storage, a database, a remote API).
117
98
  *
118
99
  * @example In-memory storage (the built-in implementation)
@@ -229,7 +210,7 @@ const fsStorage = createStorage(() => ({
229
210
  /**
230
211
  * Builds a `Storage` view scoped to the file paths produced by the current build.
231
212
  * Reads delegate to the underlying `storage` so source bytes stay where they were
232
- * written; writes register the key so subsequent reads and `getKeys` are scoped
213
+ * written. Writes register the key so subsequent reads and `getKeys` are scoped
233
214
  * to this build's output.
234
215
  */
235
216
  function createSourcesView(storage) {
@@ -270,8 +251,8 @@ function resolveConfig(userConfig) {
270
251
  output: {
271
252
  format: false,
272
253
  lint: false,
273
- extension: DEFAULT_EXTENSION,
274
- defaultBanner: DEFAULT_BANNER,
254
+ extension: { ".ts": ".ts" },
255
+ defaultBanner: "simple",
275
256
  ...userConfig.output
276
257
  },
277
258
  storage: userConfig.storage ?? fsStorage(),
@@ -282,21 +263,6 @@ function resolveConfig(userConfig) {
282
263
  plugins: userConfig.plugins ?? []
283
264
  };
284
265
  }
285
- /**
286
- * Returns a snapshot of the current runtime environment.
287
- *
288
- * Useful for attaching context to debug logs and error reports so that
289
- * issues can be reproduced without manual information gathering.
290
- */
291
- function getDiagnosticInfo() {
292
- return {
293
- nodeVersion: version,
294
- KubbVersion: version$1,
295
- platform: process.platform,
296
- arch: process.arch,
297
- cwd: process.cwd()
298
- };
299
- }
300
266
  function isInputPath(config) {
301
267
  return typeof config?.input === "object" && config.input !== null && "path" in config.input;
302
268
  }
@@ -311,7 +277,7 @@ function isInputPath(config) {
311
277
  * ```ts
312
278
  * const kubb = createKubb(userConfig)
313
279
  * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => console.log(plugin.name, duration))
314
- * const { files, failedPlugins } = await kubb.safeBuild()
280
+ * const { files, diagnostics } = await kubb.safeBuild()
315
281
  * ```
316
282
  */
317
283
  var Kubb = class {
@@ -343,26 +309,8 @@ var Kubb = class {
343
309
  const config = resolveConfig(this.#userConfig);
344
310
  const driver = new KubbDriver(config, { hooks: this.hooks });
345
311
  const storage = createSourcesView(config.storage);
346
- await this.hooks.emit("kubb:debug", {
347
- date: /* @__PURE__ */ new Date(),
348
- logs: this.#configLogs(config)
349
- });
350
- if (isInputPath(this.#userConfig) && !new URLPath(this.#userConfig.input.path).isURL) try {
351
- await exists(this.#userConfig.input.path);
352
- await this.hooks.emit("kubb:debug", {
353
- date: /* @__PURE__ */ new Date(),
354
- logs: [`✓ Input file validated: ${this.#userConfig.input.path}`]
355
- });
356
- } catch (caughtError) {
357
- throw new Error(`Cannot read file/URL defined in \`input.path\` or set with \`kubb generate PATH\` in the CLI of your Kubb config ${this.#userConfig.input.path}`, { cause: caughtError });
358
- }
359
- if (config.output.clean) {
360
- await this.hooks.emit("kubb:debug", {
361
- date: /* @__PURE__ */ new Date(),
362
- logs: ["Cleaning output directories", ` • Output: ${config.output.path}`]
363
- });
364
- await config.storage.clear(resolve(config.root, config.output.path));
365
- }
312
+ this.hooks.setMaxListeners(Math.max(10, config.plugins.length * 4));
313
+ if (config.output.clean) await config.storage.clear(resolve(config.root, config.output.path));
366
314
  await driver.setup();
367
315
  this.#config = config;
368
316
  this.#driver = driver;
@@ -374,10 +322,9 @@ var Kubb = class {
374
322
  */
375
323
  async build() {
376
324
  const out = await this.safeBuild();
377
- if (out.error) throw out.error;
378
- if (out.failedPlugins.size > 0) {
379
- const errors = [...out.failedPlugins].map(({ error }) => error);
380
- throw new BuildError(`Build Error with ${out.failedPlugins.size} failed plugins`, { errors });
325
+ if (Diagnostics.hasError(out.diagnostics)) {
326
+ const errors = out.diagnostics.filter(isProblemDiagnostic).filter((diagnostic) => diagnostic.severity === "error").map((diagnostic) => diagnostic.cause ?? new DiagnosticError(diagnostic));
327
+ throw new BuildError(`Build failed with ${errors.length} ${errors.length === 1 ? "error" : "errors"}`, { errors });
381
328
  }
382
329
  return out;
383
330
  }
@@ -392,14 +339,12 @@ var Kubb = class {
392
339
  const cleanup = _usingCtx$1.u(this);
393
340
  const driver = cleanup.driver;
394
341
  const storage = cleanup.storage;
395
- const { failedPlugins, pluginTimings, error } = await driver.run({ storage });
342
+ const { diagnostics } = await driver.run({ storage });
396
343
  return {
397
- failedPlugins,
344
+ diagnostics,
398
345
  files: driver.fileManager.files,
399
346
  driver,
400
- pluginTimings,
401
- storage,
402
- ...error ? { error } : {}
347
+ storage
403
348
  };
404
349
  } catch (_) {
405
350
  _usingCtx$1.e = _;
@@ -413,24 +358,6 @@ var Kubb = class {
413
358
  [Symbol.dispose]() {
414
359
  this.dispose();
415
360
  }
416
- #configLogs(config) {
417
- const u = this.#userConfig;
418
- const diag = getDiagnosticInfo();
419
- return [
420
- "Configuration:",
421
- ` • Name: ${u.name || "unnamed"}`,
422
- ` • Root: ${u.root || process.cwd()}`,
423
- ` • Output: ${u.output?.path || "not specified"}`,
424
- ` • Plugins: ${u.plugins?.length || 0}`,
425
- "Output Settings:",
426
- ` • Storage: ${config.storage.name}`,
427
- ` • Formatter: ${u.output?.format || "none"}`,
428
- ` • Linter: ${u.output?.lint || "none"}`,
429
- `Running adapter: ${config.adapter?.name || "none"}`,
430
- "Environment:",
431
- Object.entries(diag).map(([key, value]) => ` • ${key}: ${value}`).join("\n")
432
- ];
433
- }
434
361
  };
435
362
  /**
436
363
  * Constructs a {@link Kubb} build orchestrator from a user config. Equivalent
@@ -456,13 +383,54 @@ function createKubb(userConfig, options = {}) {
456
383
  return new Kubb(userConfig, options);
457
384
  }
458
385
  //#endregion
386
+ //#region src/createReporter.ts
387
+ /**
388
+ * Defines a reporter. When the definition has a `flush`, the returned reporter buffers each value
389
+ * `report` returns and hands the array to `flush` once, then clears it. Without a `flush`, nothing
390
+ * is buffered. Wiring the reporter onto the run's events is the host's job, so the reporter only
391
+ * ever deals with a {@link GenerationResult}.
392
+ *
393
+ * @example
394
+ * ```ts
395
+ * import { createReporter, Diagnostics } from '@kubb/core'
396
+ *
397
+ * export const jsonReporter = createReporter({
398
+ * name: 'json',
399
+ * report(result) {
400
+ * return { status: Diagnostics.hasError(result.diagnostics) ? 'failed' : 'success', diagnostics: result.diagnostics }
401
+ * },
402
+ * flush(context, reports) {
403
+ * process.stdout.write(`${JSON.stringify(reports, null, 2)}\n`)
404
+ * },
405
+ * })
406
+ * ```
407
+ */
408
+ function createReporter(reporter) {
409
+ const flush = reporter.flush;
410
+ if (!flush) return {
411
+ name: reporter.name,
412
+ report: reporter.report
413
+ };
414
+ const reports = [];
415
+ return {
416
+ name: reporter.name,
417
+ async report(result, context) {
418
+ reports.push(await reporter.report(result, context));
419
+ },
420
+ async flush(context) {
421
+ await flush(context, reports);
422
+ reports.length = 0;
423
+ }
424
+ };
425
+ }
426
+ //#endregion
459
427
  //#region src/createRenderer.ts
460
428
  /**
461
429
  * Defines a renderer factory. Renderers turn the generator's return value
462
430
  * (JSX, a template string, a tree of any shape) into `FileNode`s that get
463
431
  * written to disk.
464
432
  *
465
- * Use this to support output formats beyond JSX for instance, a Handlebars
433
+ * Use this to support output formats beyond JSX, for instance, a Handlebars
466
434
  * renderer, a string-template renderer, or a renderer that writes binary
467
435
  * files. Plugins and generators pick the renderer to use via the `renderer`
468
436
  * field on `defineGenerator`.
@@ -506,7 +474,7 @@ function createRenderer(factory) {
506
474
  * The returned object is the input as-is, but with `this` types preserved so
507
475
  * `schema`/`operation`/`operations` methods are correctly typed against the
508
476
  * plugin's `PluginFactoryOptions`. Renderer elements and `FileNode[]` returns
509
- * are both handled by the runtime pick whichever style fits.
477
+ * are both handled by the runtime, so pick whichever style fits.
510
478
  *
511
479
  * @example JSX-based schema generator
512
480
  * ```tsx
@@ -688,6 +656,6 @@ const memoryStorage = createStorage(() => {
688
656
  };
689
657
  });
690
658
  //#endregion
691
- export { AsyncEventEmitter, FileManager, FileProcessor, KubbDriver, URLPath, ast, createAdapter, createKubb, createRenderer, createStorage, defineGenerator, defineLogger, defineMiddleware, defineParser, definePlugin, defineResolver, fsStorage, isInputPath, logLevel, memoryStorage };
659
+ export { AsyncEventEmitter, DiagnosticError, Diagnostics, FileManager, FileProcessor, KubbDriver, URLPath, ast, createAdapter, createKubb, createRenderer, createReporter, createStorage, defineGenerator, defineLogger, defineMiddleware, defineParser, definePlugin, defineResolver, diagnosticCatalog, diagnosticCode, fsStorage, isInputPath, isPerformanceDiagnostic, isProblemDiagnostic, isUpdateDiagnostic, logLevel, memoryStorage, narrowDiagnostic };
692
660
 
693
661
  //# sourceMappingURL=index.js.map