@kubb/plugin-barrel 5.23.1 → 5.23.3

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
@@ -21,8 +21,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
21
21
  enumerable: true
22
22
  }) : target, mod));
23
23
  let node_path = require("node:path");
24
- node_path = __toESM(node_path, 1);
25
24
  let _kubb_kit = require("@kubb/kit");
25
+ node_path = __toESM(node_path, 1);
26
26
  // ../../internals/utils/src/promise.ts
27
27
  /**
28
28
  * Returns the value cached under `key` in `store`, computing and storing it on the first call.
@@ -64,37 +64,6 @@ function createStore({ weak, max } = {}) {
64
64
  };
65
65
  }
66
66
  memo.create = createStore;
67
- // ../../internals/utils/src/casing.ts
68
- /**
69
- * Shared implementation for camelCase and PascalCase conversion.
70
- * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
71
- * and capitalizes each word according to `pascal`.
72
- *
73
- * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
74
- */
75
- function convert(text, pascal) {
76
- return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)(?!xx(?![a-z]))([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
77
- if (word.length > 1 && word === word.toUpperCase()) return word;
78
- return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
79
- }).join("").replace(/[^a-zA-Z0-9]/g, "");
80
- }
81
- const cache = memo.create({ max: 1e5 });
82
- function toCamelOrPascal(text, pascal) {
83
- const key = `${pascal ? "P" : "c"}${text}`;
84
- return memo(cache, key, () => convert(text, pascal));
85
- }
86
- /**
87
- * Converts `text` to PascalCase.
88
- *
89
- * @example Word boundaries
90
- * `pascalCase('hello-world') // 'HelloWorld'`
91
- *
92
- * @example With a suffix
93
- * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
94
- */
95
- function pascalCase(text, { prefix = "", suffix = "" } = {}) {
96
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
97
- }
98
67
  // ../../internals/utils/src/fs.ts
99
68
  /**
100
69
  * Converts a filesystem path to use POSIX (`/`) separators.
@@ -140,7 +109,7 @@ var compatibility = {
140
109
  "node": ">=22.22"
141
110
  };
142
111
  // package.json
143
- var version = "5.23.1";
112
+ var version = "5.23.3";
144
113
  // src/utils.ts
145
114
  const SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
146
115
  ".ts",
@@ -225,21 +194,22 @@ function getLeafNames(sourceFile) {
225
194
  const { sources } = sourceFile;
226
195
  return memo(leafNamesCache, sourceFile, () => ({
227
196
  hasSources: sources.length > 0,
228
- hasIndexable: sources.some((source) => source.isIndexable),
229
- valueNames: indexableNames(sources, false),
230
- typeNames: indexableNames(sources, true)
197
+ hasExported: sources.some(isExported),
198
+ valueNames: exportedNames(sources, false),
199
+ typeNames: exportedNames(sources, true)
231
200
  }));
232
201
  }
233
- function indexableNames(sources, isTypeOnly) {
234
- const names = sources.flatMap((source) => source.isIndexable && source.name && Boolean(source.isTypeOnly) === isTypeOnly ? [source.name] : []);
202
+ const isExported = (source) => !source.default && !!(source.export ?? source.isIndexable);
203
+ function exportedNames(sources, isTypeOnly) {
204
+ const names = sources.flatMap((source) => isExported(source) && source.name && Boolean(source.isTypeOnly) === isTypeOnly ? [source.name] : []);
235
205
  return [...new Set(names)].sort();
236
206
  }
237
207
  /**
238
- * Re-exports the whole module, unless it has sources and none of them is indexable.
208
+ * Re-exports the whole module, unless it has sources and none of them is exported.
239
209
  */
240
210
  const allStrategy = (path, sourceFile) => {
241
211
  const names = sourceFile && getLeafNames(sourceFile);
242
- return names?.hasSources && !names.hasIndexable ? [] : [_kubb_kit.ast.factory.createExport({ path })];
212
+ return names?.hasSources && !names.hasExported ? [] : [_kubb_kit.ast.factory.createExport({ path })];
243
213
  };
244
214
  /**
245
215
  * Re-exports the indexable names, values and types separately, or the whole module when it has no sources.
@@ -298,7 +268,7 @@ function walkNested(node, ctx) {
298
268
  };
299
269
  const modulePath = toRelativeModulePath(node.path, `${child.path}${BARREL_SUFFIX}`);
300
270
  const exports = [_kubb_kit.ast.factory.createExport({ path: modulePath })];
301
- const name = pascalCase(node_path.posix.basename(child.path));
271
+ const name = _kubb_kit.casing.pascal(node_path.posix.basename(child.path));
302
272
  if (ctx.namespace) exports.push(_kubb_kit.ast.factory.createExport({
303
273
  path: modulePath,
304
274
  name: /^[A-Za-z]/.test(name) ? name : `_${name}`,
@@ -385,16 +355,16 @@ function getBarrelFiles({ index, targetPath, barrelType, nested = false, namespa
385
355
  /**
386
356
  * Applies a plugin's configured `output.banner`/`footer` to a barrel file, flagged as `isBarrel`.
387
357
  *
388
- * Resolves through the plugin's own resolver, and only when the plugin explicitly sets a
389
- * banner/footer, so barrels stay banner-free by default and never inherit the implicit
358
+ * Resolves through the plugin's resolver from the running hook's build memo, and only when the plugin explicitly
359
+ * sets a banner/footer, so barrels stay banner-free by default and never inherit the implicit
390
360
  * "Generated by Kubb" notice.
391
361
  */
392
362
  function withBarrelBannerFooter({ file, plugin, config }) {
393
363
  const output = plugin.options?.output;
394
- const resolver = plugin.resolver;
395
364
  const hasBanner = output?.banner !== void 0;
396
365
  const hasFooter = output?.footer !== void 0;
397
- if (!resolver || !hasBanner && !hasFooter) return file;
366
+ if (!hasBanner && !hasFooter) return file;
367
+ const resolver = (0, _kubb_kit.getResolver)(plugin.name);
398
368
  const context = {
399
369
  output,
400
370
  config,
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["resolve","relative","isAbsolute","posix","Diagnostics","ast","extname","defineExtension","path","Diagnostics","ast"],"sources":["../../../internals/utils/src/promise.ts","../../../internals/utils/src/casing.ts","../../../internals/utils/src/fs.ts","../kubb-extension.json","../package.json","../src/utils.ts","../src/plugin.ts"],"sourcesContent":["/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Returns the value cached under `key` in `store`, computing and storing it on the first call.\n * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive\n * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.\n *\n * @example\n * `const refs = memo(refCache, node, () => collectRefs(node))`\n */\nexport function memo<TKey, TValue>(store: Store<TKey, TValue>, key: TKey, compute: () => TValue): TValue {\n const cached = store.get(key)\n if (cached !== undefined || store.has(key)) return cached as TValue\n const value = compute()\n store.set(key, value)\n return value\n}\n\n/**\n * Creates a store for `memo`. With no options it is a `Map`. Each option changes one thing:\n *\n * - `weak` holds the keys weakly, in a `WeakMap`, so an entry goes away with its key.\n * - `max` bounds the store: it empties itself before the entry that would pass `max`, which keeps a\n * cache in a long-running process from growing without end. `max: 1` keeps only the last entry.\n *\n * @example\n * `const patterns = memo.create<string, RegExp>()`\n *\n * @example Freed with its key\n * `const refs = memo.create<SchemaNode, Array<string>>({ weak: true })`\n *\n * @example Bounded\n * `const names = memo.create<string, string>({ max: 100_000 })`\n *\n * @example Many values per key\n * ```ts\n * const filesByPlugin = memo.create<string, Array<string>>()\n * memo(filesByPlugin, 'plugin-ts', () => []).push('models.ts')\n * ```\n */\nfunction createStore<TKey, TValue>(options?: { weak?: false; max?: undefined }): Map<TKey, TValue>\nfunction createStore<TKey extends WeakKey, TValue>(options: { weak: true; max?: undefined }): WeakMap<TKey, TValue>\nfunction createStore<TKey, TValue>(options: { max: number; weak?: false }): Store<TKey, TValue>\nfunction createStore<TKey, TValue>({ weak, max }: { weak?: boolean; max?: number } = {}): Store<TKey, TValue> {\n if (weak) return new WeakMap<WeakKey, TValue>() as Store<TKey, TValue>\n const entry = new Map<TKey, TValue>()\n if (max === undefined) return entry\n const set = (key: TKey, value: TValue) => {\n if (entry.size >= max) entry.clear()\n entry.set(key, value)\n }\n if (max !== 1) return { has: (key) => entry.has(key), get: (key) => entry.get(key), set }\n // A key equal to the stored one but a different object, such as a copy of a string, replaces the\n // stored key, so the next lookup is an identity hit instead of a full comparison.\n const touch = (key: TKey) => {\n if (!entry.has(key)) return false\n set(key, entry.get(key) as TValue)\n return true\n }\n return { has: touch, get: (key) => (touch(key) ? entry.get(key) : undefined), set }\n}\n\nmemo.create = createStore\n\ntype ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","import { memo } from './promise.ts'\n\ntype Options = {\n /** Text prepended before casing is applied. */\n prefix?: string\n /** Text appended before casing is applied. */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction convert(text: string, pascal: boolean): string {\n return (\n text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n // A status range such as `2xx` stays one word.\n .replace(/(\\d)(?!xx(?![a-z]))([a-z])/g, '$1 $2')\n .split(/[\\s\\-_./\\\\:]+/)\n .filter(Boolean)\n .map((word, i) => {\n if (word.length > 1 && word === word.toUpperCase()) return word\n const head = i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()\n return head + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n )\n}\n\n// Plugins case the same names on every visit. Clearing at the limit bounds a long-running host.\nconst cache = memo.create<string, string>({ max: 100_000 })\n\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n const key = `${pascal ? 'P' : 'c'}${text}`\n return memo(cache, key, () => convert(text, pascal))\n}\n\n/**\n * Converts `text` to camelCase.\n *\n * @example Word boundaries\n * `camelCase('hello-world') // 'helloWorld'`\n *\n * @example With a prefix\n * `camelCase('tag', { prefix: 'create' }) // 'createTag'`\n */\nexport function camelCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n *\n * @example Word boundaries\n * `pascalCase('hello-world') // 'HelloWorld'`\n *\n * @example With a suffix\n * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`\n */\nexport function pascalCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n\n// A word starts at `petType`, `sensor2Reading`, and `HTTPResponse`, while `IDs` and `OAuth` stay whole\nconst wordStart = /(?<=[a-z\\d])(?=[A-Z])|(?<=[A-Z]{2})(?=[A-Z][a-z]{2})/\n\n// A segment without lowercase letters, such as `COOL` or `2D`, stays one word, so a snake_case name is left unchanged.\nfunction words(text: string): Array<string> {\n return text\n .split(/[\\s\\-_./\\\\:]+/)\n .filter(Boolean)\n .flatMap((segment) => (segment === segment.toUpperCase() ? segment : segment.split(wordStart)))\n}\n\n/**\n * Uppercases only the first character of `text`. Unlike `pascalCase` it never splits words or strips characters.\n *\n * @example\n * `capitalize('getPetById') // 'GetPetById'`\n */\nexport function capitalize(text: string): string {\n return `${text.charAt(0).toUpperCase()}${text.slice(1)}`\n}\n\n/**\n * Converts `text` to snake_case.\n *\n * @example\n * `snakeCase('helloWorld') // 'hello_world'`\n */\nexport function snakeCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return words(`${prefix} ${text} ${suffix}`)\n .map((word) => word.replace(/[^a-zA-Z0-9]/g, '').toLowerCase())\n .filter(Boolean)\n .join('_')\n}\n\n/**\n * Converts `text` to SCREAMING_SNAKE_CASE.\n *\n * @example\n * `screamingSnakeCase('helloWorld') // 'HELLO_WORLD'`\n */\nexport function screamingSnakeCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return snakeCase(text, { prefix, suffix }).toUpperCase()\n}\n","import { existsSync, readFile, readFileSync, writeFile } from 'node:fs'\nimport { access, glob as globNode, mkdir } from 'node:fs/promises'\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\nexport { existsSync } from 'node:fs'\nexport { mkdir, mkdtemp, rm } from 'node:fs/promises'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n // The callback API skips the `FileHandle` every `fs/promises` call opens.\n return new Promise((resolvePromise, reject) => readFile(path, { encoding: 'utf8' }, (error, data) => (error ? reject(error) : resolvePromise(data))))\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string, or `null` when it does not exist or cannot be read.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFileSync` otherwise.\n *\n * @example\n * ```ts\n * const stored = await readIfExists('./src/gen/Pet.ts') // null on a first run\n * ```\n */\nexport async function readIfExists(path: string): Promise<string | null> {\n if (runtime.isBun) {\n return Bun.file(path)\n .text()\n .catch(() => null)\n }\n // A small read is faster on the main thread than a thread-pool round trip, and `existsSync`\n // answers a missing file without building an error.\n if (!existsSync(path)) return null\n try {\n return readFileSync(path, 'utf8')\n } catch (_error) {\n return null\n }\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n const stored = options.stored === undefined ? await readIfExists(resolved) : options.stored\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n await writeRaw(resolved, content)\n\n if (options.sanity) {\n const savedData = await read(resolved)\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Writes UTF-8 content verbatim, including empty files and surrounding whitespace.\n * Uses Bun.write under Bun and creates missing parent directories under either runtime.\n *\n * @example\n * await writeRaw('./cache/output.ts', ' // keep these bytes\\n\\n')\n */\nexport async function writeRaw(path: string, content: string): Promise<void> {\n const resolved = resolve(path)\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return\n }\n try {\n await new Promise<void>((resolvePromise, reject) =>\n writeFile(resolved, content, { encoding: 'utf-8' }, (error) => (error ? reject(error) : resolvePromise())),\n )\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await mkdir(dirname(resolved), { recursive: true })\n await new Promise<void>((resolvePromise, reject) =>\n writeFile(resolved, content, { encoding: 'utf-8' }, (error) => (error ? reject(error) : resolvePromise())),\n )\n }\n}\n\n/**\n * Lists non-hidden regular files below `directory` as relative POSIX paths, excluding directories and symlinks.\n * Uses Bun.Glob under Bun because its Node glob compatibility API lacks directory-entry support.\n *\n * @example\n * for await (const path of listFiles('./src')) console.log(path)\n */\nexport async function* listFiles(directory: string): AsyncGenerator<string> {\n const cwd = resolve(directory)\n if (runtime.isBun) {\n yield* new Bun.Glob('**/*').scan({ cwd, dot: false, onlyFiles: true, followSymlinks: false })\n return\n }\n for await (const entry of globNode('**/*', { cwd, withFileTypes: true })) {\n if (entry.isFile()) yield toPosixPath(relative(cwd, join(entry.parentPath, entry.name)))\n }\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","","","import { extname, posix } from 'node:path'\nimport { ast, Diagnostics } from '@kubb/kit'\nimport { memo, pascalCase, toPosixPath } from '@internals/utils'\nimport type { BarrelType } from './types.ts'\n\nconst SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\nconst BARREL_SUFFIX = `/index.ts`\n\n/**\n * A file (no `children`) or directory in the tree barrels are computed from. `path` is absolute and\n * POSIX-normalized, and a directory's `children` are keyed by entry name.\n */\ntype TreeNode = { path: string; children?: undefined } | DirectoryNode\ntype DirectoryNode = { path: string; children: Map<string, TreeNode> }\n\n/** A directory's children in name order, the way a directory listing sorts them. Every barrel of a build walks the same tree. */\nfunction sortedChildren(node: DirectoryNode): ReadonlyArray<TreeNode> {\n return memo(sortedChildrenCache, node, () => [...node.children.entries()].sort(([a], [b]) => (a < b ? -1 : 1)).map(([, child]) => child))\n}\n\nconst sortedChildrenCache = memo.create<DirectoryNode, ReadonlyArray<TreeNode>>({ weak: true })\n\n// An empty, `.` or `..` segment, which `posix.relative` would normalize away.\nconst UNNORMALIZED_SEGMENT = /(?:^|\\/)\\.{0,2}(?:\\/|$)/\n\nfunction toRelativeModulePath(fromDir: string, filePath: string): string {\n // Tree paths extend their parent's path with `/<name>`, so below `fromDir` the relative path is the rest of the path.\n const rest = filePath.startsWith(`${fromDir}/`) ? filePath.slice(fromDir.length + 1) : undefined\n if (rest && !UNNORMALIZED_SEGMENT.test(rest)) return `./${rest}`\n const relativePath = posix.relative(fromDir, filePath)\n return relativePath.startsWith('../') ? relativePath : `./${relativePath}`\n}\n\ntype WalkContext = {\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n barrelFiles: Map<string, ast.FileNode>\n reportedCollisions: Set<string>\n recursive: boolean\n namespace: boolean\n additionalExports: ReadonlyArray<ast.ExportNode>\n leafExports: (dirPath: string, leafPath: string) => Array<ast.ExportNode>\n}\n\nfunction getExportNames({ item, dirPath, ctx }: { item: ast.ExportNode; dirPath: string; ctx: WalkContext }): Array<string> {\n if (item.name != null) return [item.name].flat()\n\n const itemPath = posix.join(dirPath, item.path)\n const barrel = ctx.barrelFiles.get(itemPath)\n if (barrel) return barrel.exports.flatMap((item) => getExportNames({ item, dirPath: posix.dirname(barrel.path), ctx }))\n\n return ctx.sourceFiles.get(itemPath)?.sources.flatMap((source) => source.name || []) ?? []\n}\n\n/**\n * Builds the `index.ts` for `dirPath`. Keeps the first export of each name and reports later duplicates once per build.\n */\nfunction makeBarrel(dirPath: string, exports: Array<ast.ExportNode>, ctx: WalkContext): ast.FileNode {\n const { reportedCollisions } = ctx\n const owners = new Map<string, string>()\n const uniqueExports = exports.flatMap((item) => {\n const itemPath = posix.join(dirPath, item.path)\n // A wildcard export carries no names, so collisions are checked against its source file.\n const names = getExportNames({ item, dirPath, ctx })\n const uniqueNames = names.filter((name) => {\n const first = owners.get(name)\n if (!first) {\n owners.set(name, item.path)\n return true\n }\n\n const key = [name, posix.join(dirPath, first), itemPath].join('\\0')\n if (!reportedCollisions.has(key)) {\n reportedCollisions.add(key)\n Diagnostics.report({\n code: Diagnostics.code.barrelDuplicateExport,\n severity: 'error',\n message: `\"${name}\" is exported by both \"${first}\" and \"${item.path}\", so \"${dirPath}${BARREL_SUFFIX}\" cannot re-export both.`,\n help: 'Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names.',\n })\n }\n return false\n })\n\n if (item.name == null) return [item]\n return uniqueNames.length > 0 ? [ast.factory.createExport({ ...item, name: Array.isArray(item.name) ? uniqueNames : uniqueNames[0] })] : []\n })\n\n const file = ast.factory.createFile({ baseName: 'index.ts', path: `${dirPath}${BARREL_SUFFIX}`, exports: uniqueExports })\n ctx.barrelFiles.set(file.path, file)\n return file\n}\n\ntype LeafStrategy = (path: string, sourceFile: ast.FileNode | undefined) => Array<ast.ExportNode>\n\ntype LeafNames = { hasSources: boolean; hasIndexable: boolean; valueNames: Array<string>; typeNames: Array<string> }\n\n// A nested barrel asks for the same file's names once per ancestor folder; only the relative path differs.\nconst leafNamesCache = memo.create<ast.FileNode, LeafNames>({ weak: true })\n\nfunction getLeafNames(sourceFile: ast.FileNode): LeafNames {\n const { sources } = sourceFile\n return memo(leafNamesCache, sourceFile, () => ({\n hasSources: sources.length > 0,\n hasIndexable: sources.some((source) => source.isIndexable),\n valueNames: indexableNames(sources, false),\n typeNames: indexableNames(sources, true),\n }))\n}\n\nfunction indexableNames(sources: ReadonlyArray<ast.SourceNode>, isTypeOnly: boolean): Array<string> {\n const names = sources.flatMap((source) => (source.isIndexable && source.name && Boolean(source.isTypeOnly) === isTypeOnly ? [source.name] : []))\n return [...new Set(names)].sort()\n}\n\n/**\n * Re-exports the whole module, unless it has sources and none of them is indexable.\n */\nconst allStrategy: LeafStrategy = (path, sourceFile) => {\n const names = sourceFile && getLeafNames(sourceFile)\n return names?.hasSources && !names.hasIndexable ? [] : [ast.factory.createExport({ path })]\n}\n\n/**\n * Re-exports the indexable names, values and types separately, or the whole module when it has no sources.\n */\nconst namedStrategy: LeafStrategy = (path, sourceFile) => {\n const names = sourceFile && getLeafNames(sourceFile)\n if (!names?.hasSources) return [ast.factory.createExport({ path })]\n\n const { valueNames, typeNames } = names\n return [\n ...(valueNames.length > 0 ? [ast.factory.createExport({ name: valueNames, path })] : []),\n ...(typeNames.length > 0 ? [ast.factory.createExport({ name: typeNames, path, isTypeOnly: true })] : []),\n ]\n}\n\ntype FlatWalk = { barrels: Array<ast.FileNode>; leaves: Array<string> }\n\n/**\n * Post-order walk that builds a barrel re-exporting every leaf below the visited directory, for\n * the start node and, with `recursive`, every sub-directory. Also returns the subtree's leaf paths.\n */\nfunction walkFlat(node: DirectoryNode, ctx: WalkContext, isRoot = true): FlatWalk {\n const results = sortedChildren(node).map((child): FlatWalk => (child.children ? walkFlat(child, ctx, false) : { barrels: [], leaves: [child.path] }))\n const barrels = results.flatMap((result) => result.barrels)\n const leaves = results.flatMap((result) => result.leaves)\n const exports = isRoot || ctx.recursive ? leaves.flatMap((leaf) => ctx.leafExports(node.path, leaf)) : []\n if (isRoot) exports.push(...ctx.additionalExports)\n\n return { barrels: exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels, leaves }\n}\n\n/**\n * Recursive walk that builds one barrel per directory, re-exporting files and sub-barrels.\n * Used when nested: true. Leaf files honor the barrel `strategy`, so `named` emits explicit\n * named exports instead of wildcards. Sub-directory barrels are chained with a wildcard\n * re-export, which forwards the names the child barrel already curated. A sub-directory that\n * produced no barrel is never re-exported.\n */\nfunction walkNested(node: DirectoryNode, ctx: WalkContext): Array<ast.FileNode> {\n const results = sortedChildren(node).map((child) => {\n if (!child.children) return { barrels: [], exports: ctx.leafExports(node.path, child.path) }\n\n // A sub-directory has barrels only when it has its own `index.ts`.\n const barrels = walkNested(child, { ...ctx, namespace: false })\n if (barrels.length === 0) return { barrels, exports: [] }\n\n const modulePath = toRelativeModulePath(node.path, `${child.path}${BARREL_SUFFIX}`)\n const exports = [ast.factory.createExport({ path: modulePath })]\n const name = pascalCase(posix.basename(child.path))\n if (ctx.namespace) exports.push(ast.factory.createExport({ path: modulePath, name: /^[A-Za-z]/.test(name) ? name : `_${name}`, asAlias: true }))\n return { barrels, exports }\n })\n const barrels = results.flatMap((result) => result.barrels)\n const exports = results.flatMap((result) => result.exports)\n\n return exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels\n}\n\n/**\n * A directory tree plus the source-file lookup it was built from, scoped to a single output root.\n * Build it once with {@link buildBarrelIndex} and derive every barrel (per-plugin and root) from\n * it via {@link getBarrelFiles}, instead of re-scanning the full file set once per barrel.\n */\ntype BarrelIndex = {\n tree: DirectoryNode\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n}\n\n/**\n * Indexes `files` once for the directory rooted at `outputPath`: filters to indexable source\n * files under that path and builds their directory tree. Reuse the result across every barrel\n * derived from the same root rather than re-filtering and re-building per barrel.\n */\nexport function buildBarrelIndex({\n outputPath,\n files,\n sharedPath,\n}: {\n outputPath: string\n files: ReadonlyArray<ast.FileNode>\n sharedPath?: string\n}): BarrelIndex {\n const tree: DirectoryNode = { path: toPosixPath(outputPath), children: new Map() }\n // Files under `sharedPath` (the config's `shared.path`) join the tree at the same relative position; `outputPath` wins when both match.\n const roots = sharedPath ? [tree.path, toPosixPath(sharedPath)] : [tree.path]\n const rootOf = (filePath: string) => roots.find((root) => filePath.startsWith(`${root}/`))\n const sourceFiles = new Map(\n files.flatMap((file) => {\n const filePath = toPosixPath(file.path)\n const isSource = rootOf(filePath) !== undefined && !filePath.endsWith(BARREL_SUFFIX) && SOURCE_EXTENSIONS.has(extname(filePath))\n return isSource ? [[filePath, file] as const] : []\n }),\n )\n\n for (const filePath of sourceFiles.keys()) {\n const parts = filePath\n .slice(rootOf(filePath)!.length + 1)\n .split('/')\n .filter(Boolean)\n parts.reduce<DirectoryNode>((dir, part, i) => {\n const path = `${dir.path}/${part}`\n const child = memo(dir.children, part, (): TreeNode => (i === parts.length - 1 ? { path: filePath } : { path, children: new Map() }))\n return child.children ? child : dir\n }, tree)\n }\n\n return { tree, sourceFiles }\n}\n\n/**\n * Locates the directory node for `targetPath` within an index tree. Returns `undefined` when no\n * file exists under `targetPath` (nothing to barrel).\n */\nfunction findDirectory(tree: DirectoryNode, targetPath: string): DirectoryNode | undefined {\n if (targetPath === tree.path) return tree\n if (!targetPath.startsWith(`${tree.path}/`)) return undefined\n\n const node = targetPath\n .slice(tree.path.length + 1)\n .split('/')\n .reduce<TreeNode | undefined>((current, part) => current?.children?.get(part), tree)\n return node?.children ? node : undefined\n}\n\ntype GetBarrelFilesParams = {\n /**\n * Index built once via {@link buildBarrelIndex} for the shared output root.\n */\n index: BarrelIndex\n /** Absolute directory to root the barrel(s) at, a subtree of the index root. Defaults to the index root. */\n targetPath?: string\n /** `'all'` re-exports whole modules (`export * from './x'`), `'named'` only the indexable named symbols. */\n barrelType: BarrelType\n /** One `index.ts` per sub-directory, each re-exporting only what is directly inside it. */\n nested?: boolean\n /** Add PascalCase namespace exports for immediate subdirectories and enable nested barrels. */\n namespace?: boolean\n /** Extra exports to forward from plugin barrels into the root barrel. */\n additionalExports?: ReadonlyArray<ast.ExportNode>\n /** Also generate a barrel for each sub-directory when `nested` is false. */\n recursive?: boolean\n /**\n * Collision identities reported by related barrel generations in the same build.\n */\n reportedCollisions?: Set<string>\n}\n\n/**\n * Returns the barrel `ast.FileNode`s for `targetPath` (or the index root), derived from a shared index.\n * Locating the subtree is a bounded walk down from the root, so deriving many barrels (one per\n * plugin, plus the root) from one index avoids re-scanning the full file set for each.\n *\n * @example\n * ```ts\n * const index = buildBarrelIndex({ outputPath, files })\n * getBarrelFiles({ index, targetPath, barrelType }).forEach((file) => upsertFile(file))\n * ```\n */\nexport function getBarrelFiles({\n index,\n targetPath,\n barrelType,\n nested = false,\n namespace = false,\n additionalExports = [],\n recursive = false,\n reportedCollisions = new Set(),\n}: GetBarrelFilesParams): Array<ast.FileNode> {\n const node = targetPath ? findDirectory(index.tree, toPosixPath(targetPath)) : index.tree\n if (!node) return []\n\n const strategy = barrelType === 'named' ? namedStrategy : allStrategy\n const ctx: WalkContext = {\n sourceFiles: index.sourceFiles,\n barrelFiles: new Map(),\n reportedCollisions,\n recursive,\n namespace,\n additionalExports,\n leafExports: (dirPath, leafPath) => strategy(toRelativeModulePath(dirPath, leafPath), index.sourceFiles.get(leafPath)),\n }\n\n return nested || namespace ? walkNested(node, ctx) : walkFlat(node, ctx).barrels\n}\n","import path from 'node:path'\nimport { isPathInside, memo, toPosixPath } from '@internals/utils'\nimport { ast, defineExtension, Diagnostics } from '@kubb/kit'\nimport type { Config, NormalizedPlugin, Plugin } from '@kubb/kit'\nimport { compatibility } from '../kubb-extension.json'\nimport { version } from '../package.json'\nimport type { BarrelType, PluginBarrelConfig } from './types.ts'\nimport { buildBarrelIndex, getBarrelFiles } from './utils.ts'\n\n/**\n * Applies a plugin's configured `output.banner`/`footer` to a barrel file, flagged as `isBarrel`.\n *\n * Resolves through the plugin's own resolver, and only when the plugin explicitly sets a\n * banner/footer, so barrels stay banner-free by default and never inherit the implicit\n * \"Generated by Kubb\" notice.\n */\nfunction withBarrelBannerFooter({ file, plugin, config }: { file: ast.FileNode; plugin: NormalizedPlugin; config: Config }): ast.FileNode {\n const output = plugin.options?.output\n const resolver = plugin.resolver\n const hasBanner = output?.banner !== undefined\n const hasFooter = output?.footer !== undefined\n if (!resolver || (!hasBanner && !hasFooter)) return file\n\n const context = { output, config, file: { path: file.path, baseName: file.baseName, isBarrel: true } }\n return {\n ...file,\n banner: hasBanner ? resolver.default.banner(undefined, context) : file.banner,\n footer: hasFooter ? resolver.default.footer(undefined, context) : file.footer,\n }\n}\n\n/**\n * Canonical plugin name for `@kubb/plugin-barrel`. Used for driver lookups\n * and to guard the `kubb:plugin:end` handler against reacting to its own lifecycle hook.\n */\nexport const pluginBarrelName = 'plugin-barrel' satisfies Plugin['name']\n\ntype PendingBarrel = {\n plugin: NormalizedPlugin\n target: string\n barrelType: BarrelType\n nested: boolean\n namespace: boolean\n}\n\ntype BarrelState = {\n excludedPlugins: Set<string>\n // Subdirectories of `barrel: false` plugins, for files without a `meta.pluginName` owner.\n excludedTargets: Array<string>\n pendingBarrels: Array<PendingBarrel>\n}\n\n// One state per build, keyed by the build's `config`. The object form has no factory closure to hold it.\nconst states = memo.create<Config, BarrelState>({ weak: true })\n\nfunction getState(config: Config): BarrelState {\n return memo(states, config, () => ({ excludedPlugins: new Set(), excludedTargets: [], pendingBarrels: [] }))\n}\n\n/**\n * Generates an `index.ts` for every plugin output directory and one root\n * barrel at `config.output.path/index.ts` after the build completes. Ships\n * with Kubb and is registered by default in `defineConfig`.\n *\n * A plugin without its own `output.barrel` inherits `config.output.barrel`\n * (which defaults to `false`, no root barrel). The default `output` of most\n * plugins carries `barrel: { type: 'named' }`, so they get a barrel unless you\n * pass your own `output` without one. Set `barrel: { type: 'named' | 'all' }` on\n * the root config, a plugin, or both to opt in; a plugin-level `false`\n * overrides an enabled root barrel and also excludes that plugin's files\n * from the root barrel.\n *\n * A plugin with `output.mode: 'file'` gets no per-plugin barrel, since its output\n * is a single file. The root barrel re-exports that file directly.\n *\n * @example\n * ```ts\n * import { defineConfig } from '@kubb/core'\n * import { pluginBarrel } from '@kubb/plugin-barrel'\n * import { pluginTs } from '@kubb/plugin-ts'\n * import { pluginZod } from '@kubb/plugin-zod'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: 'src/gen', barrel: { type: 'named' } },\n * plugins: [\n * pluginTs({ output: { path: 'types', barrel: { type: 'all' } } }),\n * pluginZod({ output: { path: 'schemas' } }),\n * pluginBarrel(),\n * ],\n * })\n * ```\n */\nexport const pluginBarrel = defineExtension({\n kind: 'plugin',\n meta: { name: pluginBarrelName, version, compatibility, issues: 'https://github.com/kubb-labs/kubb/issues' },\n enforce: 'post',\n hooks: {\n 'kubb:plugin:end'({ plugin, config }) {\n // Skip reactions to the barrel plugin's own lifecycle hook\n if (plugin.name === pluginBarrelName) return\n\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n\n // A plugin-level `false` wins over an enabled root barrel.\n const barrelConfig: PluginBarrelConfig | false = plugin.options.output?.barrel ?? config.output.barrel ?? false\n const base = path.resolve(config.root, config.output.path)\n const target = path.resolve(base, plugin.options.output.path ?? '.')\n\n if (barrelConfig === false) {\n excludedPlugins.add(plugin.name)\n // The output root holds every plugin's files, so there only the owner match applies.\n if (target !== base && isPathInside(target, base)) {\n excludedTargets.push(target)\n }\n return\n }\n\n // A plugin at the output root (no own `output.path`) gets no per-plugin barrel, which would\n // claim every other plugin's directory. The root barrel picks up its files.\n if (target === base) {\n if (barrelConfig.namespace) {\n Diagnostics.report({\n code: Diagnostics.code.pluginWarning,\n severity: 'warning',\n message: `Plugin \"${plugin.name}\" sets \\`output.barrel.namespace\\` but writes to the output root, so no namespaces are generated.`,\n help: 'Give the plugin its own `output.path`, such as `client`.',\n })\n }\n return\n }\n\n // `mode: 'file'` writes a single file, so there is no directory to barrel. The root barrel\n // re-exports that file as a direct leaf of `config.output.path`.\n if (plugin.options.output.mode === 'file') {\n return\n }\n\n if (!isPathInside(target, base)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.pathTraversal,\n severity: 'error',\n message: `Output path \"${plugin.options.output.path}\" of plugin \"${plugin.name}\" resolves outside the output directory \"${base}\".`,\n help: 'Keep the plugin `output.path` within `config.output.path`.',\n location: { kind: 'config' },\n })\n }\n\n // Only the target directory and barrel strategy are recorded here. The actual file-set\n // scan and directory-tree build happen once, in `kubb:plugins:end`, and are shared by\n // every plugin barrel plus the root barrel instead of repeating per plugin.\n pendingBarrels.push({ plugin, target, barrelType: barrelConfig.type, nested: barrelConfig.nested ?? false, namespace: barrelConfig.namespace ?? false })\n },\n 'kubb:plugins:end'({ files, config, upsertFile }) {\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n const rootBarrelConfig = config.output.barrel ?? false\n const outputPath = path.resolve(config.root, config.output.path)\n\n // A `barrel: false` plugin gets no barrel and stays out of the root, so drop its files\n // once here. Every barrel below then derives from a single index of what remains.\n const relevantFiles = files.filter((file) => {\n const owner = (file.meta as { pluginName?: string } | undefined)?.pluginName\n if (owner) return !excludedPlugins.has(owner)\n\n return !excludedTargets.some((target) => isPathInside(file.path, target))\n })\n excludedPlugins.clear()\n excludedTargets.length = 0\n\n // Each config's barrels re-export the shared schemas it defines. The shared directory gets none, since each config writes only part of it.\n const index = buildBarrelIndex({\n outputPath,\n files: relevantFiles,\n sharedPath: config.shared && path.resolve(config.root, config.shared.path),\n })\n const reportedCollisions = new Set<string>()\n // Keyed by path and name: plugins sharing an `output.path` produce the same aliases.\n const namespaceExports = new Map<string, ast.ExportNode>()\n\n pendingBarrels.forEach(({ plugin, target, barrelType, nested, namespace }) => {\n getBarrelFiles({ index, targetPath: target, barrelType, nested, namespace, recursive: true, reportedCollisions }).forEach((file) => {\n upsertFile(withBarrelBannerFooter({ file, plugin, config }))\n if (file.path !== `${toPosixPath(target)}/index.ts`) return\n file.exports\n .filter((item) => item.asAlias)\n .forEach((item) => {\n const itemPath = `./${toPosixPath(path.relative(outputPath, path.resolve(target, item.path)))}`\n namespaceExports.set(`${itemPath}\\0${item.name}`, ast.factory.createExport({ ...item, path: itemPath }))\n })\n })\n })\n pendingBarrels.length = 0\n\n if (rootBarrelConfig === false) return\n\n getBarrelFiles({ index, barrelType: rootBarrelConfig.type, additionalExports: [...namespaceExports.values()], reportedCollisions }).forEach((file) => {\n upsertFile(file)\n })\n },\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,KAAmB,OAA4B,KAAW,SAA+B;CACvG,MAAM,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ACL,CAAC;GACH,CAAC;GACD,eAAe,SAAS;GAExB,IAAI,qBAAqB,OAAO;GAEhC,eAAe;IAAE;IAAO,YAAY,iBAAiB;IAAM,mBAAmB,CAAC,GAAG,iBAAiB,OAAO,CAAC;IAAG;GAAmB,CAAC,CAAC,CAAC,SAAS,SAAS;IACpJ,WAAW,IAAI;GACjB,CAAC;EACH;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"index.cjs","names":["resolve","relative","isAbsolute","posix","Diagnostics","ast","casing","extname","getResolver","defineExtension","path","Diagnostics","ast"],"sources":["../../../internals/utils/src/promise.ts","../../../internals/utils/src/fs.ts","../kubb-extension.json","../package.json","../src/utils.ts","../src/plugin.ts"],"sourcesContent":["/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Returns the value cached under `key` in `store`, computing and storing it on the first call.\n * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive\n * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.\n *\n * @example\n * `const refs = memo(refCache, node, () => collectRefs(node))`\n */\nexport function memo<TKey, TValue>(store: Store<TKey, TValue>, key: TKey, compute: () => TValue): TValue {\n const cached = store.get(key)\n if (cached !== undefined || store.has(key)) return cached as TValue\n const value = compute()\n store.set(key, value)\n return value\n}\n\n/**\n * Creates a store for `memo`. With no options it is a `Map`. Each option changes one thing:\n *\n * - `weak` holds the keys weakly, in a `WeakMap`, so an entry goes away with its key.\n * - `max` bounds the store: it empties itself before the entry that would pass `max`, which keeps a\n * cache in a long-running process from growing without end. `max: 1` keeps only the last entry.\n *\n * @example\n * `const patterns = memo.create<string, RegExp>()`\n *\n * @example Freed with its key\n * `const refs = memo.create<SchemaNode, Array<string>>({ weak: true })`\n *\n * @example Bounded\n * `const names = memo.create<string, string>({ max: 100_000 })`\n *\n * @example Many values per key\n * ```ts\n * const filesByPlugin = memo.create<string, Array<string>>()\n * memo(filesByPlugin, 'plugin-ts', () => []).push('models.ts')\n * ```\n */\nfunction createStore<TKey, TValue>(options?: { weak?: false; max?: undefined }): Map<TKey, TValue>\nfunction createStore<TKey extends WeakKey, TValue>(options: { weak: true; max?: undefined }): WeakMap<TKey, TValue>\nfunction createStore<TKey, TValue>(options: { max: number; weak?: false }): Store<TKey, TValue>\nfunction createStore<TKey, TValue>({ weak, max }: { weak?: boolean; max?: number } = {}): Store<TKey, TValue> {\n if (weak) return new WeakMap<WeakKey, TValue>() as Store<TKey, TValue>\n const entry = new Map<TKey, TValue>()\n if (max === undefined) return entry\n const set = (key: TKey, value: TValue) => {\n if (entry.size >= max) entry.clear()\n entry.set(key, value)\n }\n if (max !== 1) return { has: (key) => entry.has(key), get: (key) => entry.get(key), set }\n // A key equal to the stored one but a different object, such as a copy of a string, replaces the\n // stored key, so the next lookup is an identity hit instead of a full comparison.\n const touch = (key: TKey) => {\n if (!entry.has(key)) return false\n set(key, entry.get(key) as TValue)\n return true\n }\n return { has: touch, get: (key) => (touch(key) ? entry.get(key) : undefined), set }\n}\n\nmemo.create = createStore\n\ntype ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","import { existsSync, readFile, readFileSync, writeFile } from 'node:fs'\nimport { access, glob as globNode, mkdir } from 'node:fs/promises'\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\nexport { existsSync } from 'node:fs'\nexport { mkdir, mkdtemp, rm } from 'node:fs/promises'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n // The callback API skips the `FileHandle` every `fs/promises` call opens.\n return new Promise((resolvePromise, reject) => readFile(path, { encoding: 'utf8' }, (error, data) => (error ? reject(error) : resolvePromise(data))))\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string, or `null` when it does not exist or cannot be read.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFileSync` otherwise.\n *\n * @example\n * ```ts\n * const stored = await readIfExists('./src/gen/Pet.ts') // null on a first run\n * ```\n */\nexport async function readIfExists(path: string): Promise<string | null> {\n if (runtime.isBun) {\n return Bun.file(path)\n .text()\n .catch(() => null)\n }\n // A small read is faster on the main thread than a thread-pool round trip, and `existsSync`\n // answers a missing file without building an error.\n if (!existsSync(path)) return null\n try {\n return readFileSync(path, 'utf8')\n } catch (_error) {\n return null\n }\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n const stored = options.stored === undefined ? await readIfExists(resolved) : options.stored\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n await writeRaw(resolved, content)\n\n if (options.sanity) {\n const savedData = await read(resolved)\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Writes UTF-8 content verbatim, including empty files and surrounding whitespace.\n * Uses Bun.write under Bun and creates missing parent directories under either runtime.\n *\n * @example\n * await writeRaw('./cache/output.ts', ' // keep these bytes\\n\\n')\n */\nexport async function writeRaw(path: string, content: string): Promise<void> {\n const resolved = resolve(path)\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return\n }\n try {\n await new Promise<void>((resolvePromise, reject) =>\n writeFile(resolved, content, { encoding: 'utf-8' }, (error) => (error ? reject(error) : resolvePromise())),\n )\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await mkdir(dirname(resolved), { recursive: true })\n await new Promise<void>((resolvePromise, reject) =>\n writeFile(resolved, content, { encoding: 'utf-8' }, (error) => (error ? reject(error) : resolvePromise())),\n )\n }\n}\n\n/**\n * Lists non-hidden regular files below `directory` as relative POSIX paths, excluding directories and symlinks.\n * Uses Bun.Glob under Bun because its Node glob compatibility API lacks directory-entry support.\n *\n * @example\n * for await (const path of listFiles('./src')) console.log(path)\n */\nexport async function* listFiles(directory: string): AsyncGenerator<string> {\n const cwd = resolve(directory)\n if (runtime.isBun) {\n yield* new Bun.Glob('**/*').scan({ cwd, dot: false, onlyFiles: true, followSymlinks: false })\n return\n }\n for await (const entry of globNode('**/*', { cwd, withFileTypes: true })) {\n if (entry.isFile()) yield toPosixPath(relative(cwd, join(entry.parentPath, entry.name)))\n }\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","","","import { extname, posix } from 'node:path'\nimport { ast, casing, Diagnostics } from '@kubb/kit'\nimport { memo, toPosixPath } from '@internals/utils'\nimport type { BarrelType } from './types.ts'\n\nconst SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\nconst BARREL_SUFFIX = `/index.ts`\n\n/**\n * A file (no `children`) or directory in the tree barrels are computed from. `path` is absolute and\n * POSIX-normalized, and a directory's `children` are keyed by entry name.\n */\ntype TreeNode = { path: string; children?: undefined } | DirectoryNode\ntype DirectoryNode = { path: string; children: Map<string, TreeNode> }\n\n/** A directory's children in name order, the way a directory listing sorts them. Every barrel of a build walks the same tree. */\nfunction sortedChildren(node: DirectoryNode): ReadonlyArray<TreeNode> {\n return memo(sortedChildrenCache, node, () => [...node.children.entries()].sort(([a], [b]) => (a < b ? -1 : 1)).map(([, child]) => child))\n}\n\nconst sortedChildrenCache = memo.create<DirectoryNode, ReadonlyArray<TreeNode>>({ weak: true })\n\n// An empty, `.` or `..` segment, which `posix.relative` would normalize away.\nconst UNNORMALIZED_SEGMENT = /(?:^|\\/)\\.{0,2}(?:\\/|$)/\n\nfunction toRelativeModulePath(fromDir: string, filePath: string): string {\n // Tree paths extend their parent's path with `/<name>`, so below `fromDir` the relative path is the rest of the path.\n const rest = filePath.startsWith(`${fromDir}/`) ? filePath.slice(fromDir.length + 1) : undefined\n if (rest && !UNNORMALIZED_SEGMENT.test(rest)) return `./${rest}`\n const relativePath = posix.relative(fromDir, filePath)\n return relativePath.startsWith('../') ? relativePath : `./${relativePath}`\n}\n\ntype WalkContext = {\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n barrelFiles: Map<string, ast.FileNode>\n reportedCollisions: Set<string>\n recursive: boolean\n namespace: boolean\n additionalExports: ReadonlyArray<ast.ExportNode>\n leafExports: (dirPath: string, leafPath: string) => Array<ast.ExportNode>\n}\n\nfunction getExportNames({ item, dirPath, ctx }: { item: ast.ExportNode; dirPath: string; ctx: WalkContext }): Array<string> {\n if (item.name != null) return [item.name].flat()\n\n const itemPath = posix.join(dirPath, item.path)\n const barrel = ctx.barrelFiles.get(itemPath)\n if (barrel) return barrel.exports.flatMap((item) => getExportNames({ item, dirPath: posix.dirname(barrel.path), ctx }))\n\n return ctx.sourceFiles.get(itemPath)?.sources.flatMap((source) => source.name || []) ?? []\n}\n\n/**\n * Builds the `index.ts` for `dirPath`. Keeps the first export of each name and reports later duplicates once per build.\n */\nfunction makeBarrel(dirPath: string, exports: Array<ast.ExportNode>, ctx: WalkContext): ast.FileNode {\n const { reportedCollisions } = ctx\n const owners = new Map<string, string>()\n const uniqueExports = exports.flatMap((item) => {\n const itemPath = posix.join(dirPath, item.path)\n // A wildcard export carries no names, so collisions are checked against its source file.\n const names = getExportNames({ item, dirPath, ctx })\n const uniqueNames = names.filter((name) => {\n const first = owners.get(name)\n if (!first) {\n owners.set(name, item.path)\n return true\n }\n\n const key = [name, posix.join(dirPath, first), itemPath].join('\\0')\n if (!reportedCollisions.has(key)) {\n reportedCollisions.add(key)\n Diagnostics.report({\n code: Diagnostics.code.barrelDuplicateExport,\n severity: 'error',\n message: `\"${name}\" is exported by both \"${first}\" and \"${item.path}\", so \"${dirPath}${BARREL_SUFFIX}\" cannot re-export both.`,\n help: 'Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names.',\n })\n }\n return false\n })\n\n if (item.name == null) return [item]\n return uniqueNames.length > 0 ? [ast.factory.createExport({ ...item, name: Array.isArray(item.name) ? uniqueNames : uniqueNames[0] })] : []\n })\n\n const file = ast.factory.createFile({ baseName: 'index.ts', path: `${dirPath}${BARREL_SUFFIX}`, exports: uniqueExports })\n ctx.barrelFiles.set(file.path, file)\n return file\n}\n\ntype LeafStrategy = (path: string, sourceFile: ast.FileNode | undefined) => Array<ast.ExportNode>\n\ntype LeafNames = { hasSources: boolean; hasExported: boolean; valueNames: Array<string>; typeNames: Array<string> }\n\n// A nested barrel asks for the same file's names once per ancestor folder; only the relative path differs.\nconst leafNamesCache = memo.create<ast.FileNode, LeafNames>({ weak: true })\n\nfunction getLeafNames(sourceFile: ast.FileNode): LeafNames {\n const { sources } = sourceFile\n return memo(leafNamesCache, sourceFile, () => ({\n hasSources: sources.length > 0,\n hasExported: sources.some(isExported),\n valueNames: exportedNames(sources, false),\n typeNames: exportedNames(sources, true),\n }))\n}\n\n// `isIndexable` is the deprecated spelling of `export`. A default export can't be re-exported by name.\nconst isExported = (source: ast.SourceNode): boolean => !source.default && !!(source.export ?? source.isIndexable)\n\nfunction exportedNames(sources: ReadonlyArray<ast.SourceNode>, isTypeOnly: boolean): Array<string> {\n const names = sources.flatMap((source) => (isExported(source) && source.name && Boolean(source.isTypeOnly) === isTypeOnly ? [source.name] : []))\n return [...new Set(names)].sort()\n}\n\n/**\n * Re-exports the whole module, unless it has sources and none of them is exported.\n */\nconst allStrategy: LeafStrategy = (path, sourceFile) => {\n const names = sourceFile && getLeafNames(sourceFile)\n return names?.hasSources && !names.hasExported ? [] : [ast.factory.createExport({ path })]\n}\n\n/**\n * Re-exports the indexable names, values and types separately, or the whole module when it has no sources.\n */\nconst namedStrategy: LeafStrategy = (path, sourceFile) => {\n const names = sourceFile && getLeafNames(sourceFile)\n if (!names?.hasSources) return [ast.factory.createExport({ path })]\n\n const { valueNames, typeNames } = names\n return [\n ...(valueNames.length > 0 ? [ast.factory.createExport({ name: valueNames, path })] : []),\n ...(typeNames.length > 0 ? [ast.factory.createExport({ name: typeNames, path, isTypeOnly: true })] : []),\n ]\n}\n\ntype FlatWalk = { barrels: Array<ast.FileNode>; leaves: Array<string> }\n\n/**\n * Post-order walk that builds a barrel re-exporting every leaf below the visited directory, for\n * the start node and, with `recursive`, every sub-directory. Also returns the subtree's leaf paths.\n */\nfunction walkFlat(node: DirectoryNode, ctx: WalkContext, isRoot = true): FlatWalk {\n const results = sortedChildren(node).map((child): FlatWalk => (child.children ? walkFlat(child, ctx, false) : { barrels: [], leaves: [child.path] }))\n const barrels = results.flatMap((result) => result.barrels)\n const leaves = results.flatMap((result) => result.leaves)\n const exports = isRoot || ctx.recursive ? leaves.flatMap((leaf) => ctx.leafExports(node.path, leaf)) : []\n if (isRoot) exports.push(...ctx.additionalExports)\n\n return { barrels: exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels, leaves }\n}\n\n/**\n * Recursive walk that builds one barrel per directory, re-exporting files and sub-barrels.\n * Used when nested: true. Leaf files honor the barrel `strategy`, so `named` emits explicit\n * named exports instead of wildcards. Sub-directory barrels are chained with a wildcard\n * re-export, which forwards the names the child barrel already curated. A sub-directory that\n * produced no barrel is never re-exported.\n */\nfunction walkNested(node: DirectoryNode, ctx: WalkContext): Array<ast.FileNode> {\n const results = sortedChildren(node).map((child) => {\n if (!child.children) return { barrels: [], exports: ctx.leafExports(node.path, child.path) }\n\n // A sub-directory has barrels only when it has its own `index.ts`.\n const barrels = walkNested(child, { ...ctx, namespace: false })\n if (barrels.length === 0) return { barrels, exports: [] }\n\n const modulePath = toRelativeModulePath(node.path, `${child.path}${BARREL_SUFFIX}`)\n const exports = [ast.factory.createExport({ path: modulePath })]\n const name = casing.pascal(posix.basename(child.path))\n if (ctx.namespace) exports.push(ast.factory.createExport({ path: modulePath, name: /^[A-Za-z]/.test(name) ? name : `_${name}`, asAlias: true }))\n return { barrels, exports }\n })\n const barrels = results.flatMap((result) => result.barrels)\n const exports = results.flatMap((result) => result.exports)\n\n return exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels\n}\n\n/**\n * A directory tree plus the source-file lookup it was built from, scoped to a single output root.\n * Build it once with {@link buildBarrelIndex} and derive every barrel (per-plugin and root) from\n * it via {@link getBarrelFiles}, instead of re-scanning the full file set once per barrel.\n */\ntype BarrelIndex = {\n tree: DirectoryNode\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n}\n\n/**\n * Indexes `files` once for the directory rooted at `outputPath`: filters to indexable source\n * files under that path and builds their directory tree. Reuse the result across every barrel\n * derived from the same root rather than re-filtering and re-building per barrel.\n */\nexport function buildBarrelIndex({\n outputPath,\n files,\n sharedPath,\n}: {\n outputPath: string\n files: ReadonlyArray<ast.FileNode>\n sharedPath?: string\n}): BarrelIndex {\n const tree: DirectoryNode = { path: toPosixPath(outputPath), children: new Map() }\n // Files under `sharedPath` (the config's `shared.path`) join the tree at the same relative position; `outputPath` wins when both match.\n const roots = sharedPath ? [tree.path, toPosixPath(sharedPath)] : [tree.path]\n const rootOf = (filePath: string) => roots.find((root) => filePath.startsWith(`${root}/`))\n const sourceFiles = new Map(\n files.flatMap((file) => {\n const filePath = toPosixPath(file.path)\n const isSource = rootOf(filePath) !== undefined && !filePath.endsWith(BARREL_SUFFIX) && SOURCE_EXTENSIONS.has(extname(filePath))\n return isSource ? [[filePath, file] as const] : []\n }),\n )\n\n for (const filePath of sourceFiles.keys()) {\n const parts = filePath\n .slice(rootOf(filePath)!.length + 1)\n .split('/')\n .filter(Boolean)\n parts.reduce<DirectoryNode>((dir, part, i) => {\n const path = `${dir.path}/${part}`\n const child = memo(dir.children, part, (): TreeNode => (i === parts.length - 1 ? { path: filePath } : { path, children: new Map() }))\n return child.children ? child : dir\n }, tree)\n }\n\n return { tree, sourceFiles }\n}\n\n/**\n * Locates the directory node for `targetPath` within an index tree. Returns `undefined` when no\n * file exists under `targetPath` (nothing to barrel).\n */\nfunction findDirectory(tree: DirectoryNode, targetPath: string): DirectoryNode | undefined {\n if (targetPath === tree.path) return tree\n if (!targetPath.startsWith(`${tree.path}/`)) return undefined\n\n const node = targetPath\n .slice(tree.path.length + 1)\n .split('/')\n .reduce<TreeNode | undefined>((current, part) => current?.children?.get(part), tree)\n return node?.children ? node : undefined\n}\n\ntype GetBarrelFilesParams = {\n /**\n * Index built once via {@link buildBarrelIndex} for the shared output root.\n */\n index: BarrelIndex\n /** Absolute directory to root the barrel(s) at, a subtree of the index root. Defaults to the index root. */\n targetPath?: string\n /** `'all'` re-exports whole modules (`export * from './x'`), `'named'` only the indexable named symbols. */\n barrelType: BarrelType\n /** One `index.ts` per sub-directory, each re-exporting only what is directly inside it. */\n nested?: boolean\n /** Add PascalCase namespace exports for immediate subdirectories and enable nested barrels. */\n namespace?: boolean\n /** Extra exports to forward from plugin barrels into the root barrel. */\n additionalExports?: ReadonlyArray<ast.ExportNode>\n /** Also generate a barrel for each sub-directory when `nested` is false. */\n recursive?: boolean\n /**\n * Collision identities reported by related barrel generations in the same build.\n */\n reportedCollisions?: Set<string>\n}\n\n/**\n * Returns the barrel `ast.FileNode`s for `targetPath` (or the index root), derived from a shared index.\n * Locating the subtree is a bounded walk down from the root, so deriving many barrels (one per\n * plugin, plus the root) from one index avoids re-scanning the full file set for each.\n *\n * @example\n * ```ts\n * const index = buildBarrelIndex({ outputPath, files })\n * getBarrelFiles({ index, targetPath, barrelType }).forEach((file) => upsertFile(file))\n * ```\n */\nexport function getBarrelFiles({\n index,\n targetPath,\n barrelType,\n nested = false,\n namespace = false,\n additionalExports = [],\n recursive = false,\n reportedCollisions = new Set(),\n}: GetBarrelFilesParams): Array<ast.FileNode> {\n const node = targetPath ? findDirectory(index.tree, toPosixPath(targetPath)) : index.tree\n if (!node) return []\n\n const strategy = barrelType === 'named' ? namedStrategy : allStrategy\n const ctx: WalkContext = {\n sourceFiles: index.sourceFiles,\n barrelFiles: new Map(),\n reportedCollisions,\n recursive,\n namespace,\n additionalExports,\n leafExports: (dirPath, leafPath) => strategy(toRelativeModulePath(dirPath, leafPath), index.sourceFiles.get(leafPath)),\n }\n\n return nested || namespace ? walkNested(node, ctx) : walkFlat(node, ctx).barrels\n}\n","import path from 'node:path'\nimport { isPathInside, memo, toPosixPath } from '@internals/utils'\nimport { ast, defineExtension, Diagnostics, getResolver } from '@kubb/kit'\nimport type { Config, NormalizedPlugin, Plugin } from '@kubb/kit'\nimport { compatibility } from '../kubb-extension.json'\nimport { version } from '../package.json'\nimport type { BarrelType, PluginBarrelConfig } from './types.ts'\nimport { buildBarrelIndex, getBarrelFiles } from './utils.ts'\n\n/**\n * Applies a plugin's configured `output.banner`/`footer` to a barrel file, flagged as `isBarrel`.\n *\n * Resolves through the plugin's resolver from the running hook's build memo, and only when the plugin explicitly\n * sets a banner/footer, so barrels stay banner-free by default and never inherit the implicit\n * \"Generated by Kubb\" notice.\n */\nfunction withBarrelBannerFooter({ file, plugin, config }: { file: ast.FileNode; plugin: NormalizedPlugin; config: Config }): ast.FileNode {\n const output = plugin.options?.output\n const hasBanner = output?.banner !== undefined\n const hasFooter = output?.footer !== undefined\n if (!hasBanner && !hasFooter) return file\n\n const resolver = getResolver(plugin.name)\n\n const context = { output, config, file: { path: file.path, baseName: file.baseName, isBarrel: true } }\n return {\n ...file,\n banner: hasBanner ? resolver.default.banner(undefined, context) : file.banner,\n footer: hasFooter ? resolver.default.footer(undefined, context) : file.footer,\n }\n}\n\n/**\n * Canonical plugin name for `@kubb/plugin-barrel`. Used for driver lookups\n * and to guard the `kubb:plugin:end` handler against reacting to its own lifecycle hook.\n */\nexport const pluginBarrelName = 'plugin-barrel' satisfies Plugin['name']\n\ntype PendingBarrel = {\n plugin: NormalizedPlugin\n target: string\n barrelType: BarrelType\n nested: boolean\n namespace: boolean\n}\n\ntype BarrelState = {\n excludedPlugins: Set<string>\n // Subdirectories of `barrel: false` plugins, for files without a `meta.pluginName` owner.\n excludedTargets: Array<string>\n pendingBarrels: Array<PendingBarrel>\n}\n\n// One state per build, keyed by the build's `config`. The object form has no factory closure to hold it.\nconst states = memo.create<Config, BarrelState>({ weak: true })\n\nfunction getState(config: Config): BarrelState {\n return memo(states, config, () => ({ excludedPlugins: new Set(), excludedTargets: [], pendingBarrels: [] }))\n}\n\n/**\n * Generates an `index.ts` for every plugin output directory and one root\n * barrel at `config.output.path/index.ts` after the build completes. Ships\n * with Kubb and is registered by default in `defineConfig`.\n *\n * A plugin without its own `output.barrel` inherits `config.output.barrel`\n * (which defaults to `false`, no root barrel). The default `output` of most\n * plugins carries `barrel: { type: 'named' }`, so they get a barrel unless you\n * pass your own `output` without one. Set `barrel: { type: 'named' | 'all' }` on\n * the root config, a plugin, or both to opt in; a plugin-level `false`\n * overrides an enabled root barrel and also excludes that plugin's files\n * from the root barrel.\n *\n * A plugin with `output.mode: 'file'` gets no per-plugin barrel, since its output\n * is a single file. The root barrel re-exports that file directly.\n *\n * @example\n * ```ts\n * import { defineConfig } from '@kubb/core'\n * import { pluginBarrel } from '@kubb/plugin-barrel'\n * import { pluginTs } from '@kubb/plugin-ts'\n * import { pluginZod } from '@kubb/plugin-zod'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: 'src/gen', barrel: { type: 'named' } },\n * plugins: [\n * pluginTs({ output: { path: 'types', barrel: { type: 'all' } } }),\n * pluginZod({ output: { path: 'schemas' } }),\n * pluginBarrel(),\n * ],\n * })\n * ```\n */\nexport const pluginBarrel = defineExtension({\n kind: 'plugin',\n meta: { name: pluginBarrelName, version, compatibility, issues: 'https://github.com/kubb-labs/kubb/issues' },\n enforce: 'post',\n hooks: {\n 'kubb:plugin:end'({ plugin, config }) {\n // Skip reactions to the barrel plugin's own lifecycle hook\n if (plugin.name === pluginBarrelName) return\n\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n\n // A plugin-level `false` wins over an enabled root barrel.\n const barrelConfig: PluginBarrelConfig | false = plugin.options.output?.barrel ?? config.output.barrel ?? false\n const base = path.resolve(config.root, config.output.path)\n const target = path.resolve(base, plugin.options.output.path ?? '.')\n\n if (barrelConfig === false) {\n excludedPlugins.add(plugin.name)\n // The output root holds every plugin's files, so there only the owner match applies.\n if (target !== base && isPathInside(target, base)) {\n excludedTargets.push(target)\n }\n return\n }\n\n // A plugin at the output root (no own `output.path`) gets no per-plugin barrel, which would\n // claim every other plugin's directory. The root barrel picks up its files.\n if (target === base) {\n if (barrelConfig.namespace) {\n Diagnostics.report({\n code: Diagnostics.code.pluginWarning,\n severity: 'warning',\n message: `Plugin \"${plugin.name}\" sets \\`output.barrel.namespace\\` but writes to the output root, so no namespaces are generated.`,\n help: 'Give the plugin its own `output.path`, such as `client`.',\n })\n }\n return\n }\n\n // `mode: 'file'` writes a single file, so there is no directory to barrel. The root barrel\n // re-exports that file as a direct leaf of `config.output.path`.\n if (plugin.options.output.mode === 'file') {\n return\n }\n\n if (!isPathInside(target, base)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.pathTraversal,\n severity: 'error',\n message: `Output path \"${plugin.options.output.path}\" of plugin \"${plugin.name}\" resolves outside the output directory \"${base}\".`,\n help: 'Keep the plugin `output.path` within `config.output.path`.',\n location: { kind: 'config' },\n })\n }\n\n // Only the target directory and barrel strategy are recorded here. The actual file-set\n // scan and directory-tree build happen once, in `kubb:plugins:end`, and are shared by\n // every plugin barrel plus the root barrel instead of repeating per plugin.\n pendingBarrels.push({ plugin, target, barrelType: barrelConfig.type, nested: barrelConfig.nested ?? false, namespace: barrelConfig.namespace ?? false })\n },\n 'kubb:plugins:end'({ files, config, upsertFile }) {\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n const rootBarrelConfig = config.output.barrel ?? false\n const outputPath = path.resolve(config.root, config.output.path)\n\n // A `barrel: false` plugin gets no barrel and stays out of the root, so drop its files\n // once here. Every barrel below then derives from a single index of what remains.\n const relevantFiles = files.filter((file) => {\n const owner = (file.meta as { pluginName?: string } | undefined)?.pluginName\n if (owner) return !excludedPlugins.has(owner)\n\n return !excludedTargets.some((target) => isPathInside(file.path, target))\n })\n excludedPlugins.clear()\n excludedTargets.length = 0\n\n // Each config's barrels re-export the shared schemas it defines. The shared directory gets none, since each config writes only part of it.\n const index = buildBarrelIndex({\n outputPath,\n files: relevantFiles,\n sharedPath: config.shared && path.resolve(config.root, config.shared.path),\n })\n const reportedCollisions = new Set<string>()\n // Keyed by path and name: plugins sharing an `output.path` produce the same aliases.\n const namespaceExports = new Map<string, ast.ExportNode>()\n\n pendingBarrels.forEach(({ plugin, target, barrelType, nested, namespace }) => {\n getBarrelFiles({ index, targetPath: target, barrelType, nested, namespace, recursive: true, reportedCollisions }).forEach((file) => {\n upsertFile(withBarrelBannerFooter({ file, plugin, config }))\n if (file.path !== `${toPosixPath(target)}/index.ts`) return\n file.exports\n .filter((item) => item.asAlias)\n .forEach((item) => {\n const itemPath = `./${toPosixPath(path.relative(outputPath, path.resolve(target, item.path)))}`\n namespaceExports.set(`${itemPath}\\0${item.name}`, ast.factory.createExport({ ...item, path: itemPath }))\n })\n })\n })\n pendingBarrels.length = 0\n\n if (rootBarrelConfig === false) return\n\n getBarrelFiles({ index, barrelType: rootBarrelConfig.type, additionalExports: [...namespaceExports.values()], reportedCollisions }).forEach((file) => {\n upsertFile(file)\n })\n },\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,KAAmB,OAA4B,KAAW,SAA+B;CACvG,MAAM,SAAS,MAAM,IAAI,GAAG;CAC5B,IAAI,WAAW,KAAA,KAAa,MAAM,IAAI,GAAG,GAAG,OAAO;CACnD,MAAM,QAAQ,QAAQ;CACtB,MAAM,IAAI,KAAK,KAAK;CACpB,OAAO;AACT;AA2BA,SAAS,YAA0B,EAAE,MAAM,QAA0C,CAAC,GAAwB;CAC5G,IAAI,MAAM,uBAAO,IAAI,QAAyB;CAC9C,MAAM,wBAAQ,IAAI,IAAkB;CACpC,IAAI,QAAQ,KAAA,GAAW,OAAO;CAC9B,MAAM,OAAO,KAAW,UA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AI,GAAG,SAAS,IAAI,KAAK,QAAQE,UAAAA,IAAI,QAAQ,aAAa;OAAE,GAAG;OAAM,MAAM;MAAS,CAAC,CAAC;KACzG,CAAC;IACL,CAAC;GACH,CAAC;GACD,eAAe,SAAS;GAExB,IAAI,qBAAqB,OAAO;GAEhC,eAAe;IAAE;IAAO,YAAY,iBAAiB;IAAM,mBAAmB,CAAC,GAAG,iBAAiB,OAAO,CAAC;IAAG;GAAmB,CAAC,CAAC,CAAC,SAAS,SAAS;IACpJ,WAAW,IAAI;GACjB,CAAC;EACH;CACF;AACF,CAAC"}
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import path, { extname, isAbsolute, posix, relative, resolve } from "node:path";
2
- import { Diagnostics, ast, defineExtension } from "@kubb/kit";
2
+ import { Diagnostics, ast, casing, defineExtension, getResolver } from "@kubb/kit";
3
3
  // ../../internals/utils/src/promise.ts
4
4
  /**
5
5
  * Returns the value cached under `key` in `store`, computing and storing it on the first call.
@@ -41,37 +41,6 @@ function createStore({ weak, max } = {}) {
41
41
  };
42
42
  }
43
43
  memo.create = createStore;
44
- // ../../internals/utils/src/casing.ts
45
- /**
46
- * Shared implementation for camelCase and PascalCase conversion.
47
- * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
48
- * and capitalizes each word according to `pascal`.
49
- *
50
- * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
51
- */
52
- function convert(text, pascal) {
53
- return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)(?!xx(?![a-z]))([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
54
- if (word.length > 1 && word === word.toUpperCase()) return word;
55
- return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
56
- }).join("").replace(/[^a-zA-Z0-9]/g, "");
57
- }
58
- const cache = memo.create({ max: 1e5 });
59
- function toCamelOrPascal(text, pascal) {
60
- const key = `${pascal ? "P" : "c"}${text}`;
61
- return memo(cache, key, () => convert(text, pascal));
62
- }
63
- /**
64
- * Converts `text` to PascalCase.
65
- *
66
- * @example Word boundaries
67
- * `pascalCase('hello-world') // 'HelloWorld'`
68
- *
69
- * @example With a suffix
70
- * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
71
- */
72
- function pascalCase(text, { prefix = "", suffix = "" } = {}) {
73
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
74
- }
75
44
  // ../../internals/utils/src/fs.ts
76
45
  /**
77
46
  * Converts a filesystem path to use POSIX (`/`) separators.
@@ -117,7 +86,7 @@ var compatibility = {
117
86
  "node": ">=22.22"
118
87
  };
119
88
  // package.json
120
- var version = "5.23.1";
89
+ var version = "5.23.3";
121
90
  // src/utils.ts
122
91
  const SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
123
92
  ".ts",
@@ -202,21 +171,22 @@ function getLeafNames(sourceFile) {
202
171
  const { sources } = sourceFile;
203
172
  return memo(leafNamesCache, sourceFile, () => ({
204
173
  hasSources: sources.length > 0,
205
- hasIndexable: sources.some((source) => source.isIndexable),
206
- valueNames: indexableNames(sources, false),
207
- typeNames: indexableNames(sources, true)
174
+ hasExported: sources.some(isExported),
175
+ valueNames: exportedNames(sources, false),
176
+ typeNames: exportedNames(sources, true)
208
177
  }));
209
178
  }
210
- function indexableNames(sources, isTypeOnly) {
211
- const names = sources.flatMap((source) => source.isIndexable && source.name && Boolean(source.isTypeOnly) === isTypeOnly ? [source.name] : []);
179
+ const isExported = (source) => !source.default && !!(source.export ?? source.isIndexable);
180
+ function exportedNames(sources, isTypeOnly) {
181
+ const names = sources.flatMap((source) => isExported(source) && source.name && Boolean(source.isTypeOnly) === isTypeOnly ? [source.name] : []);
212
182
  return [...new Set(names)].sort();
213
183
  }
214
184
  /**
215
- * Re-exports the whole module, unless it has sources and none of them is indexable.
185
+ * Re-exports the whole module, unless it has sources and none of them is exported.
216
186
  */
217
187
  const allStrategy = (path, sourceFile) => {
218
188
  const names = sourceFile && getLeafNames(sourceFile);
219
- return names?.hasSources && !names.hasIndexable ? [] : [ast.factory.createExport({ path })];
189
+ return names?.hasSources && !names.hasExported ? [] : [ast.factory.createExport({ path })];
220
190
  };
221
191
  /**
222
192
  * Re-exports the indexable names, values and types separately, or the whole module when it has no sources.
@@ -275,7 +245,7 @@ function walkNested(node, ctx) {
275
245
  };
276
246
  const modulePath = toRelativeModulePath(node.path, `${child.path}${BARREL_SUFFIX}`);
277
247
  const exports = [ast.factory.createExport({ path: modulePath })];
278
- const name = pascalCase(posix.basename(child.path));
248
+ const name = casing.pascal(posix.basename(child.path));
279
249
  if (ctx.namespace) exports.push(ast.factory.createExport({
280
250
  path: modulePath,
281
251
  name: /^[A-Za-z]/.test(name) ? name : `_${name}`,
@@ -362,16 +332,16 @@ function getBarrelFiles({ index, targetPath, barrelType, nested = false, namespa
362
332
  /**
363
333
  * Applies a plugin's configured `output.banner`/`footer` to a barrel file, flagged as `isBarrel`.
364
334
  *
365
- * Resolves through the plugin's own resolver, and only when the plugin explicitly sets a
366
- * banner/footer, so barrels stay banner-free by default and never inherit the implicit
335
+ * Resolves through the plugin's resolver from the running hook's build memo, and only when the plugin explicitly
336
+ * sets a banner/footer, so barrels stay banner-free by default and never inherit the implicit
367
337
  * "Generated by Kubb" notice.
368
338
  */
369
339
  function withBarrelBannerFooter({ file, plugin, config }) {
370
340
  const output = plugin.options?.output;
371
- const resolver = plugin.resolver;
372
341
  const hasBanner = output?.banner !== void 0;
373
342
  const hasFooter = output?.footer !== void 0;
374
- if (!resolver || !hasBanner && !hasFooter) return file;
343
+ if (!hasBanner && !hasFooter) return file;
344
+ const resolver = getResolver(plugin.name);
375
345
  const context = {
376
346
  output,
377
347
  config,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../internals/utils/src/promise.ts","../../../internals/utils/src/casing.ts","../../../internals/utils/src/fs.ts","../kubb-extension.json","../package.json","../src/utils.ts","../src/plugin.ts"],"sourcesContent":["/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Returns the value cached under `key` in `store`, computing and storing it on the first call.\n * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive\n * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.\n *\n * @example\n * `const refs = memo(refCache, node, () => collectRefs(node))`\n */\nexport function memo<TKey, TValue>(store: Store<TKey, TValue>, key: TKey, compute: () => TValue): TValue {\n const cached = store.get(key)\n if (cached !== undefined || store.has(key)) return cached as TValue\n const value = compute()\n store.set(key, value)\n return value\n}\n\n/**\n * Creates a store for `memo`. With no options it is a `Map`. Each option changes one thing:\n *\n * - `weak` holds the keys weakly, in a `WeakMap`, so an entry goes away with its key.\n * - `max` bounds the store: it empties itself before the entry that would pass `max`, which keeps a\n * cache in a long-running process from growing without end. `max: 1` keeps only the last entry.\n *\n * @example\n * `const patterns = memo.create<string, RegExp>()`\n *\n * @example Freed with its key\n * `const refs = memo.create<SchemaNode, Array<string>>({ weak: true })`\n *\n * @example Bounded\n * `const names = memo.create<string, string>({ max: 100_000 })`\n *\n * @example Many values per key\n * ```ts\n * const filesByPlugin = memo.create<string, Array<string>>()\n * memo(filesByPlugin, 'plugin-ts', () => []).push('models.ts')\n * ```\n */\nfunction createStore<TKey, TValue>(options?: { weak?: false; max?: undefined }): Map<TKey, TValue>\nfunction createStore<TKey extends WeakKey, TValue>(options: { weak: true; max?: undefined }): WeakMap<TKey, TValue>\nfunction createStore<TKey, TValue>(options: { max: number; weak?: false }): Store<TKey, TValue>\nfunction createStore<TKey, TValue>({ weak, max }: { weak?: boolean; max?: number } = {}): Store<TKey, TValue> {\n if (weak) return new WeakMap<WeakKey, TValue>() as Store<TKey, TValue>\n const entry = new Map<TKey, TValue>()\n if (max === undefined) return entry\n const set = (key: TKey, value: TValue) => {\n if (entry.size >= max) entry.clear()\n entry.set(key, value)\n }\n if (max !== 1) return { has: (key) => entry.has(key), get: (key) => entry.get(key), set }\n // A key equal to the stored one but a different object, such as a copy of a string, replaces the\n // stored key, so the next lookup is an identity hit instead of a full comparison.\n const touch = (key: TKey) => {\n if (!entry.has(key)) return false\n set(key, entry.get(key) as TValue)\n return true\n }\n return { has: touch, get: (key) => (touch(key) ? entry.get(key) : undefined), set }\n}\n\nmemo.create = createStore\n\ntype ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","import { memo } from './promise.ts'\n\ntype Options = {\n /** Text prepended before casing is applied. */\n prefix?: string\n /** Text appended before casing is applied. */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction convert(text: string, pascal: boolean): string {\n return (\n text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n // A status range such as `2xx` stays one word.\n .replace(/(\\d)(?!xx(?![a-z]))([a-z])/g, '$1 $2')\n .split(/[\\s\\-_./\\\\:]+/)\n .filter(Boolean)\n .map((word, i) => {\n if (word.length > 1 && word === word.toUpperCase()) return word\n const head = i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()\n return head + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n )\n}\n\n// Plugins case the same names on every visit. Clearing at the limit bounds a long-running host.\nconst cache = memo.create<string, string>({ max: 100_000 })\n\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n const key = `${pascal ? 'P' : 'c'}${text}`\n return memo(cache, key, () => convert(text, pascal))\n}\n\n/**\n * Converts `text` to camelCase.\n *\n * @example Word boundaries\n * `camelCase('hello-world') // 'helloWorld'`\n *\n * @example With a prefix\n * `camelCase('tag', { prefix: 'create' }) // 'createTag'`\n */\nexport function camelCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n *\n * @example Word boundaries\n * `pascalCase('hello-world') // 'HelloWorld'`\n *\n * @example With a suffix\n * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`\n */\nexport function pascalCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n\n// A word starts at `petType`, `sensor2Reading`, and `HTTPResponse`, while `IDs` and `OAuth` stay whole\nconst wordStart = /(?<=[a-z\\d])(?=[A-Z])|(?<=[A-Z]{2})(?=[A-Z][a-z]{2})/\n\n// A segment without lowercase letters, such as `COOL` or `2D`, stays one word, so a snake_case name is left unchanged.\nfunction words(text: string): Array<string> {\n return text\n .split(/[\\s\\-_./\\\\:]+/)\n .filter(Boolean)\n .flatMap((segment) => (segment === segment.toUpperCase() ? segment : segment.split(wordStart)))\n}\n\n/**\n * Uppercases only the first character of `text`. Unlike `pascalCase` it never splits words or strips characters.\n *\n * @example\n * `capitalize('getPetById') // 'GetPetById'`\n */\nexport function capitalize(text: string): string {\n return `${text.charAt(0).toUpperCase()}${text.slice(1)}`\n}\n\n/**\n * Converts `text` to snake_case.\n *\n * @example\n * `snakeCase('helloWorld') // 'hello_world'`\n */\nexport function snakeCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return words(`${prefix} ${text} ${suffix}`)\n .map((word) => word.replace(/[^a-zA-Z0-9]/g, '').toLowerCase())\n .filter(Boolean)\n .join('_')\n}\n\n/**\n * Converts `text` to SCREAMING_SNAKE_CASE.\n *\n * @example\n * `screamingSnakeCase('helloWorld') // 'HELLO_WORLD'`\n */\nexport function screamingSnakeCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return snakeCase(text, { prefix, suffix }).toUpperCase()\n}\n","import { existsSync, readFile, readFileSync, writeFile } from 'node:fs'\nimport { access, glob as globNode, mkdir } from 'node:fs/promises'\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\nexport { existsSync } from 'node:fs'\nexport { mkdir, mkdtemp, rm } from 'node:fs/promises'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n // The callback API skips the `FileHandle` every `fs/promises` call opens.\n return new Promise((resolvePromise, reject) => readFile(path, { encoding: 'utf8' }, (error, data) => (error ? reject(error) : resolvePromise(data))))\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string, or `null` when it does not exist or cannot be read.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFileSync` otherwise.\n *\n * @example\n * ```ts\n * const stored = await readIfExists('./src/gen/Pet.ts') // null on a first run\n * ```\n */\nexport async function readIfExists(path: string): Promise<string | null> {\n if (runtime.isBun) {\n return Bun.file(path)\n .text()\n .catch(() => null)\n }\n // A small read is faster on the main thread than a thread-pool round trip, and `existsSync`\n // answers a missing file without building an error.\n if (!existsSync(path)) return null\n try {\n return readFileSync(path, 'utf8')\n } catch (_error) {\n return null\n }\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n const stored = options.stored === undefined ? await readIfExists(resolved) : options.stored\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n await writeRaw(resolved, content)\n\n if (options.sanity) {\n const savedData = await read(resolved)\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Writes UTF-8 content verbatim, including empty files and surrounding whitespace.\n * Uses Bun.write under Bun and creates missing parent directories under either runtime.\n *\n * @example\n * await writeRaw('./cache/output.ts', ' // keep these bytes\\n\\n')\n */\nexport async function writeRaw(path: string, content: string): Promise<void> {\n const resolved = resolve(path)\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return\n }\n try {\n await new Promise<void>((resolvePromise, reject) =>\n writeFile(resolved, content, { encoding: 'utf-8' }, (error) => (error ? reject(error) : resolvePromise())),\n )\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await mkdir(dirname(resolved), { recursive: true })\n await new Promise<void>((resolvePromise, reject) =>\n writeFile(resolved, content, { encoding: 'utf-8' }, (error) => (error ? reject(error) : resolvePromise())),\n )\n }\n}\n\n/**\n * Lists non-hidden regular files below `directory` as relative POSIX paths, excluding directories and symlinks.\n * Uses Bun.Glob under Bun because its Node glob compatibility API lacks directory-entry support.\n *\n * @example\n * for await (const path of listFiles('./src')) console.log(path)\n */\nexport async function* listFiles(directory: string): AsyncGenerator<string> {\n const cwd = resolve(directory)\n if (runtime.isBun) {\n yield* new Bun.Glob('**/*').scan({ cwd, dot: false, onlyFiles: true, followSymlinks: false })\n return\n }\n for await (const entry of globNode('**/*', { cwd, withFileTypes: true })) {\n if (entry.isFile()) yield toPosixPath(relative(cwd, join(entry.parentPath, entry.name)))\n }\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","","","import { extname, posix } from 'node:path'\nimport { ast, Diagnostics } from '@kubb/kit'\nimport { memo, pascalCase, toPosixPath } from '@internals/utils'\nimport type { BarrelType } from './types.ts'\n\nconst SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\nconst BARREL_SUFFIX = `/index.ts`\n\n/**\n * A file (no `children`) or directory in the tree barrels are computed from. `path` is absolute and\n * POSIX-normalized, and a directory's `children` are keyed by entry name.\n */\ntype TreeNode = { path: string; children?: undefined } | DirectoryNode\ntype DirectoryNode = { path: string; children: Map<string, TreeNode> }\n\n/** A directory's children in name order, the way a directory listing sorts them. Every barrel of a build walks the same tree. */\nfunction sortedChildren(node: DirectoryNode): ReadonlyArray<TreeNode> {\n return memo(sortedChildrenCache, node, () => [...node.children.entries()].sort(([a], [b]) => (a < b ? -1 : 1)).map(([, child]) => child))\n}\n\nconst sortedChildrenCache = memo.create<DirectoryNode, ReadonlyArray<TreeNode>>({ weak: true })\n\n// An empty, `.` or `..` segment, which `posix.relative` would normalize away.\nconst UNNORMALIZED_SEGMENT = /(?:^|\\/)\\.{0,2}(?:\\/|$)/\n\nfunction toRelativeModulePath(fromDir: string, filePath: string): string {\n // Tree paths extend their parent's path with `/<name>`, so below `fromDir` the relative path is the rest of the path.\n const rest = filePath.startsWith(`${fromDir}/`) ? filePath.slice(fromDir.length + 1) : undefined\n if (rest && !UNNORMALIZED_SEGMENT.test(rest)) return `./${rest}`\n const relativePath = posix.relative(fromDir, filePath)\n return relativePath.startsWith('../') ? relativePath : `./${relativePath}`\n}\n\ntype WalkContext = {\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n barrelFiles: Map<string, ast.FileNode>\n reportedCollisions: Set<string>\n recursive: boolean\n namespace: boolean\n additionalExports: ReadonlyArray<ast.ExportNode>\n leafExports: (dirPath: string, leafPath: string) => Array<ast.ExportNode>\n}\n\nfunction getExportNames({ item, dirPath, ctx }: { item: ast.ExportNode; dirPath: string; ctx: WalkContext }): Array<string> {\n if (item.name != null) return [item.name].flat()\n\n const itemPath = posix.join(dirPath, item.path)\n const barrel = ctx.barrelFiles.get(itemPath)\n if (barrel) return barrel.exports.flatMap((item) => getExportNames({ item, dirPath: posix.dirname(barrel.path), ctx }))\n\n return ctx.sourceFiles.get(itemPath)?.sources.flatMap((source) => source.name || []) ?? []\n}\n\n/**\n * Builds the `index.ts` for `dirPath`. Keeps the first export of each name and reports later duplicates once per build.\n */\nfunction makeBarrel(dirPath: string, exports: Array<ast.ExportNode>, ctx: WalkContext): ast.FileNode {\n const { reportedCollisions } = ctx\n const owners = new Map<string, string>()\n const uniqueExports = exports.flatMap((item) => {\n const itemPath = posix.join(dirPath, item.path)\n // A wildcard export carries no names, so collisions are checked against its source file.\n const names = getExportNames({ item, dirPath, ctx })\n const uniqueNames = names.filter((name) => {\n const first = owners.get(name)\n if (!first) {\n owners.set(name, item.path)\n return true\n }\n\n const key = [name, posix.join(dirPath, first), itemPath].join('\\0')\n if (!reportedCollisions.has(key)) {\n reportedCollisions.add(key)\n Diagnostics.report({\n code: Diagnostics.code.barrelDuplicateExport,\n severity: 'error',\n message: `\"${name}\" is exported by both \"${first}\" and \"${item.path}\", so \"${dirPath}${BARREL_SUFFIX}\" cannot re-export both.`,\n help: 'Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names.',\n })\n }\n return false\n })\n\n if (item.name == null) return [item]\n return uniqueNames.length > 0 ? [ast.factory.createExport({ ...item, name: Array.isArray(item.name) ? uniqueNames : uniqueNames[0] })] : []\n })\n\n const file = ast.factory.createFile({ baseName: 'index.ts', path: `${dirPath}${BARREL_SUFFIX}`, exports: uniqueExports })\n ctx.barrelFiles.set(file.path, file)\n return file\n}\n\ntype LeafStrategy = (path: string, sourceFile: ast.FileNode | undefined) => Array<ast.ExportNode>\n\ntype LeafNames = { hasSources: boolean; hasIndexable: boolean; valueNames: Array<string>; typeNames: Array<string> }\n\n// A nested barrel asks for the same file's names once per ancestor folder; only the relative path differs.\nconst leafNamesCache = memo.create<ast.FileNode, LeafNames>({ weak: true })\n\nfunction getLeafNames(sourceFile: ast.FileNode): LeafNames {\n const { sources } = sourceFile\n return memo(leafNamesCache, sourceFile, () => ({\n hasSources: sources.length > 0,\n hasIndexable: sources.some((source) => source.isIndexable),\n valueNames: indexableNames(sources, false),\n typeNames: indexableNames(sources, true),\n }))\n}\n\nfunction indexableNames(sources: ReadonlyArray<ast.SourceNode>, isTypeOnly: boolean): Array<string> {\n const names = sources.flatMap((source) => (source.isIndexable && source.name && Boolean(source.isTypeOnly) === isTypeOnly ? [source.name] : []))\n return [...new Set(names)].sort()\n}\n\n/**\n * Re-exports the whole module, unless it has sources and none of them is indexable.\n */\nconst allStrategy: LeafStrategy = (path, sourceFile) => {\n const names = sourceFile && getLeafNames(sourceFile)\n return names?.hasSources && !names.hasIndexable ? [] : [ast.factory.createExport({ path })]\n}\n\n/**\n * Re-exports the indexable names, values and types separately, or the whole module when it has no sources.\n */\nconst namedStrategy: LeafStrategy = (path, sourceFile) => {\n const names = sourceFile && getLeafNames(sourceFile)\n if (!names?.hasSources) return [ast.factory.createExport({ path })]\n\n const { valueNames, typeNames } = names\n return [\n ...(valueNames.length > 0 ? [ast.factory.createExport({ name: valueNames, path })] : []),\n ...(typeNames.length > 0 ? [ast.factory.createExport({ name: typeNames, path, isTypeOnly: true })] : []),\n ]\n}\n\ntype FlatWalk = { barrels: Array<ast.FileNode>; leaves: Array<string> }\n\n/**\n * Post-order walk that builds a barrel re-exporting every leaf below the visited directory, for\n * the start node and, with `recursive`, every sub-directory. Also returns the subtree's leaf paths.\n */\nfunction walkFlat(node: DirectoryNode, ctx: WalkContext, isRoot = true): FlatWalk {\n const results = sortedChildren(node).map((child): FlatWalk => (child.children ? walkFlat(child, ctx, false) : { barrels: [], leaves: [child.path] }))\n const barrels = results.flatMap((result) => result.barrels)\n const leaves = results.flatMap((result) => result.leaves)\n const exports = isRoot || ctx.recursive ? leaves.flatMap((leaf) => ctx.leafExports(node.path, leaf)) : []\n if (isRoot) exports.push(...ctx.additionalExports)\n\n return { barrels: exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels, leaves }\n}\n\n/**\n * Recursive walk that builds one barrel per directory, re-exporting files and sub-barrels.\n * Used when nested: true. Leaf files honor the barrel `strategy`, so `named` emits explicit\n * named exports instead of wildcards. Sub-directory barrels are chained with a wildcard\n * re-export, which forwards the names the child barrel already curated. A sub-directory that\n * produced no barrel is never re-exported.\n */\nfunction walkNested(node: DirectoryNode, ctx: WalkContext): Array<ast.FileNode> {\n const results = sortedChildren(node).map((child) => {\n if (!child.children) return { barrels: [], exports: ctx.leafExports(node.path, child.path) }\n\n // A sub-directory has barrels only when it has its own `index.ts`.\n const barrels = walkNested(child, { ...ctx, namespace: false })\n if (barrels.length === 0) return { barrels, exports: [] }\n\n const modulePath = toRelativeModulePath(node.path, `${child.path}${BARREL_SUFFIX}`)\n const exports = [ast.factory.createExport({ path: modulePath })]\n const name = pascalCase(posix.basename(child.path))\n if (ctx.namespace) exports.push(ast.factory.createExport({ path: modulePath, name: /^[A-Za-z]/.test(name) ? name : `_${name}`, asAlias: true }))\n return { barrels, exports }\n })\n const barrels = results.flatMap((result) => result.barrels)\n const exports = results.flatMap((result) => result.exports)\n\n return exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels\n}\n\n/**\n * A directory tree plus the source-file lookup it was built from, scoped to a single output root.\n * Build it once with {@link buildBarrelIndex} and derive every barrel (per-plugin and root) from\n * it via {@link getBarrelFiles}, instead of re-scanning the full file set once per barrel.\n */\ntype BarrelIndex = {\n tree: DirectoryNode\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n}\n\n/**\n * Indexes `files` once for the directory rooted at `outputPath`: filters to indexable source\n * files under that path and builds their directory tree. Reuse the result across every barrel\n * derived from the same root rather than re-filtering and re-building per barrel.\n */\nexport function buildBarrelIndex({\n outputPath,\n files,\n sharedPath,\n}: {\n outputPath: string\n files: ReadonlyArray<ast.FileNode>\n sharedPath?: string\n}): BarrelIndex {\n const tree: DirectoryNode = { path: toPosixPath(outputPath), children: new Map() }\n // Files under `sharedPath` (the config's `shared.path`) join the tree at the same relative position; `outputPath` wins when both match.\n const roots = sharedPath ? [tree.path, toPosixPath(sharedPath)] : [tree.path]\n const rootOf = (filePath: string) => roots.find((root) => filePath.startsWith(`${root}/`))\n const sourceFiles = new Map(\n files.flatMap((file) => {\n const filePath = toPosixPath(file.path)\n const isSource = rootOf(filePath) !== undefined && !filePath.endsWith(BARREL_SUFFIX) && SOURCE_EXTENSIONS.has(extname(filePath))\n return isSource ? [[filePath, file] as const] : []\n }),\n )\n\n for (const filePath of sourceFiles.keys()) {\n const parts = filePath\n .slice(rootOf(filePath)!.length + 1)\n .split('/')\n .filter(Boolean)\n parts.reduce<DirectoryNode>((dir, part, i) => {\n const path = `${dir.path}/${part}`\n const child = memo(dir.children, part, (): TreeNode => (i === parts.length - 1 ? { path: filePath } : { path, children: new Map() }))\n return child.children ? child : dir\n }, tree)\n }\n\n return { tree, sourceFiles }\n}\n\n/**\n * Locates the directory node for `targetPath` within an index tree. Returns `undefined` when no\n * file exists under `targetPath` (nothing to barrel).\n */\nfunction findDirectory(tree: DirectoryNode, targetPath: string): DirectoryNode | undefined {\n if (targetPath === tree.path) return tree\n if (!targetPath.startsWith(`${tree.path}/`)) return undefined\n\n const node = targetPath\n .slice(tree.path.length + 1)\n .split('/')\n .reduce<TreeNode | undefined>((current, part) => current?.children?.get(part), tree)\n return node?.children ? node : undefined\n}\n\ntype GetBarrelFilesParams = {\n /**\n * Index built once via {@link buildBarrelIndex} for the shared output root.\n */\n index: BarrelIndex\n /** Absolute directory to root the barrel(s) at, a subtree of the index root. Defaults to the index root. */\n targetPath?: string\n /** `'all'` re-exports whole modules (`export * from './x'`), `'named'` only the indexable named symbols. */\n barrelType: BarrelType\n /** One `index.ts` per sub-directory, each re-exporting only what is directly inside it. */\n nested?: boolean\n /** Add PascalCase namespace exports for immediate subdirectories and enable nested barrels. */\n namespace?: boolean\n /** Extra exports to forward from plugin barrels into the root barrel. */\n additionalExports?: ReadonlyArray<ast.ExportNode>\n /** Also generate a barrel for each sub-directory when `nested` is false. */\n recursive?: boolean\n /**\n * Collision identities reported by related barrel generations in the same build.\n */\n reportedCollisions?: Set<string>\n}\n\n/**\n * Returns the barrel `ast.FileNode`s for `targetPath` (or the index root), derived from a shared index.\n * Locating the subtree is a bounded walk down from the root, so deriving many barrels (one per\n * plugin, plus the root) from one index avoids re-scanning the full file set for each.\n *\n * @example\n * ```ts\n * const index = buildBarrelIndex({ outputPath, files })\n * getBarrelFiles({ index, targetPath, barrelType }).forEach((file) => upsertFile(file))\n * ```\n */\nexport function getBarrelFiles({\n index,\n targetPath,\n barrelType,\n nested = false,\n namespace = false,\n additionalExports = [],\n recursive = false,\n reportedCollisions = new Set(),\n}: GetBarrelFilesParams): Array<ast.FileNode> {\n const node = targetPath ? findDirectory(index.tree, toPosixPath(targetPath)) : index.tree\n if (!node) return []\n\n const strategy = barrelType === 'named' ? namedStrategy : allStrategy\n const ctx: WalkContext = {\n sourceFiles: index.sourceFiles,\n barrelFiles: new Map(),\n reportedCollisions,\n recursive,\n namespace,\n additionalExports,\n leafExports: (dirPath, leafPath) => strategy(toRelativeModulePath(dirPath, leafPath), index.sourceFiles.get(leafPath)),\n }\n\n return nested || namespace ? walkNested(node, ctx) : walkFlat(node, ctx).barrels\n}\n","import path from 'node:path'\nimport { isPathInside, memo, toPosixPath } from '@internals/utils'\nimport { ast, defineExtension, Diagnostics } from '@kubb/kit'\nimport type { Config, NormalizedPlugin, Plugin } from '@kubb/kit'\nimport { compatibility } from '../kubb-extension.json'\nimport { version } from '../package.json'\nimport type { BarrelType, PluginBarrelConfig } from './types.ts'\nimport { buildBarrelIndex, getBarrelFiles } from './utils.ts'\n\n/**\n * Applies a plugin's configured `output.banner`/`footer` to a barrel file, flagged as `isBarrel`.\n *\n * Resolves through the plugin's own resolver, and only when the plugin explicitly sets a\n * banner/footer, so barrels stay banner-free by default and never inherit the implicit\n * \"Generated by Kubb\" notice.\n */\nfunction withBarrelBannerFooter({ file, plugin, config }: { file: ast.FileNode; plugin: NormalizedPlugin; config: Config }): ast.FileNode {\n const output = plugin.options?.output\n const resolver = plugin.resolver\n const hasBanner = output?.banner !== undefined\n const hasFooter = output?.footer !== undefined\n if (!resolver || (!hasBanner && !hasFooter)) return file\n\n const context = { output, config, file: { path: file.path, baseName: file.baseName, isBarrel: true } }\n return {\n ...file,\n banner: hasBanner ? resolver.default.banner(undefined, context) : file.banner,\n footer: hasFooter ? resolver.default.footer(undefined, context) : file.footer,\n }\n}\n\n/**\n * Canonical plugin name for `@kubb/plugin-barrel`. Used for driver lookups\n * and to guard the `kubb:plugin:end` handler against reacting to its own lifecycle hook.\n */\nexport const pluginBarrelName = 'plugin-barrel' satisfies Plugin['name']\n\ntype PendingBarrel = {\n plugin: NormalizedPlugin\n target: string\n barrelType: BarrelType\n nested: boolean\n namespace: boolean\n}\n\ntype BarrelState = {\n excludedPlugins: Set<string>\n // Subdirectories of `barrel: false` plugins, for files without a `meta.pluginName` owner.\n excludedTargets: Array<string>\n pendingBarrels: Array<PendingBarrel>\n}\n\n// One state per build, keyed by the build's `config`. The object form has no factory closure to hold it.\nconst states = memo.create<Config, BarrelState>({ weak: true })\n\nfunction getState(config: Config): BarrelState {\n return memo(states, config, () => ({ excludedPlugins: new Set(), excludedTargets: [], pendingBarrels: [] }))\n}\n\n/**\n * Generates an `index.ts` for every plugin output directory and one root\n * barrel at `config.output.path/index.ts` after the build completes. Ships\n * with Kubb and is registered by default in `defineConfig`.\n *\n * A plugin without its own `output.barrel` inherits `config.output.barrel`\n * (which defaults to `false`, no root barrel). The default `output` of most\n * plugins carries `barrel: { type: 'named' }`, so they get a barrel unless you\n * pass your own `output` without one. Set `barrel: { type: 'named' | 'all' }` on\n * the root config, a plugin, or both to opt in; a plugin-level `false`\n * overrides an enabled root barrel and also excludes that plugin's files\n * from the root barrel.\n *\n * A plugin with `output.mode: 'file'` gets no per-plugin barrel, since its output\n * is a single file. The root barrel re-exports that file directly.\n *\n * @example\n * ```ts\n * import { defineConfig } from '@kubb/core'\n * import { pluginBarrel } from '@kubb/plugin-barrel'\n * import { pluginTs } from '@kubb/plugin-ts'\n * import { pluginZod } from '@kubb/plugin-zod'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: 'src/gen', barrel: { type: 'named' } },\n * plugins: [\n * pluginTs({ output: { path: 'types', barrel: { type: 'all' } } }),\n * pluginZod({ output: { path: 'schemas' } }),\n * pluginBarrel(),\n * ],\n * })\n * ```\n */\nexport const pluginBarrel = defineExtension({\n kind: 'plugin',\n meta: { name: pluginBarrelName, version, compatibility, issues: 'https://github.com/kubb-labs/kubb/issues' },\n enforce: 'post',\n hooks: {\n 'kubb:plugin:end'({ plugin, config }) {\n // Skip reactions to the barrel plugin's own lifecycle hook\n if (plugin.name === pluginBarrelName) return\n\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n\n // A plugin-level `false` wins over an enabled root barrel.\n const barrelConfig: PluginBarrelConfig | false = plugin.options.output?.barrel ?? config.output.barrel ?? false\n const base = path.resolve(config.root, config.output.path)\n const target = path.resolve(base, plugin.options.output.path ?? '.')\n\n if (barrelConfig === false) {\n excludedPlugins.add(plugin.name)\n // The output root holds every plugin's files, so there only the owner match applies.\n if (target !== base && isPathInside(target, base)) {\n excludedTargets.push(target)\n }\n return\n }\n\n // A plugin at the output root (no own `output.path`) gets no per-plugin barrel, which would\n // claim every other plugin's directory. The root barrel picks up its files.\n if (target === base) {\n if (barrelConfig.namespace) {\n Diagnostics.report({\n code: Diagnostics.code.pluginWarning,\n severity: 'warning',\n message: `Plugin \"${plugin.name}\" sets \\`output.barrel.namespace\\` but writes to the output root, so no namespaces are generated.`,\n help: 'Give the plugin its own `output.path`, such as `client`.',\n })\n }\n return\n }\n\n // `mode: 'file'` writes a single file, so there is no directory to barrel. The root barrel\n // re-exports that file as a direct leaf of `config.output.path`.\n if (plugin.options.output.mode === 'file') {\n return\n }\n\n if (!isPathInside(target, base)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.pathTraversal,\n severity: 'error',\n message: `Output path \"${plugin.options.output.path}\" of plugin \"${plugin.name}\" resolves outside the output directory \"${base}\".`,\n help: 'Keep the plugin `output.path` within `config.output.path`.',\n location: { kind: 'config' },\n })\n }\n\n // Only the target directory and barrel strategy are recorded here. The actual file-set\n // scan and directory-tree build happen once, in `kubb:plugins:end`, and are shared by\n // every plugin barrel plus the root barrel instead of repeating per plugin.\n pendingBarrels.push({ plugin, target, barrelType: barrelConfig.type, nested: barrelConfig.nested ?? false, namespace: barrelConfig.namespace ?? false })\n },\n 'kubb:plugins:end'({ files, config, upsertFile }) {\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n const rootBarrelConfig = config.output.barrel ?? false\n const outputPath = path.resolve(config.root, config.output.path)\n\n // A `barrel: false` plugin gets no barrel and stays out of the root, so drop its files\n // once here. Every barrel below then derives from a single index of what remains.\n const relevantFiles = files.filter((file) => {\n const owner = (file.meta as { pluginName?: string } | undefined)?.pluginName\n if (owner) return !excludedPlugins.has(owner)\n\n return !excludedTargets.some((target) => isPathInside(file.path, target))\n })\n excludedPlugins.clear()\n excludedTargets.length = 0\n\n // Each config's barrels re-export the shared schemas it defines. The shared directory gets none, since each config writes only part of it.\n const index = buildBarrelIndex({\n outputPath,\n files: relevantFiles,\n sharedPath: config.shared && path.resolve(config.root, config.shared.path),\n })\n const reportedCollisions = new Set<string>()\n // Keyed by path and name: plugins sharing an `output.path` produce the same aliases.\n const namespaceExports = new Map<string, ast.ExportNode>()\n\n pendingBarrels.forEach(({ plugin, target, barrelType, nested, namespace }) => {\n getBarrelFiles({ index, targetPath: target, barrelType, nested, namespace, recursive: true, reportedCollisions }).forEach((file) => {\n upsertFile(withBarrelBannerFooter({ file, plugin, config }))\n if (file.path !== `${toPosixPath(target)}/index.ts`) return\n file.exports\n .filter((item) => item.asAlias)\n .forEach((item) => {\n const itemPath = `./${toPosixPath(path.relative(outputPath, path.resolve(target, item.path)))}`\n namespaceExports.set(`${itemPath}\\0${item.name}`, ast.factory.createExport({ ...item, path: itemPath }))\n })\n })\n })\n pendingBarrels.length = 0\n\n if (rootBarrelConfig === false) return\n\n getBarrelFiles({ index, barrelType: rootBarrelConfig.type, additionalExports: [...namespaceExports.values()], reportedCollisions }).forEach((file) => {\n upsertFile(file)\n })\n },\n },\n})\n"],"mappings":";;;;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als/utils/src/promise.ts","../../../internals/utils/src/fs.ts","../kubb-extension.json","../package.json","../src/utils.ts","../src/plugin.ts"],"sourcesContent":["/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Returns the value cached under `key` in `store`, computing and storing it on the first call.\n * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive\n * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.\n *\n * @example\n * `const refs = memo(refCache, node, () => collectRefs(node))`\n */\nexport function memo<TKey, TValue>(store: Store<TKey, TValue>, key: TKey, compute: () => TValue): TValue {\n const cached = store.get(key)\n if (cached !== undefined || store.has(key)) return cached as TValue\n const value = compute()\n store.set(key, value)\n return value\n}\n\n/**\n * Creates a store for `memo`. With no options it is a `Map`. Each option changes one thing:\n *\n * - `weak` holds the keys weakly, in a `WeakMap`, so an entry goes away with its key.\n * - `max` bounds the store: it empties itself before the entry that would pass `max`, which keeps a\n * cache in a long-running process from growing without end. `max: 1` keeps only the last entry.\n *\n * @example\n * `const patterns = memo.create<string, RegExp>()`\n *\n * @example Freed with its key\n * `const refs = memo.create<SchemaNode, Array<string>>({ weak: true })`\n *\n * @example Bounded\n * `const names = memo.create<string, string>({ max: 100_000 })`\n *\n * @example Many values per key\n * ```ts\n * const filesByPlugin = memo.create<string, Array<string>>()\n * memo(filesByPlugin, 'plugin-ts', () => []).push('models.ts')\n * ```\n */\nfunction createStore<TKey, TValue>(options?: { weak?: false; max?: undefined }): Map<TKey, TValue>\nfunction createStore<TKey extends WeakKey, TValue>(options: { weak: true; max?: undefined }): WeakMap<TKey, TValue>\nfunction createStore<TKey, TValue>(options: { max: number; weak?: false }): Store<TKey, TValue>\nfunction createStore<TKey, TValue>({ weak, max }: { weak?: boolean; max?: number } = {}): Store<TKey, TValue> {\n if (weak) return new WeakMap<WeakKey, TValue>() as Store<TKey, TValue>\n const entry = new Map<TKey, TValue>()\n if (max === undefined) return entry\n const set = (key: TKey, value: TValue) => {\n if (entry.size >= max) entry.clear()\n entry.set(key, value)\n }\n if (max !== 1) return { has: (key) => entry.has(key), get: (key) => entry.get(key), set }\n // A key equal to the stored one but a different object, such as a copy of a string, replaces the\n // stored key, so the next lookup is an identity hit instead of a full comparison.\n const touch = (key: TKey) => {\n if (!entry.has(key)) return false\n set(key, entry.get(key) as TValue)\n return true\n }\n return { has: touch, get: (key) => (touch(key) ? entry.get(key) : undefined), set }\n}\n\nmemo.create = createStore\n\ntype ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","import { existsSync, readFile, readFileSync, writeFile } from 'node:fs'\nimport { access, glob as globNode, mkdir } from 'node:fs/promises'\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\nexport { existsSync } from 'node:fs'\nexport { mkdir, mkdtemp, rm } from 'node:fs/promises'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n // The callback API skips the `FileHandle` every `fs/promises` call opens.\n return new Promise((resolvePromise, reject) => readFile(path, { encoding: 'utf8' }, (error, data) => (error ? reject(error) : resolvePromise(data))))\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string, or `null` when it does not exist or cannot be read.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFileSync` otherwise.\n *\n * @example\n * ```ts\n * const stored = await readIfExists('./src/gen/Pet.ts') // null on a first run\n * ```\n */\nexport async function readIfExists(path: string): Promise<string | null> {\n if (runtime.isBun) {\n return Bun.file(path)\n .text()\n .catch(() => null)\n }\n // A small read is faster on the main thread than a thread-pool round trip, and `existsSync`\n // answers a missing file without building an error.\n if (!existsSync(path)) return null\n try {\n return readFileSync(path, 'utf8')\n } catch (_error) {\n return null\n }\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n const stored = options.stored === undefined ? await readIfExists(resolved) : options.stored\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n await writeRaw(resolved, content)\n\n if (options.sanity) {\n const savedData = await read(resolved)\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Writes UTF-8 content verbatim, including empty files and surrounding whitespace.\n * Uses Bun.write under Bun and creates missing parent directories under either runtime.\n *\n * @example\n * await writeRaw('./cache/output.ts', ' // keep these bytes\\n\\n')\n */\nexport async function writeRaw(path: string, content: string): Promise<void> {\n const resolved = resolve(path)\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return\n }\n try {\n await new Promise<void>((resolvePromise, reject) =>\n writeFile(resolved, content, { encoding: 'utf-8' }, (error) => (error ? reject(error) : resolvePromise())),\n )\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await mkdir(dirname(resolved), { recursive: true })\n await new Promise<void>((resolvePromise, reject) =>\n writeFile(resolved, content, { encoding: 'utf-8' }, (error) => (error ? reject(error) : resolvePromise())),\n )\n }\n}\n\n/**\n * Lists non-hidden regular files below `directory` as relative POSIX paths, excluding directories and symlinks.\n * Uses Bun.Glob under Bun because its Node glob compatibility API lacks directory-entry support.\n *\n * @example\n * for await (const path of listFiles('./src')) console.log(path)\n */\nexport async function* listFiles(directory: string): AsyncGenerator<string> {\n const cwd = resolve(directory)\n if (runtime.isBun) {\n yield* new Bun.Glob('**/*').scan({ cwd, dot: false, onlyFiles: true, followSymlinks: false })\n return\n }\n for await (const entry of globNode('**/*', { cwd, withFileTypes: true })) {\n if (entry.isFile()) yield toPosixPath(relative(cwd, join(entry.parentPath, entry.name)))\n }\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","","","import { extname, posix } from 'node:path'\nimport { ast, casing, Diagnostics } from '@kubb/kit'\nimport { memo, toPosixPath } from '@internals/utils'\nimport type { BarrelType } from './types.ts'\n\nconst SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\nconst BARREL_SUFFIX = `/index.ts`\n\n/**\n * A file (no `children`) or directory in the tree barrels are computed from. `path` is absolute and\n * POSIX-normalized, and a directory's `children` are keyed by entry name.\n */\ntype TreeNode = { path: string; children?: undefined } | DirectoryNode\ntype DirectoryNode = { path: string; children: Map<string, TreeNode> }\n\n/** A directory's children in name order, the way a directory listing sorts them. Every barrel of a build walks the same tree. */\nfunction sortedChildren(node: DirectoryNode): ReadonlyArray<TreeNode> {\n return memo(sortedChildrenCache, node, () => [...node.children.entries()].sort(([a], [b]) => (a < b ? -1 : 1)).map(([, child]) => child))\n}\n\nconst sortedChildrenCache = memo.create<DirectoryNode, ReadonlyArray<TreeNode>>({ weak: true })\n\n// An empty, `.` or `..` segment, which `posix.relative` would normalize away.\nconst UNNORMALIZED_SEGMENT = /(?:^|\\/)\\.{0,2}(?:\\/|$)/\n\nfunction toRelativeModulePath(fromDir: string, filePath: string): string {\n // Tree paths extend their parent's path with `/<name>`, so below `fromDir` the relative path is the rest of the path.\n const rest = filePath.startsWith(`${fromDir}/`) ? filePath.slice(fromDir.length + 1) : undefined\n if (rest && !UNNORMALIZED_SEGMENT.test(rest)) return `./${rest}`\n const relativePath = posix.relative(fromDir, filePath)\n return relativePath.startsWith('../') ? relativePath : `./${relativePath}`\n}\n\ntype WalkContext = {\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n barrelFiles: Map<string, ast.FileNode>\n reportedCollisions: Set<string>\n recursive: boolean\n namespace: boolean\n additionalExports: ReadonlyArray<ast.ExportNode>\n leafExports: (dirPath: string, leafPath: string) => Array<ast.ExportNode>\n}\n\nfunction getExportNames({ item, dirPath, ctx }: { item: ast.ExportNode; dirPath: string; ctx: WalkContext }): Array<string> {\n if (item.name != null) return [item.name].flat()\n\n const itemPath = posix.join(dirPath, item.path)\n const barrel = ctx.barrelFiles.get(itemPath)\n if (barrel) return barrel.exports.flatMap((item) => getExportNames({ item, dirPath: posix.dirname(barrel.path), ctx }))\n\n return ctx.sourceFiles.get(itemPath)?.sources.flatMap((source) => source.name || []) ?? []\n}\n\n/**\n * Builds the `index.ts` for `dirPath`. Keeps the first export of each name and reports later duplicates once per build.\n */\nfunction makeBarrel(dirPath: string, exports: Array<ast.ExportNode>, ctx: WalkContext): ast.FileNode {\n const { reportedCollisions } = ctx\n const owners = new Map<string, string>()\n const uniqueExports = exports.flatMap((item) => {\n const itemPath = posix.join(dirPath, item.path)\n // A wildcard export carries no names, so collisions are checked against its source file.\n const names = getExportNames({ item, dirPath, ctx })\n const uniqueNames = names.filter((name) => {\n const first = owners.get(name)\n if (!first) {\n owners.set(name, item.path)\n return true\n }\n\n const key = [name, posix.join(dirPath, first), itemPath].join('\\0')\n if (!reportedCollisions.has(key)) {\n reportedCollisions.add(key)\n Diagnostics.report({\n code: Diagnostics.code.barrelDuplicateExport,\n severity: 'error',\n message: `\"${name}\" is exported by both \"${first}\" and \"${item.path}\", so \"${dirPath}${BARREL_SUFFIX}\" cannot re-export both.`,\n help: 'Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names.',\n })\n }\n return false\n })\n\n if (item.name == null) return [item]\n return uniqueNames.length > 0 ? [ast.factory.createExport({ ...item, name: Array.isArray(item.name) ? uniqueNames : uniqueNames[0] })] : []\n })\n\n const file = ast.factory.createFile({ baseName: 'index.ts', path: `${dirPath}${BARREL_SUFFIX}`, exports: uniqueExports })\n ctx.barrelFiles.set(file.path, file)\n return file\n}\n\ntype LeafStrategy = (path: string, sourceFile: ast.FileNode | undefined) => Array<ast.ExportNode>\n\ntype LeafNames = { hasSources: boolean; hasExported: boolean; valueNames: Array<string>; typeNames: Array<string> }\n\n// A nested barrel asks for the same file's names once per ancestor folder; only the relative path differs.\nconst leafNamesCache = memo.create<ast.FileNode, LeafNames>({ weak: true })\n\nfunction getLeafNames(sourceFile: ast.FileNode): LeafNames {\n const { sources } = sourceFile\n return memo(leafNamesCache, sourceFile, () => ({\n hasSources: sources.length > 0,\n hasExported: sources.some(isExported),\n valueNames: exportedNames(sources, false),\n typeNames: exportedNames(sources, true),\n }))\n}\n\n// `isIndexable` is the deprecated spelling of `export`. A default export can't be re-exported by name.\nconst isExported = (source: ast.SourceNode): boolean => !source.default && !!(source.export ?? source.isIndexable)\n\nfunction exportedNames(sources: ReadonlyArray<ast.SourceNode>, isTypeOnly: boolean): Array<string> {\n const names = sources.flatMap((source) => (isExported(source) && source.name && Boolean(source.isTypeOnly) === isTypeOnly ? [source.name] : []))\n return [...new Set(names)].sort()\n}\n\n/**\n * Re-exports the whole module, unless it has sources and none of them is exported.\n */\nconst allStrategy: LeafStrategy = (path, sourceFile) => {\n const names = sourceFile && getLeafNames(sourceFile)\n return names?.hasSources && !names.hasExported ? [] : [ast.factory.createExport({ path })]\n}\n\n/**\n * Re-exports the indexable names, values and types separately, or the whole module when it has no sources.\n */\nconst namedStrategy: LeafStrategy = (path, sourceFile) => {\n const names = sourceFile && getLeafNames(sourceFile)\n if (!names?.hasSources) return [ast.factory.createExport({ path })]\n\n const { valueNames, typeNames } = names\n return [\n ...(valueNames.length > 0 ? [ast.factory.createExport({ name: valueNames, path })] : []),\n ...(typeNames.length > 0 ? [ast.factory.createExport({ name: typeNames, path, isTypeOnly: true })] : []),\n ]\n}\n\ntype FlatWalk = { barrels: Array<ast.FileNode>; leaves: Array<string> }\n\n/**\n * Post-order walk that builds a barrel re-exporting every leaf below the visited directory, for\n * the start node and, with `recursive`, every sub-directory. Also returns the subtree's leaf paths.\n */\nfunction walkFlat(node: DirectoryNode, ctx: WalkContext, isRoot = true): FlatWalk {\n const results = sortedChildren(node).map((child): FlatWalk => (child.children ? walkFlat(child, ctx, false) : { barrels: [], leaves: [child.path] }))\n const barrels = results.flatMap((result) => result.barrels)\n const leaves = results.flatMap((result) => result.leaves)\n const exports = isRoot || ctx.recursive ? leaves.flatMap((leaf) => ctx.leafExports(node.path, leaf)) : []\n if (isRoot) exports.push(...ctx.additionalExports)\n\n return { barrels: exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels, leaves }\n}\n\n/**\n * Recursive walk that builds one barrel per directory, re-exporting files and sub-barrels.\n * Used when nested: true. Leaf files honor the barrel `strategy`, so `named` emits explicit\n * named exports instead of wildcards. Sub-directory barrels are chained with a wildcard\n * re-export, which forwards the names the child barrel already curated. A sub-directory that\n * produced no barrel is never re-exported.\n */\nfunction walkNested(node: DirectoryNode, ctx: WalkContext): Array<ast.FileNode> {\n const results = sortedChildren(node).map((child) => {\n if (!child.children) return { barrels: [], exports: ctx.leafExports(node.path, child.path) }\n\n // A sub-directory has barrels only when it has its own `index.ts`.\n const barrels = walkNested(child, { ...ctx, namespace: false })\n if (barrels.length === 0) return { barrels, exports: [] }\n\n const modulePath = toRelativeModulePath(node.path, `${child.path}${BARREL_SUFFIX}`)\n const exports = [ast.factory.createExport({ path: modulePath })]\n const name = casing.pascal(posix.basename(child.path))\n if (ctx.namespace) exports.push(ast.factory.createExport({ path: modulePath, name: /^[A-Za-z]/.test(name) ? name : `_${name}`, asAlias: true }))\n return { barrels, exports }\n })\n const barrels = results.flatMap((result) => result.barrels)\n const exports = results.flatMap((result) => result.exports)\n\n return exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels\n}\n\n/**\n * A directory tree plus the source-file lookup it was built from, scoped to a single output root.\n * Build it once with {@link buildBarrelIndex} and derive every barrel (per-plugin and root) from\n * it via {@link getBarrelFiles}, instead of re-scanning the full file set once per barrel.\n */\ntype BarrelIndex = {\n tree: DirectoryNode\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n}\n\n/**\n * Indexes `files` once for the directory rooted at `outputPath`: filters to indexable source\n * files under that path and builds their directory tree. Reuse the result across every barrel\n * derived from the same root rather than re-filtering and re-building per barrel.\n */\nexport function buildBarrelIndex({\n outputPath,\n files,\n sharedPath,\n}: {\n outputPath: string\n files: ReadonlyArray<ast.FileNode>\n sharedPath?: string\n}): BarrelIndex {\n const tree: DirectoryNode = { path: toPosixPath(outputPath), children: new Map() }\n // Files under `sharedPath` (the config's `shared.path`) join the tree at the same relative position; `outputPath` wins when both match.\n const roots = sharedPath ? [tree.path, toPosixPath(sharedPath)] : [tree.path]\n const rootOf = (filePath: string) => roots.find((root) => filePath.startsWith(`${root}/`))\n const sourceFiles = new Map(\n files.flatMap((file) => {\n const filePath = toPosixPath(file.path)\n const isSource = rootOf(filePath) !== undefined && !filePath.endsWith(BARREL_SUFFIX) && SOURCE_EXTENSIONS.has(extname(filePath))\n return isSource ? [[filePath, file] as const] : []\n }),\n )\n\n for (const filePath of sourceFiles.keys()) {\n const parts = filePath\n .slice(rootOf(filePath)!.length + 1)\n .split('/')\n .filter(Boolean)\n parts.reduce<DirectoryNode>((dir, part, i) => {\n const path = `${dir.path}/${part}`\n const child = memo(dir.children, part, (): TreeNode => (i === parts.length - 1 ? { path: filePath } : { path, children: new Map() }))\n return child.children ? child : dir\n }, tree)\n }\n\n return { tree, sourceFiles }\n}\n\n/**\n * Locates the directory node for `targetPath` within an index tree. Returns `undefined` when no\n * file exists under `targetPath` (nothing to barrel).\n */\nfunction findDirectory(tree: DirectoryNode, targetPath: string): DirectoryNode | undefined {\n if (targetPath === tree.path) return tree\n if (!targetPath.startsWith(`${tree.path}/`)) return undefined\n\n const node = targetPath\n .slice(tree.path.length + 1)\n .split('/')\n .reduce<TreeNode | undefined>((current, part) => current?.children?.get(part), tree)\n return node?.children ? node : undefined\n}\n\ntype GetBarrelFilesParams = {\n /**\n * Index built once via {@link buildBarrelIndex} for the shared output root.\n */\n index: BarrelIndex\n /** Absolute directory to root the barrel(s) at, a subtree of the index root. Defaults to the index root. */\n targetPath?: string\n /** `'all'` re-exports whole modules (`export * from './x'`), `'named'` only the indexable named symbols. */\n barrelType: BarrelType\n /** One `index.ts` per sub-directory, each re-exporting only what is directly inside it. */\n nested?: boolean\n /** Add PascalCase namespace exports for immediate subdirectories and enable nested barrels. */\n namespace?: boolean\n /** Extra exports to forward from plugin barrels into the root barrel. */\n additionalExports?: ReadonlyArray<ast.ExportNode>\n /** Also generate a barrel for each sub-directory when `nested` is false. */\n recursive?: boolean\n /**\n * Collision identities reported by related barrel generations in the same build.\n */\n reportedCollisions?: Set<string>\n}\n\n/**\n * Returns the barrel `ast.FileNode`s for `targetPath` (or the index root), derived from a shared index.\n * Locating the subtree is a bounded walk down from the root, so deriving many barrels (one per\n * plugin, plus the root) from one index avoids re-scanning the full file set for each.\n *\n * @example\n * ```ts\n * const index = buildBarrelIndex({ outputPath, files })\n * getBarrelFiles({ index, targetPath, barrelType }).forEach((file) => upsertFile(file))\n * ```\n */\nexport function getBarrelFiles({\n index,\n targetPath,\n barrelType,\n nested = false,\n namespace = false,\n additionalExports = [],\n recursive = false,\n reportedCollisions = new Set(),\n}: GetBarrelFilesParams): Array<ast.FileNode> {\n const node = targetPath ? findDirectory(index.tree, toPosixPath(targetPath)) : index.tree\n if (!node) return []\n\n const strategy = barrelType === 'named' ? namedStrategy : allStrategy\n const ctx: WalkContext = {\n sourceFiles: index.sourceFiles,\n barrelFiles: new Map(),\n reportedCollisions,\n recursive,\n namespace,\n additionalExports,\n leafExports: (dirPath, leafPath) => strategy(toRelativeModulePath(dirPath, leafPath), index.sourceFiles.get(leafPath)),\n }\n\n return nested || namespace ? walkNested(node, ctx) : walkFlat(node, ctx).barrels\n}\n","import path from 'node:path'\nimport { isPathInside, memo, toPosixPath } from '@internals/utils'\nimport { ast, defineExtension, Diagnostics, getResolver } from '@kubb/kit'\nimport type { Config, NormalizedPlugin, Plugin } from '@kubb/kit'\nimport { compatibility } from '../kubb-extension.json'\nimport { version } from '../package.json'\nimport type { BarrelType, PluginBarrelConfig } from './types.ts'\nimport { buildBarrelIndex, getBarrelFiles } from './utils.ts'\n\n/**\n * Applies a plugin's configured `output.banner`/`footer` to a barrel file, flagged as `isBarrel`.\n *\n * Resolves through the plugin's resolver from the running hook's build memo, and only when the plugin explicitly\n * sets a banner/footer, so barrels stay banner-free by default and never inherit the implicit\n * \"Generated by Kubb\" notice.\n */\nfunction withBarrelBannerFooter({ file, plugin, config }: { file: ast.FileNode; plugin: NormalizedPlugin; config: Config }): ast.FileNode {\n const output = plugin.options?.output\n const hasBanner = output?.banner !== undefined\n const hasFooter = output?.footer !== undefined\n if (!hasBanner && !hasFooter) return file\n\n const resolver = getResolver(plugin.name)\n\n const context = { output, config, file: { path: file.path, baseName: file.baseName, isBarrel: true } }\n return {\n ...file,\n banner: hasBanner ? resolver.default.banner(undefined, context) : file.banner,\n footer: hasFooter ? resolver.default.footer(undefined, context) : file.footer,\n }\n}\n\n/**\n * Canonical plugin name for `@kubb/plugin-barrel`. Used for driver lookups\n * and to guard the `kubb:plugin:end` handler against reacting to its own lifecycle hook.\n */\nexport const pluginBarrelName = 'plugin-barrel' satisfies Plugin['name']\n\ntype PendingBarrel = {\n plugin: NormalizedPlugin\n target: string\n barrelType: BarrelType\n nested: boolean\n namespace: boolean\n}\n\ntype BarrelState = {\n excludedPlugins: Set<string>\n // Subdirectories of `barrel: false` plugins, for files without a `meta.pluginName` owner.\n excludedTargets: Array<string>\n pendingBarrels: Array<PendingBarrel>\n}\n\n// One state per build, keyed by the build's `config`. The object form has no factory closure to hold it.\nconst states = memo.create<Config, BarrelState>({ weak: true })\n\nfunction getState(config: Config): BarrelState {\n return memo(states, config, () => ({ excludedPlugins: new Set(), excludedTargets: [], pendingBarrels: [] }))\n}\n\n/**\n * Generates an `index.ts` for every plugin output directory and one root\n * barrel at `config.output.path/index.ts` after the build completes. Ships\n * with Kubb and is registered by default in `defineConfig`.\n *\n * A plugin without its own `output.barrel` inherits `config.output.barrel`\n * (which defaults to `false`, no root barrel). The default `output` of most\n * plugins carries `barrel: { type: 'named' }`, so they get a barrel unless you\n * pass your own `output` without one. Set `barrel: { type: 'named' | 'all' }` on\n * the root config, a plugin, or both to opt in; a plugin-level `false`\n * overrides an enabled root barrel and also excludes that plugin's files\n * from the root barrel.\n *\n * A plugin with `output.mode: 'file'` gets no per-plugin barrel, since its output\n * is a single file. The root barrel re-exports that file directly.\n *\n * @example\n * ```ts\n * import { defineConfig } from '@kubb/core'\n * import { pluginBarrel } from '@kubb/plugin-barrel'\n * import { pluginTs } from '@kubb/plugin-ts'\n * import { pluginZod } from '@kubb/plugin-zod'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: 'src/gen', barrel: { type: 'named' } },\n * plugins: [\n * pluginTs({ output: { path: 'types', barrel: { type: 'all' } } }),\n * pluginZod({ output: { path: 'schemas' } }),\n * pluginBarrel(),\n * ],\n * })\n * ```\n */\nexport const pluginBarrel = defineExtension({\n kind: 'plugin',\n meta: { name: pluginBarrelName, version, compatibility, issues: 'https://github.com/kubb-labs/kubb/issues' },\n enforce: 'post',\n hooks: {\n 'kubb:plugin:end'({ plugin, config }) {\n // Skip reactions to the barrel plugin's own lifecycle hook\n if (plugin.name === pluginBarrelName) return\n\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n\n // A plugin-level `false` wins over an enabled root barrel.\n const barrelConfig: PluginBarrelConfig | false = plugin.options.output?.barrel ?? config.output.barrel ?? false\n const base = path.resolve(config.root, config.output.path)\n const target = path.resolve(base, plugin.options.output.path ?? '.')\n\n if (barrelConfig === false) {\n excludedPlugins.add(plugin.name)\n // The output root holds every plugin's files, so there only the owner match applies.\n if (target !== base && isPathInside(target, base)) {\n excludedTargets.push(target)\n }\n return\n }\n\n // A plugin at the output root (no own `output.path`) gets no per-plugin barrel, which would\n // claim every other plugin's directory. The root barrel picks up its files.\n if (target === base) {\n if (barrelConfig.namespace) {\n Diagnostics.report({\n code: Diagnostics.code.pluginWarning,\n severity: 'warning',\n message: `Plugin \"${plugin.name}\" sets \\`output.barrel.namespace\\` but writes to the output root, so no namespaces are generated.`,\n help: 'Give the plugin its own `output.path`, such as `client`.',\n })\n }\n return\n }\n\n // `mode: 'file'` writes a single file, so there is no directory to barrel. The root barrel\n // re-exports that file as a direct leaf of `config.output.path`.\n if (plugin.options.output.mode === 'file') {\n return\n }\n\n if (!isPathInside(target, base)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.pathTraversal,\n severity: 'error',\n message: `Output path \"${plugin.options.output.path}\" of plugin \"${plugin.name}\" resolves outside the output directory \"${base}\".`,\n help: 'Keep the plugin `output.path` within `config.output.path`.',\n location: { kind: 'config' },\n })\n }\n\n // Only the target directory and barrel strategy are recorded here. The actual file-set\n // scan and directory-tree build happen once, in `kubb:plugins:end`, and are shared by\n // every plugin barrel plus the root barrel instead of repeating per plugin.\n pendingBarrels.push({ plugin, target, barrelType: barrelConfig.type, nested: barrelConfig.nested ?? false, namespace: barrelConfig.namespace ?? false })\n },\n 'kubb:plugins:end'({ files, config, upsertFile }) {\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n const rootBarrelConfig = config.output.barrel ?? false\n const outputPath = path.resolve(config.root, config.output.path)\n\n // A `barrel: false` plugin gets no barrel and stays out of the root, so drop its files\n // once here. Every barrel below then derives from a single index of what remains.\n const relevantFiles = files.filter((file) => {\n const owner = (file.meta as { pluginName?: string } | undefined)?.pluginName\n if (owner) return !excludedPlugins.has(owner)\n\n return !excludedTargets.some((target) => isPathInside(file.path, target))\n })\n excludedPlugins.clear()\n excludedTargets.length = 0\n\n // Each config's barrels re-export the shared schemas it defines. The shared directory gets none, since each config writes only part of it.\n const index = buildBarrelIndex({\n outputPath,\n files: relevantFiles,\n sharedPath: config.shared && path.resolve(config.root, config.shared.path),\n })\n const reportedCollisions = new Set<string>()\n // Keyed by path and name: plugins sharing an `output.path` produce the same aliases.\n const namespaceExports = new Map<string, ast.ExportNode>()\n\n pendingBarrels.forEach(({ plugin, target, barrelType, nested, namespace }) => {\n getBarrelFiles({ index, targetPath: target, barrelType, nested, namespace, recursive: true, reportedCollisions }).forEach((file) => {\n upsertFile(withBarrelBannerFooter({ file, plugin, config }))\n if (file.path !== `${toPosixPath(target)}/index.ts`) return\n file.exports\n .filter((item) => item.asAlias)\n .forEach((item) => {\n const itemPath = `./${toPosixPath(path.relative(outputPath, path.resolve(target, item.path)))}`\n namespaceExports.set(`${itemPath}\\0${item.name}`, ast.factory.createExport({ ...item, path: itemPath }))\n })\n })\n })\n pendingBarrels.length = 0\n\n if (rootBarrelConfig === false) return\n\n getBarrelFiles({ index, barrelType: rootBarrelConfig.type, additionalExports: [...namespaceExports.values()], reportedCollisions }).forEach((file) => {\n upsertFile(file)\n })\n },\n },\n})\n"],"mappings":";;;;;;;;;;;AAyBA,SAAgB,KAAmB,OAA4B,KAAW,SAA+B;CACvG,MAAM,SAAS,MAAM,IAAI,GAAG;CAC5B,IAAI,WAAW,KAAA,KAAa,MAAM,IAAI,GAAG,GAAG,OAAO;CACnD,MAAM,QAAQ,QAAQ;CACtB,MAAM,IAAI,KAAK,KAAK;CACpB,OAAO;AACT;AA2BA,SAAS,YAA0B,EAAE,MAAM,QAA0C,CAAC,GAAwB;CAC5G,IAAI,MAAM,uBAAO,IAAI,QAAyB;CAC9C,MAAM,wBAAQ,IAAI,IAAkB;CACpC,IAAI,QAAQ,KAAA,GAAW,OAAO;CAC9B,MAAM,OAAO,KAAW,UAAkB;EACxC,IAAI,MAAM,QAAQ,KAAK,MAAM,MAAM;EACnC,MAAM,IAAI,KAAK,KAAK;CACtB;CACA,IAAI,QAAQ,GAAG,OAAO;EAAE,MAAM,QAAQ,MAAM,IAAI,GAAG;EAAG,MAAM,QAAQ,MAAM,IAAI,GAAG;EAAG;CAAI;CAGxF,MAAM,SAAS,QAAc;EAC3B,IAAI,CAAC,MAAM,IAAI,GAAG,GAAG,OAAO;EAC5B,IAAI,KAAK,MAAM,IAAI,GAAG,CAAW;EACjC,OAAO;CACT;CACA,OAAO;EAAE,KAAK;EAAO,MAAM,QAAS,MAAM,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AAmB,IAAI,IAA4B;GAEzD,eAAe,SAAS,EAAE,QAAQ,QAAQ,YAAY,QAAQ,gBAAgB;IAC5E,eAAe;KAAE;KAAO,YAAY;KAAQ;KAAY;KAAQ;KAAW,WAAW;KAAM;IAAmB,CAAC,CAAC,CAAC,SAAS,SAAS;KAClI,WAAW,uBAAuB;MAAE;MAAM;MAAQ;KAAO,CAAC,CAAC;KAC3D,IAAI,KAAK,SAAS,GAAG,YAAY,MAAM,EAAE,YAAY;KACrD,KAAK,QACF,QAAQ,SAAS,KAAK,OAAO,CAAC,CAC9B,SAAS,SAAS;MACjB,MAAM,WAAW,KAAK,YAAY,KAAK,SAAS,YAAY,KAAK,QAAQ,QAAQ,KAAK,IAAI,CAAC,CAAC;MAC5F,iBAAiB,IAAI,GAAG,SAAS,IAAI,KAAK,QAAQ,IAAI,QAAQ,aAAa;OAAE,GAAG;OAAM,MAAM;MAAS,CAAC,CAAC;KACzG,CAAC;IACL,CAAC;GACH,CAAC;GACD,eAAe,SAAS;GAExB,IAAI,qBAAqB,OAAO;GAEhC,eAAe;IAAE;IAAO,YAAY,iBAAiB;IAAM,mBAAmB,CAAC,GAAG,iBAAiB,OAAO,CAAC;IAAG;GAAmB,CAAC,CAAC,CAAC,SAAS,SAAS;IACpJ,WAAW,IAAI;GACjB,CAAC;EACH;CACF;AACF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubb/plugin-barrel",
3
- "version": "5.23.1",
3
+ "version": "5.23.3",
4
4
  "description": "Barrel-file plugin for Kubb. Automatically generates index.ts re-export files per plugin output directory.",
5
5
  "keywords": [
6
6
  "barrel",
@@ -66,7 +66,7 @@
66
66
  "registry": "https://registry.npmjs.org/"
67
67
  },
68
68
  "dependencies": {
69
- "@kubb/kit": "5.23.1"
69
+ "@kubb/kit": "5.23.3"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@internals/utils": "0.0.1"