@kubb/core 5.15.1 → 5.15.2

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.cjs CHANGED
@@ -2,6 +2,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  // \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
5
+ var __name = (target, value) => __defProp(target, "name", {
6
+ value,
7
+ configurable: true
8
+ });
5
9
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
10
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
11
  var __getProtoOf = Object.getPrototypeOf;
@@ -41,7 +45,7 @@ let node_readline = require("node:readline");
41
45
  let node_url = require("node:url");
42
46
  let node_module = require("node:module");
43
47
  // package.json
44
- var version = "5.15.1";
48
+ var version = "5.15.2";
45
49
  // ../../internals/utils/src/casing.ts
46
50
  /**
47
51
  * Shared implementation for camelCase and PascalCase conversion.
@@ -250,19 +254,8 @@ async function write(path, data, options = {}) {
250
254
  if (trimmed === "") return null;
251
255
  const content = `${trimmed}\n`;
252
256
  const resolved = (0, node_path.resolve)(path);
253
- let stored = options.stored;
254
- if (stored === void 0) {
255
- if (runtime.isBun) {
256
- const file = Bun.file(resolved);
257
- stored = await file.exists() ? await file.text() : null;
258
- } else try {
259
- stored = await (0, node_fs_promises.readFile)(resolved, { encoding: "utf-8" });
260
- } catch {
261
- stored = null;
262
- }
263
- }
264
257
  if (matchesStored({
265
- stored: stored ?? "",
258
+ stored: (options.stored === void 0 ? await read(resolved).catch(() => null) : options.stored) ?? "",
266
259
  source: trimmed
267
260
  })) return null;
268
261
  await writeRaw(resolved, content);
@@ -357,6 +350,21 @@ function isPathInside(path, parent) {
357
350
  }
358
351
  // ../../internals/utils/src/promise.ts
359
352
  /**
353
+ * Returns the value cached under `key` in `store`, computing and storing it on the first call.
354
+ * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive
355
+ * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.
356
+ *
357
+ * @example
358
+ * `const refs = memo(refCache, node, () => collectRefs(node))`
359
+ */
360
+ function memo$1(store, key, compute) {
361
+ if (store.has(key)) return store.get(key);
362
+ const value = compute();
363
+ store.set(key, value);
364
+ return value;
365
+ }
366
+ __name(memo$1, "memo");
367
+ /**
360
368
  * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each
361
369
  * takes the next item the moment it frees up instead of waiting for a batch to drain.
362
370
  *
@@ -1111,19 +1119,14 @@ var Diagnostics = class Diagnostics {
1111
1119
  */
1112
1120
  static dedupe(diagnostics) {
1113
1121
  const seen = /* @__PURE__ */ new Set();
1114
- const result = [];
1115
- for (const diagnostic of diagnostics) {
1116
- if (!isProblem(diagnostic)) {
1117
- result.push(diagnostic);
1118
- continue;
1119
- }
1122
+ return diagnostics.filter((diagnostic) => {
1123
+ if (!isProblem(diagnostic)) return true;
1120
1124
  const pointer = diagnostic.location && "pointer" in diagnostic.location ? diagnostic.location.pointer : "";
1121
1125
  const key = `${diagnostic.code} ${pointer} ${diagnostic.plugin ?? ""}`;
1122
- if (seen.has(key)) continue;
1126
+ if (seen.has(key)) return false;
1123
1127
  seen.add(key);
1124
- result.push(diagnostic);
1125
- }
1126
- return result;
1128
+ return true;
1129
+ });
1127
1130
  }
1128
1131
  /**
1129
1132
  * Builds the kubb.dev docs URL for a diagnostic code, e.g.
@@ -1446,13 +1449,6 @@ function definePlugin(definition) {
1446
1449
  ...definition
1447
1450
  });
1448
1451
  }
1449
- // src/memo.ts
1450
- function memoize(store, key, compute) {
1451
- if (store.has(key)) return store.get(key);
1452
- const value = compute();
1453
- store.set(key, value);
1454
- return value;
1455
- }
1456
1452
  // src/publicAddress.ts
1457
1453
  function createBlockList() {
1458
1454
  const list = new node_net.default.BlockList();
@@ -1739,15 +1735,10 @@ function inputToAdapterSource(config) {
1739
1735
  };
1740
1736
  }
1741
1737
  // src/resolveOptions.ts
1742
- const patternCache = /* @__PURE__ */ new Map();
1743
- const optionsCache = /* @__PURE__ */ new WeakMap();
1738
+ const patterns = /* @__PURE__ */ new Map();
1739
+ const nodeCaches = /* @__PURE__ */ new WeakMap();
1744
1740
  function testPattern(value, pattern) {
1745
- if (typeof pattern === "string") {
1746
- let regex = patternCache.get(pattern);
1747
- regex ??= new RegExp(pattern);
1748
- patternCache.set(pattern, regex);
1749
- return regex.test(value);
1750
- }
1741
+ if (typeof pattern === "string") return memo$1(patterns, pattern, () => new RegExp(pattern)).test(value);
1751
1742
  return value.match(pattern) !== null;
1752
1743
  }
1753
1744
  function matchesOperation(node, filter) {
@@ -1795,16 +1786,7 @@ function computeOptions(node, { options, exclude = [], include, override = [] })
1795
1786
  function resolveOptions(node, context) {
1796
1787
  const { options } = context;
1797
1788
  if (typeof options !== "object" || options === null) return computeOptions(node, context);
1798
- let byOptions = optionsCache.get(options);
1799
- if (!byOptions) {
1800
- byOptions = /* @__PURE__ */ new WeakMap();
1801
- optionsCache.set(options, byOptions);
1802
- }
1803
- const cached = byOptions.get(node);
1804
- if (cached) return cached.value;
1805
- const result = computeOptions(node, context);
1806
- byOptions.set(node, { value: result });
1807
- return result;
1789
+ return memo$1(memo$1(nodeCaches, options, () => /* @__PURE__ */ new WeakMap()), node, () => computeOptions(node, context));
1808
1790
  }
1809
1791
  // src/Resolver.ts
1810
1792
  function isNamespace(value) {
@@ -1910,7 +1892,7 @@ var Resolver = class Resolver {
1910
1892
  * Returns what `compute` produced the first time this build asked for `key`. A resolver lives for one build.
1911
1893
  */
1912
1894
  memo(key, compute) {
1913
- return memoize(this.#memo, key, compute);
1895
+ return memo$1(this.#memo, key, compute);
1914
1896
  }
1915
1897
  /**
1916
1898
  * Reserves emitted identifiers before allocating other declarations. The driver reserves component
@@ -2113,8 +2095,6 @@ var Resolver = class Resolver {
2113
2095
  description: meta?.description,
2114
2096
  version: meta?.version,
2115
2097
  baseURL: meta?.baseURL,
2116
- circularNames: meta?.circularNames ?? /* @__PURE__ */ new Set(),
2117
- enumNames: meta?.enumNames ?? /* @__PURE__ */ new Set(),
2118
2098
  filePath: file?.path ?? "",
2119
2099
  baseName: file?.baseName ?? "",
2120
2100
  isBarrel: file?.isBarrel ?? false,
@@ -2534,34 +2514,7 @@ var FileManager = class {
2534
2514
  });
2535
2515
  }
2536
2516
  };
2537
- // src/nodeCache.ts
2538
- /**
2539
- * Builds an empty {@link NodeCache} backed by a plain `Map`. Called once per node in the generate
2540
- * walk.
2541
- */
2542
- function createNodeCache() {
2543
- const store = /* @__PURE__ */ new Map();
2544
- return {
2545
- readItem(key) {
2546
- return store.get(key);
2547
- },
2548
- writeItem(key, value) {
2549
- store.set(key, value);
2550
- return value;
2551
- },
2552
- ensureItem(key, factory) {
2553
- if (store.has(key)) return store.get(key);
2554
- const value = factory();
2555
- store.set(key, value);
2556
- return value;
2557
- }
2558
- };
2559
- }
2560
2517
  // src/KubbDriver.ts
2561
- const ENFORCE_ORDER = {
2562
- pre: -1,
2563
- post: 1
2564
- };
2565
2518
  /** `include` filter types that select operations, and so prune the schemas they do not reach. */
2566
2519
  const OPERATION_FILTER_TYPES = /* @__PURE__ */ new Set([
2567
2520
  "tag",
@@ -2571,7 +2524,6 @@ const OPERATION_FILTER_TYPES = /* @__PURE__ */ new Set([
2571
2524
  "contentType",
2572
2525
  "extension"
2573
2526
  ]);
2574
- const enforceWeight = (plugin) => plugin.enforce ? ENFORCE_ORDER[plugin.enforce] : 0;
2575
2527
  /**
2576
2528
  * The options bag a `NormalizedPlugin` starts with before a plugin refines it: a directory output
2577
2529
  * at the plugin root and empty filter lists.
@@ -2607,21 +2559,13 @@ function normalizePluginOptions(rawOptions, pluginName) {
2607
2559
  * factory passed without calling it.
2608
2560
  */
2609
2561
  function assertPluginEntry(entry, index) {
2610
- if (typeof entry === "function") {
2611
- const name = entry.name || "pluginName";
2612
- throw new Diagnostics.Error({
2613
- code: Diagnostics.code.invalidPluginOptions,
2614
- severity: "error",
2615
- message: `plugins[${index}] is a function ("${name}"), not a plugin.`,
2616
- help: `Call it: ${name}()`,
2617
- location: { kind: "config" }
2618
- });
2619
- }
2620
- if (typeof entry !== "object" || entry === null) throw new Diagnostics.Error({
2562
+ if (typeof entry === "object" && entry !== null) return;
2563
+ const name = typeof entry === "function" ? entry.name || "pluginName" : void 0;
2564
+ throw new Diagnostics.Error({
2621
2565
  code: Diagnostics.code.invalidPluginOptions,
2622
2566
  severity: "error",
2623
- message: `plugins[${index}] is ${entry === null ? "null" : typeof entry}, not a plugin.`,
2624
- help: "Pass the result of a plugin factory, for example `pluginTs()`, or remove the entry.",
2567
+ message: name ? `plugins[${index}] is a function ("${name}"), not a plugin.` : `plugins[${index}] is ${entry === null ? "null" : typeof entry}, not a plugin.`,
2568
+ help: name ? `Call it: ${name}()` : "Pass the result of a plugin factory, for example `pluginTs()`, or remove the entry.",
2625
2569
  location: { kind: "config" }
2626
2570
  });
2627
2571
  }
@@ -2730,7 +2674,7 @@ var KubbDriver = class {
2730
2674
  * config are ignored here and surface later through `requirePlugin`.
2731
2675
  */
2732
2676
  #sortPlugins(plugins) {
2733
- const queue = [...plugins].sort((a, b) => enforceWeight(a) - enforceWeight(b));
2677
+ const queue = [...plugins].sort((a, b) => (0, _kubb_ast.compareEnforce)(a.enforce, b.enforce));
2734
2678
  const names = new Set(queue.map((plugin) => plugin.name));
2735
2679
  const blockedBy = new Map(queue.map((plugin) => {
2736
2680
  const dependencies = Array.isArray(plugin.dependencies) ? plugin.dependencies : Object.keys(plugin.dependencies ?? {});
@@ -2885,20 +2829,10 @@ var KubbDriver = class {
2885
2829
  try {
2886
2830
  await hooks.callHook("kubb:plugin:start", { plugin });
2887
2831
  } catch (caughtError) {
2888
- const error = toError(caughtError);
2889
- const duration = getElapsedMs(hrStart);
2890
- await this.#emitPluginEnd({
2832
+ diagnostics.push(...await this.#finishPlugin({
2891
2833
  plugin,
2892
- duration,
2893
- success: false,
2894
- error
2895
- });
2896
- diagnostics.push(Diagnostics.fromExtension(error, {
2897
- kind: "plugin",
2898
- extension: plugin
2899
- }), Diagnostics.performance({
2900
- plugin: plugin.name,
2901
- duration
2834
+ hrStart,
2835
+ error: toError(caughtError)
2902
2836
  }));
2903
2837
  continue;
2904
2838
  }
@@ -2910,16 +2844,10 @@ var KubbDriver = class {
2910
2844
  });
2911
2845
  continue;
2912
2846
  }
2913
- const duration = getElapsedMs(hrStart);
2914
- diagnostics.push(Diagnostics.performance({
2915
- plugin: plugin.name,
2916
- duration
2917
- }));
2918
- await this.#emitPluginEnd({
2847
+ diagnostics.push(...await this.#finishPlugin({
2919
2848
  plugin,
2920
- duration,
2921
- success: true
2922
- });
2849
+ hrStart
2850
+ }));
2923
2851
  }
2924
2852
  diagnostics.push(...await this.#runGenerators(generatorPlugins));
2925
2853
  this.#inlineFiles(parsersMap);
@@ -2976,21 +2904,35 @@ var KubbDriver = class {
2976
2904
  upsertFile: (...files) => this.fileManager.upsert(...files)
2977
2905
  };
2978
2906
  }
2979
- #emitPluginEnd({ plugin, duration, success, error }) {
2980
- return this.hooks.callHook("kubb:plugin:end", this.#withFiles({
2907
+ async #finishPlugin({ plugin, hrStart, error, crashSite }) {
2908
+ const duration = getElapsedMs(hrStart);
2909
+ await this.hooks.callHook("kubb:plugin:end", this.#withFiles({
2981
2910
  plugin,
2982
2911
  duration,
2983
- success,
2912
+ success: !error,
2984
2913
  ...error ? { error } : {},
2985
2914
  config: this.config
2986
2915
  }));
2916
+ const timing = Diagnostics.performance({
2917
+ plugin: plugin.name,
2918
+ duration
2919
+ });
2920
+ if (!error) return [timing];
2921
+ const diagnostic = Diagnostics.fromExtension(error, {
2922
+ kind: "plugin",
2923
+ extension: plugin
2924
+ });
2925
+ const site = diagnostic.code === Diagnostics.code.pluginFailed && !diagnostic.location ? crashSite : void 0;
2926
+ return [site ? {
2927
+ ...diagnostic,
2928
+ message: `While generating ${site.label}: ${diagnostic.message}`,
2929
+ ...site.location ? { location: site.location } : {}
2930
+ } : diagnostic, timing];
2987
2931
  }
2988
2932
  /**
2989
2933
  * Runs schemas and operations through every plugin's generators. The walk is node-outer: each
2990
2934
  * schema is visited once and each operation once, and the node fans out to the matching
2991
- * generators of every plugin in dependency order. A per-node cache (`createNodeCache`) is created
2992
- * once per node and shared by all of that node's plugins, so node-derived work is computed once
2993
- * and reused instead of recomputed per plugin. Each node still runs through the plugin's macros
2935
+ * generators of every plugin in dependency order. Each node still runs through the plugin's macros
2994
2936
  * and its exclude/include/override filters before that plugin's
2995
2937
  * generator sees it, so plugins stay isolated. Schemas run before operations so file output
2996
2938
  * stays deterministic across runs. A generator with a `match` predicate that resolves `false`
@@ -3008,18 +2950,10 @@ var KubbDriver = class {
3008
2950
  const diagnostics = [];
3009
2951
  if (entries.length === 0) return diagnostics;
3010
2952
  if (!this.inputNode) {
3011
- for (const { plugin, hrStart } of entries) {
3012
- const duration = getElapsedMs(hrStart);
3013
- diagnostics.push(Diagnostics.performance({
3014
- plugin: plugin.name,
3015
- duration
3016
- }));
3017
- await this.#emitPluginEnd({
3018
- plugin,
3019
- duration,
3020
- success: true
3021
- });
3022
- }
2953
+ for (const { plugin, hrStart } of entries) diagnostics.push(...await this.#finishPlugin({
2954
+ plugin,
2955
+ hrStart
2956
+ }));
3023
2957
  return diagnostics;
3024
2958
  }
3025
2959
  const { schemas, operations } = this.inputNode;
@@ -3093,60 +3027,52 @@ var KubbDriver = class {
3093
3027
  break;
3094
3028
  }
3095
3029
  }
3096
- for (const node of schemas) {
3097
- const cache = createNodeCache();
3098
- for (const state of states) {
3099
- if (state.error || !state.schemaGenerators.length) continue;
3100
- try {
3101
- const resolved = state.schemas.get(node);
3102
- if (resolved instanceof Error) throw resolved;
3103
- if (!resolved) continue;
3104
- const { transformedNode, options } = resolved;
3030
+ for (const node of schemas) for (const state of states) {
3031
+ if (state.error || !state.schemaGenerators.length) continue;
3032
+ try {
3033
+ const resolved = state.schemas.get(node);
3034
+ if (resolved instanceof Error) throw resolved;
3035
+ if (!resolved) continue;
3036
+ const { transformedNode, options } = resolved;
3037
+ const ctx = {
3038
+ ...state.generatorContext,
3039
+ options
3040
+ };
3041
+ await this.#dispatchNode({
3042
+ generators: state.schemaGenerators,
3043
+ node: transformedNode,
3044
+ ctx,
3045
+ generate: (generator) => generator.schema(transformedNode, ctx)
3046
+ });
3047
+ await this.hooks.callHook("kubb:generate:schema", transformedNode, ctx);
3048
+ } catch (caughtError) {
3049
+ state.error = toError(caughtError);
3050
+ state.crashSite = getCrashSite(node);
3051
+ }
3052
+ }
3053
+ for (const node of operations) for (const state of states) {
3054
+ if (state.error || !state.operationGenerators.length && !state.operationsGenerators.length) continue;
3055
+ try {
3056
+ const resolved = resolveForPlugin(state, node);
3057
+ if (!resolved) continue;
3058
+ state.pluginOperations.push(resolved.transformedNode);
3059
+ if (state.operationGenerators.length) {
3060
+ const { transformedNode } = resolved;
3105
3061
  const ctx = {
3106
3062
  ...state.generatorContext,
3107
- options,
3108
- cache
3063
+ options: resolved.options
3109
3064
  };
3110
3065
  await this.#dispatchNode({
3111
- generators: state.schemaGenerators,
3066
+ generators: state.operationGenerators,
3112
3067
  node: transformedNode,
3113
3068
  ctx,
3114
- generate: (generator) => generator.schema(transformedNode, ctx)
3069
+ generate: (generator) => generator.operation(transformedNode, ctx)
3115
3070
  });
3116
- await this.hooks.callHook("kubb:generate:schema", transformedNode, ctx);
3117
- } catch (caughtError) {
3118
- state.error = toError(caughtError);
3119
- state.crashSite = getCrashSite(node);
3120
- }
3121
- }
3122
- }
3123
- for (const node of operations) {
3124
- const cache = createNodeCache();
3125
- for (const state of states) {
3126
- if (state.error || !state.operationGenerators.length && !state.operationsGenerators.length) continue;
3127
- try {
3128
- const resolved = resolveForPlugin(state, node);
3129
- if (!resolved) continue;
3130
- state.pluginOperations.push(resolved.transformedNode);
3131
- if (state.operationGenerators.length) {
3132
- const { transformedNode } = resolved;
3133
- const ctx = {
3134
- ...state.generatorContext,
3135
- options: resolved.options,
3136
- cache
3137
- };
3138
- await this.#dispatchNode({
3139
- generators: state.operationGenerators,
3140
- node: transformedNode,
3141
- ctx,
3142
- generate: (generator) => generator.operation(transformedNode, ctx)
3143
- });
3144
- await this.hooks.callHook("kubb:generate:operation", transformedNode, ctx);
3145
- }
3146
- } catch (caughtError) {
3147
- state.error = toError(caughtError);
3148
- state.crashSite = getCrashSite(node);
3071
+ await this.hooks.callHook("kubb:generate:operation", transformedNode, ctx);
3149
3072
  }
3073
+ } catch (caughtError) {
3074
+ state.error = toError(caughtError);
3075
+ state.crashSite = getCrashSite(node);
3150
3076
  }
3151
3077
  }
3152
3078
  for (const state of states) {
@@ -3154,8 +3080,7 @@ var KubbDriver = class {
3154
3080
  try {
3155
3081
  const ctx = {
3156
3082
  ...state.generatorContext,
3157
- options: state.plugin.options,
3158
- cache: createNodeCache()
3083
+ options: state.plugin.options
3159
3084
  };
3160
3085
  for (const generator of state.operationsGenerators) await this.fileManager.dispatch({
3161
3086
  result: await generator.operations(state.pluginOperations, ctx),
@@ -3166,31 +3091,12 @@ var KubbDriver = class {
3166
3091
  state.error = toError(caughtError);
3167
3092
  }
3168
3093
  }
3169
- for (const state of states) {
3170
- const duration = getElapsedMs(state.hrStart);
3171
- await this.#emitPluginEnd({
3172
- plugin: state.plugin,
3173
- duration,
3174
- success: !state.error,
3175
- error: state.error ?? void 0
3176
- });
3177
- if (state.error) {
3178
- const diagnostic = Diagnostics.fromExtension(state.error, {
3179
- kind: "plugin",
3180
- extension: state.plugin
3181
- });
3182
- const site = diagnostic.code === Diagnostics.code.pluginFailed && !diagnostic.location ? state.crashSite : void 0;
3183
- diagnostics.push(site ? {
3184
- ...diagnostic,
3185
- message: `While generating ${site.label}: ${diagnostic.message}`,
3186
- ...site.location ? { location: site.location } : {}
3187
- } : diagnostic);
3188
- }
3189
- diagnostics.push(Diagnostics.performance({
3190
- plugin: state.plugin.name,
3191
- duration
3192
- }));
3193
- }
3094
+ for (const { plugin, hrStart, error, crashSite } of states) diagnostics.push(...await this.#finishPlugin({
3095
+ plugin,
3096
+ hrStart,
3097
+ error: error ?? void 0,
3098
+ crashSite
3099
+ }));
3194
3100
  return diagnostics;
3195
3101
  }
3196
3102
  /**
@@ -3228,7 +3134,7 @@ var KubbDriver = class {
3228
3134
  return this.plugins.get(pluginName)?.resolver ?? createResolver({ pluginName });
3229
3135
  }
3230
3136
  memo(key, compute) {
3231
- return memoize(this.#memo, key, compute);
3137
+ return memo$1(this.#memo, key, compute);
3232
3138
  }
3233
3139
  getContext(plugin) {
3234
3140
  const driver = this;
@@ -3258,10 +3164,7 @@ var KubbDriver = class {
3258
3164
  driver.fileManager.upsert(...files);
3259
3165
  },
3260
3166
  get meta() {
3261
- return driver.inputNode?.meta ?? {
3262
- circularNames: /* @__PURE__ */ new Set(),
3263
- enumNames: /* @__PURE__ */ new Set()
3264
- };
3167
+ return driver.inputNode?.meta ?? {};
3265
3168
  },
3266
3169
  get adapter() {
3267
3170
  return driver.adapter;
@@ -3475,12 +3378,7 @@ const fsStorage = createStorage(() => ({
3475
3378
  await (0, node_fs_promises.rm)((0, node_path.resolve)(key), { force: true });
3476
3379
  },
3477
3380
  async readKeys(base) {
3478
- const resolvedBase = (0, node_path.resolve)(base ?? process.cwd());
3479
- const keys = [];
3480
- try {
3481
- for await (const path of listFiles(resolvedBase)) keys.push(path);
3482
- } catch (_error) {}
3483
- return keys;
3381
+ return Array.fromAsync(listFiles((0, node_path.resolve)(base ?? process.cwd()))).catch(() => []);
3484
3382
  },
3485
3383
  async empty(base) {
3486
3384
  if (!base) return;
@@ -3633,12 +3531,6 @@ var Hookable = class {
3633
3531
  return this.#listeners.get(hookName)?.size ?? 0;
3634
3532
  }
3635
3533
  /**
3636
- * No-op kept for callers written against the `EventEmitter`-backed version. Listeners are unbounded.
3637
- *
3638
- * @deprecated There is no listener ceiling anymore.
3639
- */
3640
- setMaxListeners(_max) {}
3641
- /**
3642
3534
  * Removes all listeners from every hook channel.
3643
3535
  *
3644
3536
  * @example
@@ -4118,27 +4010,96 @@ const logLevel = {
4118
4010
  */
4119
4011
  function createReporter(reporter) {
4120
4012
  const { name, needsPluginFiles, drain } = reporter;
4121
- if (!drain) return {
4122
- name,
4123
- needsPluginFiles,
4124
- async report(result, context) {
4125
- await reporter.report(result, context);
4126
- }
4127
- };
4128
4013
  const reports = [];
4129
4014
  return {
4130
4015
  name,
4131
4016
  needsPluginFiles,
4132
4017
  async report(result, context) {
4133
- reports.push(await reporter.report(result, context));
4018
+ const report = await reporter.report(result, context);
4019
+ if (drain) reports.push(report);
4134
4020
  },
4135
- async drain(context) {
4021
+ ...drain && { async drain(context) {
4136
4022
  await drain(context, reports.splice(0));
4023
+ } }
4024
+ };
4025
+ }
4026
+ // src/storages/kubbStorage.ts
4027
+ function ensurePrivateDir(dir) {
4028
+ (0, node_fs.mkdirSync)(dir, {
4029
+ recursive: true,
4030
+ mode: 448
4031
+ });
4032
+ (0, node_fs.chmodSync)(dir, 448);
4033
+ return dir;
4034
+ }
4035
+ /**
4036
+ * Folder Kubb keeps its own files in, created with mode 0700. `base` resolves inside `KUBB_HOME`
4037
+ * (default `~/.kubb`). When that folder is not writable, it falls back to a folder in the OS temp directory.
4038
+ *
4039
+ * @example
4040
+ * `resolveKubbDir('cache') // '/home/me/.kubb/cache'`
4041
+ */
4042
+ function resolveKubbDir(base = "") {
4043
+ const dir = (0, node_path.resolve)(node_process.default.env.KUBB_HOME ?? (0, node_path.join)((0, node_os.homedir)(), ".kubb"), base);
4044
+ try {
4045
+ return ensurePrivateDir(dir);
4046
+ } catch {
4047
+ return ensurePrivateDir((0, node_path.join)((0, node_os.tmpdir)(), "kubb", (0, node_crypto.hash)("sha256", dir).slice(0, 16)));
4048
+ }
4049
+ }
4050
+ /**
4051
+ * Key-value files rooted at {@link resolveKubbDir}. Each key is a file path inside that folder.
4052
+ * Strings are stored as is and other values as JSON. `getItem` parses JSON and falls back to the
4053
+ * raw string. The 0700 folder keeps files such as a stored token private.
4054
+ *
4055
+ * @example
4056
+ * ```ts
4057
+ * const storage = kubbStorage({ base: 'cache' })
4058
+ * await storage.setItem('machine-secret', secret)
4059
+ * ```
4060
+ */
4061
+ function kubbStorage({ base } = {}) {
4062
+ const dir = resolveKubbDir(base);
4063
+ const pathOf = (key) => {
4064
+ const path = (0, node_path.resolve)(dir, key.replaceAll(":", "/"));
4065
+ if (path === dir || !isPathInside(path, dir)) throw new Error(`Invalid key: ${JSON.stringify(key)}. It should not leave the storage folder`);
4066
+ return path;
4067
+ };
4068
+ return {
4069
+ async getItem(key) {
4070
+ const path = pathOf(key);
4071
+ if (!await exists(path)) return null;
4072
+ const raw = await read(path);
4073
+ try {
4074
+ return JSON.parse(raw);
4075
+ } catch {
4076
+ return raw;
4077
+ }
4078
+ },
4079
+ async setItem(key, value) {
4080
+ await writeRaw(pathOf(key), typeof value === "string" ? value : JSON.stringify(value));
4081
+ },
4082
+ async removeItem(key) {
4083
+ await (0, node_fs_promises.rm)(pathOf(key), { force: true });
4137
4084
  }
4138
4085
  };
4139
4086
  }
4140
4087
  // src/reporters/report.ts
4141
4088
  /**
4089
+ * The `.kubb` folder and file name a reporter writes to; the sanitized name keeps the file inside the folder.
4090
+ */
4091
+ function reportTarget(config) {
4092
+ const name = config.name?.replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
4093
+ return {
4094
+ dir: resolveKubbDir((0, node_path.resolve)(node_process.default.cwd(), ".kubb")),
4095
+ name: [
4096
+ "kubb",
4097
+ name,
4098
+ Date.now()
4099
+ ].filter(Boolean).join("-")
4100
+ };
4101
+ }
4102
+ /**
4142
4103
  * Builds the normalized {@link Report} for one config from its {@link GenerationResult}. Splits the
4143
4104
  * diagnostics into problems and per-plugin timings (slowest first) and derives the plugin and issue
4144
4105
  * counts, so every reporter renders the same data.
@@ -4259,67 +4220,6 @@ function createCliReporter({ render = consoleRenderer } = {}) {
4259
4220
  * logger view.
4260
4221
  */
4261
4222
  const cliReporter = createCliReporter();
4262
- // src/storages/kubbStorage.ts
4263
- function ensurePrivateDir(dir) {
4264
- (0, node_fs.mkdirSync)(dir, {
4265
- recursive: true,
4266
- mode: 448
4267
- });
4268
- (0, node_fs.chmodSync)(dir, 448);
4269
- return dir;
4270
- }
4271
- /**
4272
- * Folder Kubb keeps its own files in, created with mode 0700. `base` resolves inside `KUBB_HOME`
4273
- * (default `~/.kubb`). When that folder is not writable, it falls back to a folder in the OS temp directory.
4274
- *
4275
- * @example
4276
- * `resolveKubbDir('cache') // '/home/me/.kubb/cache'`
4277
- */
4278
- function resolveKubbDir(base = "") {
4279
- const dir = (0, node_path.resolve)(node_process.default.env.KUBB_HOME ?? (0, node_path.join)((0, node_os.homedir)(), ".kubb"), base);
4280
- try {
4281
- return ensurePrivateDir(dir);
4282
- } catch {
4283
- return ensurePrivateDir((0, node_path.join)((0, node_os.tmpdir)(), "kubb", (0, node_crypto.hash)("sha256", dir).slice(0, 16)));
4284
- }
4285
- }
4286
- /**
4287
- * Key-value files rooted at {@link resolveKubbDir}. Each key is a file path inside that folder.
4288
- * Strings are stored as is and other values as JSON. `getItem` parses JSON and falls back to the
4289
- * raw string. The 0700 folder keeps files such as a stored token private.
4290
- *
4291
- * @example
4292
- * ```ts
4293
- * const storage = kubbStorage({ base: 'cache' })
4294
- * await storage.setItem('machine-secret', secret)
4295
- * ```
4296
- */
4297
- function kubbStorage({ base } = {}) {
4298
- const dir = resolveKubbDir(base);
4299
- const pathOf = (key) => {
4300
- const path = (0, node_path.resolve)(dir, key.replaceAll(":", "/"));
4301
- if (path === dir || !isPathInside(path, dir)) throw new Error(`Invalid key: ${JSON.stringify(key)}. It should not leave the storage folder`);
4302
- return path;
4303
- };
4304
- return {
4305
- async getItem(key) {
4306
- const path = pathOf(key);
4307
- if (!await exists(path)) return null;
4308
- const raw = await read(path);
4309
- try {
4310
- return JSON.parse(raw);
4311
- } catch {
4312
- return raw;
4313
- }
4314
- },
4315
- async setItem(key, value) {
4316
- await writeRaw(pathOf(key), typeof value === "string" ? value : JSON.stringify(value));
4317
- },
4318
- async removeItem(key) {
4319
- await (0, node_fs_promises.rm)(pathOf(key), { force: true });
4320
- }
4321
- };
4322
- }
4323
4223
  // src/reporters/fileReporter.ts
4324
4224
  /**
4325
4225
  * Builds the `## Problems` section: each problem rendered in the miette block format, blocks
@@ -4358,14 +4258,10 @@ const fileReporter = createReporter({
4358
4258
  ...formatSummary(report, { showTimings: true })
4359
4259
  ], buildProblemSection(diagnostics)].filter((section) => section.length > 0);
4360
4260
  const content = (0, node_util.stripVTControlCharacters)([header, ...sections.map((section) => section.join("\n"))].join("\n\n"));
4361
- const baseName = `${[
4362
- "kubb",
4363
- config.name?.replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, ""),
4364
- Date.now()
4365
- ].filter(Boolean).join("-")}.log`;
4366
- const dir = resolveKubbDir((0, node_path.resolve)(node_process.default.cwd(), ".kubb"));
4367
- await kubbStorage({ base: dir }).setItem(baseName, `${content}\n`);
4368
- console.error(`Debug log written to ${(0, node_path.relative)(node_process.default.cwd(), (0, node_path.join)(dir, baseName))}`);
4261
+ const { dir, name } = reportTarget(config);
4262
+ const path = (0, node_path.join)(dir, `${name}.log`);
4263
+ await writeRaw(path, `${content}\n`);
4264
+ console.error(`Debug log written to ${(0, node_path.relative)(node_process.default.cwd(), path)}`);
4369
4265
  }
4370
4266
  });
4371
4267
  // src/reporters/jsonReporter.ts
@@ -4400,21 +4296,15 @@ const htmlReporter = createReporter({
4400
4296
  name: "html",
4401
4297
  needsPluginFiles: true,
4402
4298
  async report(result) {
4403
- const baseName = [
4404
- "kubb",
4405
- result.config.name?.replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, ""),
4406
- Date.now()
4407
- ].filter(Boolean).join("-");
4408
- const dir = resolveKubbDir((0, node_path.resolve)(process.cwd(), ".kubb"));
4409
- const storage = kubbStorage({ base: dir });
4299
+ const { dir, name } = reportTarget(result.config);
4410
4300
  const assets = new URL("./html/", require("url").pathToFileURL(__filename).href);
4411
4301
  const [html, ui] = await Promise.all([read((0, node_url.fileURLToPath)(new URL("index.html", assets))), read((0, node_url.fileURLToPath)(new URL("ui.iife.js", assets)))]);
4412
4302
  await Promise.all([
4413
- storage.setItem(`${baseName}/index.html`, html),
4414
- storage.setItem(`${baseName}/ui.iife.js`, ui),
4415
- storage.setItem(`${baseName}/data.js`, serializeReport(result))
4303
+ writeRaw((0, node_path.join)(dir, name, "index.html"), html),
4304
+ writeRaw((0, node_path.join)(dir, name, "ui.iife.js"), ui),
4305
+ writeRaw((0, node_path.join)(dir, name, "data.js"), serializeReport(result))
4416
4306
  ]);
4417
- const reportPath = (0, node_path.join)(dir, baseName, "index.html");
4307
+ const reportPath = (0, node_path.join)(dir, name, "index.html");
4418
4308
  console.error(`HTML report written to ${(0, node_path.relative)(process.cwd(), reportPath)}`);
4419
4309
  openInBrowser(reportPath);
4420
4310
  }
@@ -4535,11 +4425,7 @@ const memoryStorage = createStorage(() => {
4535
4425
  return base ? keys.filter((k) => k.startsWith(base)) : keys;
4536
4426
  },
4537
4427
  async empty(base) {
4538
- if (!base) {
4539
- store.clear();
4540
- return;
4541
- }
4542
- for (const key of store.keys()) if (key.startsWith(base)) store.delete(key);
4428
+ for (const key of store.keys()) if (!base || key.startsWith(base)) store.delete(key);
4543
4429
  }
4544
4430
  };
4545
4431
  });