@kubb/core 5.18.7 → 5.18.8

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.d.cts CHANGED
@@ -909,7 +909,7 @@ declare class FileManager {
909
909
  * memory rather than holding every source, while still overlapping each file's write with the
910
910
  * next file's parse. Files finish in whatever order they parse, so each finished file flushes the
911
911
  * run of finished files ahead of it as one `kubb:files:processing:update`, keeping rows in input order.
912
- * Each parsed source goes out once on `kubb:file:processed`, so listeners read it without the pool holding it.
912
+ * Each parsed source goes out once on `kubb:file:processed`, next to what the storage held before the write.
913
913
  *
914
914
  * A file the storage already holds is skipped, so a rebuild that generates identical output
915
915
  * writes nothing and leaves every mtime where it was. `kubb:files:processing:end` lists the
@@ -1620,6 +1620,8 @@ export type KubbFileProcessedContext = {
1620
1620
  file: FileNode;
1621
1621
  /** The parsed content handed to the storage, before it trims the content or an output pass such as a formatter rewrites it. */
1622
1622
  source: string;
1623
+ /** What the storage held at `file.path` before the write, or `null` when the path was missing or `output.clean` emptied its folder. */
1624
+ stored?: string | null;
1623
1625
  };
1624
1626
  export type KubbFilesProcessingEndContext = {
1625
1627
  /**
package/dist/index.d.ts CHANGED
@@ -909,7 +909,7 @@ declare class FileManager {
909
909
  * memory rather than holding every source, while still overlapping each file's write with the
910
910
  * next file's parse. Files finish in whatever order they parse, so each finished file flushes the
911
911
  * run of finished files ahead of it as one `kubb:files:processing:update`, keeping rows in input order.
912
- * Each parsed source goes out once on `kubb:file:processed`, so listeners read it without the pool holding it.
912
+ * Each parsed source goes out once on `kubb:file:processed`, next to what the storage held before the write.
913
913
  *
914
914
  * A file the storage already holds is skipped, so a rebuild that generates identical output
915
915
  * writes nothing and leaves every mtime where it was. `kubb:files:processing:end` lists the
@@ -1620,6 +1620,8 @@ export type KubbFileProcessedContext = {
1620
1620
  file: FileNode;
1621
1621
  /** The parsed content handed to the storage, before it trims the content or an output pass such as a formatter rewrites it. */
1622
1622
  source: string;
1623
+ /** What the storage held at `file.path` before the write, or `null` when the path was missing or `output.clean` emptied its folder. */
1624
+ stored?: string | null;
1623
1625
  };
1624
1626
  export type KubbFilesProcessingEndContext = {
1625
1627
  /**
package/dist/index.js CHANGED
@@ -3,9 +3,9 @@ import { isValid, satisfies } from "verkit";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
  import process$1 from "node:process";
5
5
  import { x } from "tinyexec";
6
- import { access, glob, mkdir as mkdir$1, mkdtemp as mkdtemp$1, readFile, readdir, rename, rm, rm as rm$1, writeFile } from "node:fs/promises";
6
+ import { chmodSync, existsSync, existsSync as existsSync$1, mkdirSync, readFile, readFileSync, writeFile } from "node:fs";
7
+ import { access, glob, mkdir as mkdir$1, mkdtemp as mkdtemp$1, readFile as readFile$1, readdir, rename, rm, rm as rm$1 } from "node:fs/promises";
7
8
  import path, { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
8
- import { chmodSync, existsSync, existsSync as existsSync$1, mkdirSync } from "node:fs";
9
9
  import { stripVTControlCharacters, styleText } from "node:util";
10
10
  import { ast } from "@kubb/ast";
11
11
  import dns from "node:dns";
@@ -21,7 +21,7 @@ var __name = (target, value) => __defProp(target, "name", {
21
21
  configurable: true
22
22
  });
23
23
  // package.json
24
- var version = "5.18.7";
24
+ var version = "5.18.8";
25
25
  // ../../internals/utils/src/casing.ts
26
26
  /**
27
27
  * Shared implementation for camelCase and PascalCase conversion.
@@ -196,7 +196,25 @@ async function exists(path) {
196
196
  */
197
197
  async function read(path) {
198
198
  if (runtime.isBun) return Bun.file(path).text();
199
- return readFile(path, { encoding: "utf8" });
199
+ return new Promise((resolvePromise, reject) => readFile(path, { encoding: "utf8" }, (error, data) => error ? reject(error) : resolvePromise(data)));
200
+ }
201
+ /**
202
+ * Reads the file at `path` as a UTF-8 string, or `null` when it does not exist or cannot be read.
203
+ * Uses `Bun.file().text()` when running under Bun, `fs.readFileSync` otherwise.
204
+ *
205
+ * @example
206
+ * ```ts
207
+ * const stored = await readIfExists('./src/gen/Pet.ts') // null on a first run
208
+ * ```
209
+ */
210
+ async function readIfExists(path) {
211
+ if (runtime.isBun) return Bun.file(path).text().catch(() => null);
212
+ if (!existsSync$1(path)) return null;
213
+ try {
214
+ return readFileSync(path, "utf8");
215
+ } catch (_error) {
216
+ return null;
217
+ }
200
218
  }
201
219
  /**
202
220
  * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact
@@ -231,7 +249,7 @@ async function write(path, data, options = {}) {
231
249
  const content = `${trimmed}\n`;
232
250
  const resolved = resolve(path);
233
251
  if (matchesStored({
234
- stored: (options.stored === void 0 ? await read(resolved).catch(() => null) : options.stored) ?? "",
252
+ stored: (options.stored === void 0 ? await readIfExists(resolved) : options.stored) ?? "",
235
253
  source: trimmed
236
254
  })) return null;
237
255
  await writeRaw(resolved, content);
@@ -256,11 +274,11 @@ async function writeRaw(path, content) {
256
274
  return;
257
275
  }
258
276
  try {
259
- await writeFile(resolved, content, { encoding: "utf-8" });
277
+ await new Promise((resolvePromise, reject) => writeFile(resolved, content, { encoding: "utf-8" }, (error) => error ? reject(error) : resolvePromise()));
260
278
  } catch (error) {
261
279
  if (error.code !== "ENOENT") throw error;
262
280
  await mkdir$1(dirname(resolved), { recursive: true });
263
- await writeFile(resolved, content, { encoding: "utf-8" });
281
+ await new Promise((resolvePromise, reject) => writeFile(resolved, content, { encoding: "utf-8" }, (error) => error ? reject(error) : resolvePromise()));
264
282
  }
265
283
  }
266
284
  /**
@@ -334,12 +352,33 @@ function isPathInside(path, parent) {
334
352
  * `const refs = memo(refCache, node, () => collectRefs(node))`
335
353
  */
336
354
  function memo$1(store, key, compute) {
337
- if (store.has(key)) return store.get(key);
355
+ const cached = store.get(key);
356
+ if (cached !== void 0 || store.has(key)) return cached;
338
357
  const value = compute();
339
358
  store.set(key, value);
340
359
  return value;
341
360
  }
342
361
  __name(memo$1, "memo");
362
+ function createStore({ type }) {
363
+ if (type === "weak") return /* @__PURE__ */ new WeakMap();
364
+ const entry = /* @__PURE__ */ new Map();
365
+ if (type === "map") return entry;
366
+ const set = (key, value) => {
367
+ entry.clear();
368
+ entry.set(key, value);
369
+ };
370
+ const touch = (key) => {
371
+ if (!entry.has(key)) return false;
372
+ set(key, entry.get(key));
373
+ return true;
374
+ };
375
+ return {
376
+ has: touch,
377
+ get: (key) => touch(key) ? entry.get(key) : void 0,
378
+ set
379
+ };
380
+ }
381
+ memo$1.create = createStore;
343
382
  /**
344
383
  * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each
345
384
  * takes the next item the moment it frees up instead of waiting for a batch to drain.
@@ -1786,6 +1825,7 @@ function isNamespace(value) {
1786
1825
  * reachable and a `file` override is never dropped.
1787
1826
  */
1788
1827
  const resolverOptions = Symbol.for("@kubb/core/resolver/options");
1828
+ const createNameNode = () => ({ next: /* @__PURE__ */ new Map() });
1789
1829
  /**
1790
1830
  * Builds a nested file path from a dotted name. Splits on dots that precede a letter
1791
1831
  * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
@@ -1851,6 +1891,10 @@ var Resolver = class Resolver {
1851
1891
  #options;
1852
1892
  #memo = /* @__PURE__ */ new Map();
1853
1893
  #usedNames = /* @__PURE__ */ new Set();
1894
+ #stringNames = /* @__PURE__ */ new Map();
1895
+ #arrayNames = createNameNode();
1896
+ #outputDirs = /* @__PURE__ */ new WeakMap();
1897
+ #importPaths = /* @__PURE__ */ new WeakMap();
1854
1898
  #tagParents = /* @__PURE__ */ new Map();
1855
1899
  #baseName;
1856
1900
  #filePath;
@@ -1917,16 +1961,30 @@ var Resolver = class Resolver {
1917
1961
  * ```
1918
1962
  */
1919
1963
  resolveName({ key, name, normalize = (name) => name }) {
1920
- const cacheKey = typeof key === "string" ? `s:${key}` : `a:${key.map((segment) => segment === void 0 ? "u" : `${segment.length}:${segment}`).join("")}`;
1921
- const allocate = (suffix) => {
1922
- const candidate = suffix === 1 ? name : `${name}${suffix}`;
1923
- const normalized = normalize(candidate);
1924
- const names = typeof normalized === "string" ? [normalized] : normalized;
1925
- if (names.some((emittedName) => this.#usedNames.has(emittedName))) return allocate(suffix + 1);
1926
- this.reserveNames(names);
1927
- return candidate;
1928
- };
1929
- return this.memo(`resolveName:${cacheKey}`, () => allocate(1));
1964
+ if (typeof key === "string") return memo$1(this.#stringNames, key, () => this.#allocateName({
1965
+ name,
1966
+ normalize,
1967
+ suffix: 1
1968
+ }));
1969
+ const node = key.reduce((parent, segment) => memo$1(parent.next, segment, createNameNode), this.#arrayNames);
1970
+ node.name ??= this.#allocateName({
1971
+ name,
1972
+ normalize,
1973
+ suffix: 1
1974
+ });
1975
+ return node.name;
1976
+ }
1977
+ #allocateName({ name, normalize, suffix }) {
1978
+ const candidate = suffix === 1 ? name : `${name}${suffix}`;
1979
+ const normalized = normalize(candidate);
1980
+ const names = typeof normalized === "string" ? [normalized] : normalized;
1981
+ if (names.some((emittedName) => this.#usedNames.has(emittedName))) return this.#allocateName({
1982
+ name,
1983
+ normalize,
1984
+ suffix: suffix + 1
1985
+ });
1986
+ this.reserveNames(names);
1987
+ return candidate;
1930
1988
  }
1931
1989
  file(options) {
1932
1990
  return this.#resolveFile(options);
@@ -1943,17 +2001,17 @@ var Resolver = class Resolver {
1943
2001
  * reads the same ref set instead of re-scanning it per plugin.
1944
2002
  */
1945
2003
  imports(options) {
1946
- const { node, root, output, group, extname = ".ts", name, checks } = options;
2004
+ const { node, root, output, extname = ".ts", name, checks } = options;
1947
2005
  const resolveName = name ?? ((schemaName) => this.name(schemaName));
2006
+ const paths = memo$1(memo$1(memo$1(this.#importPaths, output, () => /* @__PURE__ */ new Map()), root, () => /* @__PURE__ */ new Map()), extname, () => /* @__PURE__ */ new Map());
1948
2007
  return ast.graph.getImportedNames(node, { checks }).map((schemaName) => ast.factory.createImport({
1949
2008
  name: [resolveName(schemaName)],
1950
- path: this.#resolveFilePath({
2009
+ path: memo$1(paths, schemaName, () => this.#resolveFilePath({
1951
2010
  name: schemaName,
1952
2011
  extname,
1953
2012
  root,
1954
- output,
1955
- group
1956
- })
2013
+ output
2014
+ }))
1957
2015
  }));
1958
2016
  }
1959
2017
  /**
@@ -2025,8 +2083,8 @@ var Resolver = class Resolver {
2025
2083
  * are provided.
2026
2084
  */
2027
2085
  #resolvePath({ baseName, tag, path: groupPath, root, output, group }) {
2028
- if (output.mode !== "directory") return path.resolve(root, output.path);
2029
- const outputDir = path.resolve(root, output.path);
2086
+ const outputDir = memo$1(memo$1(this.#outputDirs, output, () => /* @__PURE__ */ new Map()), root, () => path.resolve(root, output.path));
2087
+ if (output.mode !== "directory") return outputDir;
2030
2088
  const groupValue = group?.type === "path" ? groupPath : tag;
2031
2089
  const result = group && groupValue ? path.resolve(outputDir, this.groupDir(group, groupValue), baseName) : path.resolve(outputDir, baseName);
2032
2090
  assertInside({
@@ -2268,7 +2326,7 @@ function runParser(parser, print) {
2268
2326
  * Reads a `copy` file and prints it through the parser's `copy` hook, or verbatim with `banner`/`footer` when there is none.
2269
2327
  */
2270
2328
  async function parseCopy(file, parser) {
2271
- const content = await readFile(file.copy, "utf8").catch((err) => {
2329
+ const content = await readFile$1(file.copy, "utf8").catch((err) => {
2272
2330
  throw new Diagnostics.Error({
2273
2331
  code: Diagnostics.code.pluginFailed,
2274
2332
  severity: "error",
@@ -2304,7 +2362,8 @@ function compareFiles(a, b) {
2304
2362
  /**
2305
2363
  * Writes `source` to `file.path` unless the storage already holds it, either verbatim or, per the
2306
2364
  * manifest, as what the output passes make of it. Checking here rather than in a driver gives a
2307
- * storage writing to S3 or a database the same guarantee `fsStorage` has. `false` when skipped.
2365
+ * storage writing to S3 or a database the same guarantee `fsStorage` has. `written` is `false` when
2366
+ * skipped, and `stored` is what the storage held before the write.
2308
2367
  */
2309
2368
  async function writeChanged({ storage, manifest, file, source, signal, cleaned }) {
2310
2369
  signal?.throwIfAborted();
@@ -2316,14 +2375,20 @@ async function writeChanged({ storage, manifest, file, source, signal, cleaned }
2316
2375
  key: file.path,
2317
2376
  source,
2318
2377
  disk: stored
2319
- }))) return false;
2378
+ }))) return {
2379
+ written: false,
2380
+ stored
2381
+ };
2320
2382
  signal?.throwIfAborted();
2321
2383
  await storage.writeItem(file.path, source, { stored });
2322
2384
  manifest?.track({
2323
2385
  key: file.path,
2324
2386
  source
2325
2387
  });
2326
- return true;
2388
+ return {
2389
+ written: true,
2390
+ stored
2391
+ };
2327
2392
  }
2328
2393
  /** Reports finished files in input order: each finished file flushes the run of finished files ahead of it as one update. */
2329
2394
  function createProgress(files, config, hooks) {
@@ -2483,7 +2548,7 @@ var FileManager = class {
2483
2548
  * memory rather than holding every source, while still overlapping each file's write with the
2484
2549
  * next file's parse. Files finish in whatever order they parse, so each finished file flushes the
2485
2550
  * run of finished files ahead of it as one `kubb:files:processing:update`, keeping rows in input order.
2486
- * Each parsed source goes out once on `kubb:file:processed`, so listeners read it without the pool holding it.
2551
+ * Each parsed source goes out once on `kubb:file:processed`, next to what the storage held before the write.
2487
2552
  *
2488
2553
  * A file the storage already holds is skipped, so a rebuild that generates identical output
2489
2554
  * writes nothing and leaves every mtime where it was. `kubb:files:processing:end` lists the
@@ -2501,17 +2566,19 @@ var FileManager = class {
2501
2566
  signal?.throwIfAborted();
2502
2567
  const source = await this.parse(file, { parsers });
2503
2568
  if (source) {
2504
- if (!await writeChanged({
2569
+ const { written, stored } = await writeChanged({
2505
2570
  storage,
2506
2571
  manifest,
2507
2572
  file,
2508
2573
  source,
2509
2574
  signal,
2510
2575
  cleaned
2511
- })) unchanged.push(file.path);
2576
+ });
2577
+ if (!written) unchanged.push(file.path);
2512
2578
  await hooks?.callHook("kubb:file:processed", {
2513
2579
  file,
2514
- source
2580
+ source,
2581
+ stored
2515
2582
  });
2516
2583
  }
2517
2584
  await progress?.(index);
@@ -3388,11 +3455,7 @@ const createStorage = (build) => (options) => build(options ?? {});
3388
3455
  const fsStorage = createStorage(() => ({
3389
3456
  name: "fs",
3390
3457
  async readItem(key) {
3391
- try {
3392
- return await read(resolve(key));
3393
- } catch (_error) {
3394
- return null;
3395
- }
3458
+ return readIfExists(resolve(key));
3396
3459
  },
3397
3460
  async writeItem(key, value, options) {
3398
3461
  await write(resolve(key), value, {
@@ -4587,7 +4650,7 @@ function isRegistryEntry(value) {
4587
4650
  }
4588
4651
  // src/installedPackages.ts
4589
4652
  /** Reads and parses a JSON file. Throws when it is missing or not JSON. */
4590
- const readJSON = async (file) => JSON.parse(await readFile(file, "utf8"));
4653
+ const readJSON = async (file) => JSON.parse(await readFile$1(file, "utf8"));
4591
4654
  /**
4592
4655
  * The `dependencies` and `devDependencies` of the project at `root`, plus `packages`, with the
4593
4656
  * installed version and the valid `kubb-extension.json` each one ships, when it does. A package