@kubb/core 5.15.0 → 5.15.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +203 -317
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +45 -101
- package/dist/index.d.ts +3242 -8
- package/dist/index.js +3279 -146
- package/dist/index.js.map +1 -1
- package/package.json +2 -21
- package/dist/Hookable-BYr6s0lB.js +0 -3265
- package/dist/Hookable-BYr6s0lB.js.map +0 -1
- package/dist/createAdapter-CCe-Oddm.d.ts +0 -3294
- package/dist/mocks.d.ts +0 -105
- package/dist/mocks.js +0 -204
- package/dist/mocks.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,16 +1,118 @@
|
|
|
1
|
-
import { A as resolveMeta, B as rm$1, C as setResolver, D as useOptions, E as useKubb, F as exists, G as pascalCase, H as writeRaw, I as existsSync$1, L as isPathInside, M as formatMs, N as getElapsedMs, O as checkCompatibility, P as inParallel, R as listFiles, S as setOptions, T as useConfig, U as toError, V as write, W as camelCase, _ as injectFile, b as requirePlugin, c as Resolver, d as isPublicAddress, g as addMacro, h as addGenerator, j as Diagnostics, k as defineExtension, l as getInputKind, m as definePlugin, n as KubbDriver, o as _usingCtx, p as assertPluginOption, s as createResolver, t as Hookable, u as checkoutGitInput, v as kubbContext, w as tryUseKubb, x as setMacros, y as memo, z as read } from "./Hookable-BYr6s0lB.js";
|
|
2
1
|
import { createRequire } from "node:module";
|
|
3
|
-
import { isValid } from "verkit";
|
|
2
|
+
import { isValid, satisfies } from "verkit";
|
|
3
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
4
|
import process$1 from "node:process";
|
|
5
5
|
import { x } from "tinyexec";
|
|
6
|
-
import { readFile, readdir, rename } from "node:fs/promises";
|
|
7
|
-
import path, { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
8
|
-
import { chmodSync, existsSync, mkdirSync } from "node:fs";
|
|
6
|
+
import { access, glob, mkdir, mkdtemp, readFile, readdir, rename, rm, rm as rm$1, writeFile } from "node:fs/promises";
|
|
7
|
+
import path, { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
8
|
+
import { chmodSync, existsSync, existsSync as existsSync$1, mkdirSync } from "node:fs";
|
|
9
9
|
import { stripVTControlCharacters, styleText } from "node:util";
|
|
10
|
+
import { ast, collectImportedRefNames, collectUsedSchemaNames, compareEnforce, extractStringsFromNodes } from "@kubb/ast";
|
|
11
|
+
import dns from "node:dns";
|
|
12
|
+
import net from "node:net";
|
|
10
13
|
import { homedir, tmpdir } from "node:os";
|
|
11
14
|
import { hash, randomUUID } from "node:crypto";
|
|
12
15
|
import { createInterface } from "node:readline";
|
|
13
16
|
import { fileURLToPath } from "node:url";
|
|
17
|
+
// \0rolldown/runtime.js
|
|
18
|
+
var __defProp = Object.defineProperty;
|
|
19
|
+
var __name = (target, value) => __defProp(target, "name", {
|
|
20
|
+
value,
|
|
21
|
+
configurable: true
|
|
22
|
+
});
|
|
23
|
+
// package.json
|
|
24
|
+
var version = "5.15.2";
|
|
25
|
+
// ../../internals/utils/src/casing.ts
|
|
26
|
+
/**
|
|
27
|
+
* Shared implementation for camelCase and PascalCase conversion.
|
|
28
|
+
* Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
|
|
29
|
+
* and capitalizes each word according to `pascal`.
|
|
30
|
+
*
|
|
31
|
+
* When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
|
|
32
|
+
*/
|
|
33
|
+
function convert(text, pascal) {
|
|
34
|
+
return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
|
|
35
|
+
if (word.length > 1 && word === word.toUpperCase()) return word;
|
|
36
|
+
return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
|
|
37
|
+
}).join("").replace(/[^a-zA-Z0-9]/g, "");
|
|
38
|
+
}
|
|
39
|
+
const cache = /* @__PURE__ */ new Map();
|
|
40
|
+
const cacheLimit = 1e5;
|
|
41
|
+
function toCamelOrPascal(text, pascal) {
|
|
42
|
+
const key = `${pascal ? "P" : "c"}${text}`;
|
|
43
|
+
const cached = cache.get(key);
|
|
44
|
+
if (cached !== void 0) return cached;
|
|
45
|
+
const result = convert(text, pascal);
|
|
46
|
+
if (cache.size >= cacheLimit) cache.clear();
|
|
47
|
+
cache.set(key, result);
|
|
48
|
+
return result;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Converts `text` to camelCase.
|
|
52
|
+
*
|
|
53
|
+
* @example Word boundaries
|
|
54
|
+
* `camelCase('hello-world') // 'helloWorld'`
|
|
55
|
+
*
|
|
56
|
+
* @example With a prefix
|
|
57
|
+
* `camelCase('tag', { prefix: 'create' }) // 'createTag'`
|
|
58
|
+
*/
|
|
59
|
+
function camelCase(text, { prefix = "", suffix = "" } = {}) {
|
|
60
|
+
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Converts `text` to PascalCase.
|
|
64
|
+
*
|
|
65
|
+
* @example Word boundaries
|
|
66
|
+
* `pascalCase('hello-world') // 'HelloWorld'`
|
|
67
|
+
*
|
|
68
|
+
* @example With a suffix
|
|
69
|
+
* `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
|
|
70
|
+
*/
|
|
71
|
+
function pascalCase(text, { prefix = "", suffix = "" } = {}) {
|
|
72
|
+
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
|
|
73
|
+
}
|
|
74
|
+
// ../../internals/utils/src/errors.ts
|
|
75
|
+
/**
|
|
76
|
+
* Coerces an unknown thrown value to an `Error` instance.
|
|
77
|
+
* Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* ```ts
|
|
81
|
+
* try { ... } catch(err) {
|
|
82
|
+
* throw new Error('Build failed', { cause: toError(err) })
|
|
83
|
+
* }
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
function toError(value) {
|
|
87
|
+
return value instanceof Error ? value : new Error(String(value));
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Extracts a human-readable message from any thrown value.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```ts
|
|
94
|
+
* getErrorMessage(new Error('oops')) // 'oops'
|
|
95
|
+
* getErrorMessage('plain string') // 'plain string'
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
function getErrorMessage(value) {
|
|
99
|
+
return value instanceof Error ? value.message : String(value);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Returns `error` followed by every error in its `cause` chain, outermost first. Stops at a
|
|
103
|
+
* non-`Error` cause or a cycle.
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* ```ts
|
|
107
|
+
* getErrorChain(new Error('Config failed loading', { cause: new Error('boom') })).map((error) => error.message)
|
|
108
|
+
* // ['Config failed loading', 'boom']
|
|
109
|
+
* ```
|
|
110
|
+
*/
|
|
111
|
+
function getErrorChain(error) {
|
|
112
|
+
const chain = [];
|
|
113
|
+
for (let current = error; current instanceof Error && !chain.includes(current); current = current.cause) chain.push(current);
|
|
114
|
+
return chain;
|
|
115
|
+
}
|
|
14
116
|
// ../../internals/utils/src/isCIEnvironment.ts
|
|
15
117
|
/**
|
|
16
118
|
* Returns `true` when a known CI provider has set its environment variable.
|
|
@@ -38,6 +140,222 @@ function openInBrowser(target) {
|
|
|
38
140
|
}
|
|
39
141
|
x(process$1.platform === "darwin" ? "open" : "xdg-open", [target]).then(ignore, ignore);
|
|
40
142
|
}
|
|
143
|
+
// ../../internals/utils/src/runtime.ts
|
|
144
|
+
const isBun = typeof Bun !== "undefined";
|
|
145
|
+
const isDeno = "Deno" in globalThis;
|
|
146
|
+
/**
|
|
147
|
+
* The JavaScript runtime executing the current process: its name, version and whether it is Bun.
|
|
148
|
+
*
|
|
149
|
+
* @example
|
|
150
|
+
* ```ts
|
|
151
|
+
* runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
const runtime = {
|
|
155
|
+
isBun,
|
|
156
|
+
...detect()
|
|
157
|
+
};
|
|
158
|
+
function detect() {
|
|
159
|
+
if (isBun) return {
|
|
160
|
+
name: "bun",
|
|
161
|
+
version: process.versions.bun ?? ""
|
|
162
|
+
};
|
|
163
|
+
if (isDeno) return {
|
|
164
|
+
name: "deno",
|
|
165
|
+
version: globalThis.Deno?.version?.deno ?? ""
|
|
166
|
+
};
|
|
167
|
+
return {
|
|
168
|
+
name: "node",
|
|
169
|
+
version: process.versions?.node ?? ""
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
// ../../internals/utils/src/fs.ts
|
|
173
|
+
/**
|
|
174
|
+
* Resolves to `true` when the file or directory at `path` exists.
|
|
175
|
+
* Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.
|
|
176
|
+
*
|
|
177
|
+
* @example
|
|
178
|
+
* ```ts
|
|
179
|
+
* if (await exists('./kubb.config.ts')) {
|
|
180
|
+
* const content = await read('./kubb.config.ts')
|
|
181
|
+
* }
|
|
182
|
+
* ```
|
|
183
|
+
*/
|
|
184
|
+
async function exists(path) {
|
|
185
|
+
if (runtime.isBun) return Bun.file(path).exists();
|
|
186
|
+
return access(path).then(() => true, () => false);
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Reads the file at `path` as a UTF-8 string.
|
|
190
|
+
* Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.
|
|
191
|
+
*
|
|
192
|
+
* @example
|
|
193
|
+
* ```ts
|
|
194
|
+
* const source = await read('./src/Pet.ts')
|
|
195
|
+
* ```
|
|
196
|
+
*/
|
|
197
|
+
async function read(path) {
|
|
198
|
+
if (runtime.isBun) return Bun.file(path).text();
|
|
199
|
+
return readFile(path, { encoding: "utf8" });
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact
|
|
203
|
+
* bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a
|
|
204
|
+
* reason to rewrite the file.
|
|
205
|
+
*
|
|
206
|
+
* Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one
|
|
207
|
+
* that normalizes what it stores. Trimming only `stored` would leave a source with leading
|
|
208
|
+
* whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison
|
|
209
|
+
* has already dropped.
|
|
210
|
+
*/
|
|
211
|
+
function matchesStored({ stored, source }) {
|
|
212
|
+
return stored.trim() === source.trim();
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline
|
|
216
|
+
* the way prettier, biome, and oxfmt all do.
|
|
217
|
+
* Skips the write when the trimmed content is empty, or when the file already holds that content.
|
|
218
|
+
* Creates any missing parent directories automatically.
|
|
219
|
+
* When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```ts
|
|
223
|
+
* await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline
|
|
224
|
+
* await write('./src/Pet.ts', source) // null — file unchanged
|
|
225
|
+
* await write('./src/Pet.ts', ' ') // null — empty content skipped
|
|
226
|
+
* ```
|
|
227
|
+
*/
|
|
228
|
+
async function write(path, data, options = {}) {
|
|
229
|
+
const trimmed = data.trim();
|
|
230
|
+
if (trimmed === "") return null;
|
|
231
|
+
const content = `${trimmed}\n`;
|
|
232
|
+
const resolved = resolve(path);
|
|
233
|
+
if (matchesStored({
|
|
234
|
+
stored: (options.stored === void 0 ? await read(resolved).catch(() => null) : options.stored) ?? "",
|
|
235
|
+
source: trimmed
|
|
236
|
+
})) return null;
|
|
237
|
+
await writeRaw(resolved, content);
|
|
238
|
+
if (options.sanity) {
|
|
239
|
+
const savedData = await read(resolved);
|
|
240
|
+
if (savedData !== content) throw new Error(`Sanity check failed for ${path}\n\nData[${data.length}]:\n${data}\n\nSaved[${savedData.length}]:\n${savedData}\n`);
|
|
241
|
+
return savedData;
|
|
242
|
+
}
|
|
243
|
+
return content;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Writes UTF-8 content verbatim, including empty files and surrounding whitespace.
|
|
247
|
+
* Uses Bun.write under Bun and creates missing parent directories under either runtime.
|
|
248
|
+
*
|
|
249
|
+
* @example
|
|
250
|
+
* await writeRaw('./cache/output.ts', ' // keep these bytes\n\n')
|
|
251
|
+
*/
|
|
252
|
+
async function writeRaw(path, content) {
|
|
253
|
+
const resolved = resolve(path);
|
|
254
|
+
if (runtime.isBun) {
|
|
255
|
+
await Bun.write(resolved, content);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
try {
|
|
259
|
+
await writeFile(resolved, content, { encoding: "utf-8" });
|
|
260
|
+
} catch (error) {
|
|
261
|
+
if (error.code !== "ENOENT") throw error;
|
|
262
|
+
await mkdir(dirname(resolved), { recursive: true });
|
|
263
|
+
await writeFile(resolved, content, { encoding: "utf-8" });
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Lists non-hidden regular files below `directory` as relative POSIX paths, excluding directories and symlinks.
|
|
268
|
+
* Uses Bun.Glob under Bun because its Node glob compatibility API lacks directory-entry support.
|
|
269
|
+
*
|
|
270
|
+
* @example
|
|
271
|
+
* for await (const path of listFiles('./src')) console.log(path)
|
|
272
|
+
*/
|
|
273
|
+
async function* listFiles(directory) {
|
|
274
|
+
const cwd = resolve(directory);
|
|
275
|
+
if (runtime.isBun) {
|
|
276
|
+
yield* new Bun.Glob("**/*").scan({
|
|
277
|
+
cwd,
|
|
278
|
+
dot: false,
|
|
279
|
+
onlyFiles: true,
|
|
280
|
+
followSymlinks: false
|
|
281
|
+
});
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
for await (const entry of glob("**/*", {
|
|
285
|
+
cwd,
|
|
286
|
+
withFileTypes: true
|
|
287
|
+
})) if (entry.isFile()) yield toPosixPath(relative(cwd, join(entry.parentPath, entry.name)));
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Converts a filesystem path to use POSIX (`/`) separators.
|
|
291
|
+
*
|
|
292
|
+
* Most of the codebase compares and composes paths as strings (prefix matching, joining for
|
|
293
|
+
* import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated
|
|
294
|
+
* paths, but on Windows it returns `\`-separated paths, which breaks every such comparison.
|
|
295
|
+
*
|
|
296
|
+
* Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the
|
|
297
|
+
* code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is
|
|
298
|
+
* exercisable from POSIX CI.
|
|
299
|
+
*
|
|
300
|
+
* @example
|
|
301
|
+
* toPosixPath('C:\\repo\\src\\pet.ts') // 'C:/repo/src/pet.ts'
|
|
302
|
+
*/
|
|
303
|
+
function toPosixPath(filePath) {
|
|
304
|
+
return filePath.replaceAll("\\", "/");
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved
|
|
308
|
+
* to absolute paths first, so relative and `..`-containing inputs compare correctly.
|
|
309
|
+
*
|
|
310
|
+
* Guards a destructive or an out-of-tree operation: before wiping an output directory, check that
|
|
311
|
+
* it does not contain the project root, and before loading a path a caller supplied, check that it
|
|
312
|
+
* did not escape the directory it is allowed to read from.
|
|
313
|
+
*
|
|
314
|
+
* @example
|
|
315
|
+
* isPathInside('./src/gen', '.') // true — nested inside the root
|
|
316
|
+
* isPathInside('.', '.') // true — the same directory counts as inside
|
|
317
|
+
* isPathInside('.', './src/gen') // false — the root is not inside its own output
|
|
318
|
+
* isPathInside('../other', '.') // false — escapes the root
|
|
319
|
+
*/
|
|
320
|
+
function isPathInside(path, parent) {
|
|
321
|
+
const resolvedPath = resolve(path);
|
|
322
|
+
const resolvedParent = resolve(parent);
|
|
323
|
+
if (resolvedPath === resolvedParent) return true;
|
|
324
|
+
const rel = relative(resolvedParent, resolvedPath);
|
|
325
|
+
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
|
326
|
+
}
|
|
327
|
+
// ../../internals/utils/src/promise.ts
|
|
328
|
+
/**
|
|
329
|
+
* Returns the value cached under `key` in `store`, computing and storing it on the first call.
|
|
330
|
+
* Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive
|
|
331
|
+
* keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.
|
|
332
|
+
*
|
|
333
|
+
* @example
|
|
334
|
+
* `const refs = memo(refCache, node, () => collectRefs(node))`
|
|
335
|
+
*/
|
|
336
|
+
function memo$1(store, key, compute) {
|
|
337
|
+
if (store.has(key)) return store.get(key);
|
|
338
|
+
const value = compute();
|
|
339
|
+
store.set(key, value);
|
|
340
|
+
return value;
|
|
341
|
+
}
|
|
342
|
+
__name(memo$1, "memo");
|
|
343
|
+
/**
|
|
344
|
+
* Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each
|
|
345
|
+
* takes the next item the moment it frees up instead of waiting for a batch to drain.
|
|
346
|
+
*
|
|
347
|
+
* @example
|
|
348
|
+
* ```ts
|
|
349
|
+
* await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })
|
|
350
|
+
* ```
|
|
351
|
+
*/
|
|
352
|
+
async function inParallel({ items, limit, run }) {
|
|
353
|
+
const queue = items.entries();
|
|
354
|
+
const worker = async () => {
|
|
355
|
+
for (const [index, item] of queue) await run(item, index);
|
|
356
|
+
};
|
|
357
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
|
|
358
|
+
}
|
|
41
359
|
// ../../internals/utils/src/tools.ts
|
|
42
360
|
/**
|
|
43
361
|
* CLI command descriptors for each supported code formatter.
|
|
@@ -122,45 +440,2772 @@ async function isToolAvailable(name, cwd) {
|
|
|
122
440
|
cwd,
|
|
123
441
|
stdio: "ignore"
|
|
124
442
|
}
|
|
125
|
-
}).then(({ exitCode }) => exitCode === 0, () => false);
|
|
126
|
-
}
|
|
127
|
-
/**
|
|
128
|
-
* Returns the first installed executable from `candidates`, or `null` when none are found.
|
|
129
|
-
*
|
|
130
|
-
* Not memoized: a long-running host that probes repeatedly should cache the result itself, and a
|
|
131
|
-
* `--watch` build should keep noticing a tool installed mid-session.
|
|
132
|
-
*/
|
|
133
|
-
async function detectTool(candidates, cwd) {
|
|
134
|
-
for (const candidate of candidates) if (await isToolAvailable(candidate, cwd)) return candidate;
|
|
135
|
-
return null;
|
|
136
|
-
}
|
|
137
|
-
/**
|
|
138
|
-
* Tokenizes a shell command string, respecting single and double quotes.
|
|
139
|
-
*
|
|
140
|
-
* @example
|
|
141
|
-
* ```ts
|
|
142
|
-
* tokenize('git commit -m "initial commit"')
|
|
143
|
-
* // → ['git', 'commit', '-m', 'initial commit']
|
|
144
|
-
* ```
|
|
145
|
-
*/
|
|
146
|
-
function tokenize(command) {
|
|
147
|
-
return (command.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g) ?? []).map((token) => token.replace(/^["']|["']$/g, ""));
|
|
148
|
-
}
|
|
149
|
-
// src/
|
|
150
|
-
/**
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
*
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
443
|
+
}).then(({ exitCode }) => exitCode === 0, () => false);
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Returns the first installed executable from `candidates`, or `null` when none are found.
|
|
447
|
+
*
|
|
448
|
+
* Not memoized: a long-running host that probes repeatedly should cache the result itself, and a
|
|
449
|
+
* `--watch` build should keep noticing a tool installed mid-session.
|
|
450
|
+
*/
|
|
451
|
+
async function detectTool(candidates, cwd) {
|
|
452
|
+
for (const candidate of candidates) if (await isToolAvailable(candidate, cwd)) return candidate;
|
|
453
|
+
return null;
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Tokenizes a shell command string, respecting single and double quotes.
|
|
457
|
+
*
|
|
458
|
+
* @example
|
|
459
|
+
* ```ts
|
|
460
|
+
* tokenize('git commit -m "initial commit"')
|
|
461
|
+
* // → ['git', 'commit', '-m', 'initial commit']
|
|
462
|
+
* ```
|
|
463
|
+
*/
|
|
464
|
+
function tokenize(command) {
|
|
465
|
+
return (command.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g) ?? []).map((token) => token.replace(/^["']|["']$/g, ""));
|
|
466
|
+
}
|
|
467
|
+
// ../../internals/utils/src/time.ts
|
|
468
|
+
/**
|
|
469
|
+
* Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.
|
|
470
|
+
* Rounds to 2 decimal places for sub-millisecond precision without noise.
|
|
471
|
+
*
|
|
472
|
+
* @example
|
|
473
|
+
* ```ts
|
|
474
|
+
* const start = process.hrtime()
|
|
475
|
+
* doWork()
|
|
476
|
+
* getElapsedMs(start) // 42.35
|
|
477
|
+
* ```
|
|
478
|
+
*/
|
|
479
|
+
function getElapsedMs(hrStart) {
|
|
480
|
+
const [seconds, nanoseconds] = process.hrtime(hrStart);
|
|
481
|
+
const ms = seconds * 1e3 + nanoseconds / 1e6;
|
|
482
|
+
return Math.round(ms * 100) / 100;
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).
|
|
486
|
+
*
|
|
487
|
+
* @example
|
|
488
|
+
* ```ts
|
|
489
|
+
* formatMs(250) // '250ms'
|
|
490
|
+
* formatMs(1500) // '1.50s'
|
|
491
|
+
* formatMs(90000) // '1m 30.0s'
|
|
492
|
+
* ```
|
|
493
|
+
*/
|
|
494
|
+
function formatMs(ms) {
|
|
495
|
+
if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
|
|
496
|
+
if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
|
|
497
|
+
return `${Math.round(ms)}ms`;
|
|
498
|
+
}
|
|
499
|
+
// src/diagnosticCatalog.ts
|
|
500
|
+
/**
|
|
501
|
+
* Every diagnostic code with its docs entry: a short title, what triggers it, and how to resolve
|
|
502
|
+
* it. The source of truth for {@link diagnosticCode}, and the kubb.dev `/reference/diagnostics`
|
|
503
|
+
* sections mirror it.
|
|
504
|
+
*/
|
|
505
|
+
const diagnosticCatalog = {
|
|
506
|
+
unknown: {
|
|
507
|
+
code: "KUBB_UNKNOWN",
|
|
508
|
+
title: "Unknown error",
|
|
509
|
+
cause: "An error was thrown without a stable Kubb code, so it is reported as-is.",
|
|
510
|
+
fix: "Read the underlying message and stack. If it comes from a plugin or adapter, check its configuration; otherwise report it as a possible Kubb bug."
|
|
511
|
+
},
|
|
512
|
+
inputNotFound: {
|
|
513
|
+
code: "KUBB_INPUT_NOT_FOUND",
|
|
514
|
+
title: "Input not found",
|
|
515
|
+
cause: "The file set as `input` (or passed as `kubb generate PATH`) could not be read. A URL reports `KUBB_INPUT_REQUEST_FAILED` or `KUBB_INPUT_UNREACHABLE` instead.",
|
|
516
|
+
fix: "Check that the path exists and is readable, then set it as `input` or pass it on the CLI."
|
|
517
|
+
},
|
|
518
|
+
inputRequestFailed: {
|
|
519
|
+
code: "KUBB_INPUT_REQUEST_FAILED",
|
|
520
|
+
title: "Input request failed",
|
|
521
|
+
cause: "A URL set as `input` (or reached through a `$ref`) answered with a 4xx or 5xx status instead of the document.",
|
|
522
|
+
fix: "Open the URL to see what the server returns. A 401 or 403 needs credentials Kubb does not send, so download the document and point `input` at the local file. A 404 means the path is wrong, and a 5xx means the server itself failed."
|
|
523
|
+
},
|
|
524
|
+
inputUnreachable: {
|
|
525
|
+
code: "KUBB_INPUT_UNREACHABLE",
|
|
526
|
+
title: "Input unreachable",
|
|
527
|
+
cause: "A URL set as `input` (or reached through a `$ref`) never answered, so the request failed before a status came back. A refused connection, an unknown host, an expired certificate, and a timeout all land here.",
|
|
528
|
+
fix: "Check that the host is running and reachable from this machine. For a local server, start it and confirm the port matches the one in `input`."
|
|
529
|
+
},
|
|
530
|
+
gitInputFailed: {
|
|
531
|
+
code: "KUBB_GIT_INPUT_FAILED",
|
|
532
|
+
title: "Git input failed",
|
|
533
|
+
cause: "A git `input` (`git+<repo>#<ref>:<path>`) is malformed, or `git` could not fetch it: git is not installed, the repository or ref does not exist, or the credentials were refused.",
|
|
534
|
+
fix: "Write the input as `git+<repo>#<ref>:<path>`. Run `git fetch --depth 1 <repo> <ref>` yourself to see the git error, and set up a credential helper or SSH key for a private repository."
|
|
535
|
+
},
|
|
536
|
+
inputRequired: {
|
|
537
|
+
code: "KUBB_INPUT_REQUIRED",
|
|
538
|
+
title: "Input required",
|
|
539
|
+
cause: "An adapter is configured but no `input` was provided.",
|
|
540
|
+
fix: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config."
|
|
541
|
+
},
|
|
542
|
+
legacyInput: {
|
|
543
|
+
code: "KUBB_LEGACY_INPUT",
|
|
544
|
+
title: "Legacy input shape",
|
|
545
|
+
cause: "`input` is a `{ path }` or `{ data }` wrapper, which v4 used to point at a document and v5 reads as the document itself.",
|
|
546
|
+
fix: "Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`."
|
|
547
|
+
},
|
|
548
|
+
invalidDocument: {
|
|
549
|
+
code: "KUBB_INVALID_DOCUMENT",
|
|
550
|
+
title: "Invalid document",
|
|
551
|
+
cause: "The `input` cannot be read as an OpenAPI or Swagger document: its JSON or YAML has a syntax error, it declares no `openapi` or `swagger` version field, or its version cannot be upgraded to OpenAPI 3.1.",
|
|
552
|
+
fix: "Fix the syntax at the reported line, and check that `input` points at the spec and not an HTML page. Point `input` at a Swagger 2.0, OpenAPI 3.0, or OpenAPI 3.1 document, and check that a passed object is the spec itself rather than a wrapper around it."
|
|
553
|
+
},
|
|
554
|
+
invalidSpec: {
|
|
555
|
+
code: "KUBB_INVALID_SPEC",
|
|
556
|
+
title: "Invalid spec",
|
|
557
|
+
cause: "The document does not pass OpenAPI schema validation. Kubb still generates from it, but the output can be incomplete or wrong.",
|
|
558
|
+
fix: "Fix the reported problem in the spec. Run `kubb validate` to list every error, or set `validate: false` on the adapter to skip the check."
|
|
559
|
+
},
|
|
560
|
+
refNotFound: {
|
|
561
|
+
code: "KUBB_REF_NOT_FOUND",
|
|
562
|
+
title: "Reference not found",
|
|
563
|
+
cause: "A `$ref` could not be resolved in the source document.",
|
|
564
|
+
fix: "Add the missing definition (for example under `components.schemas`) or fix the `$ref`. Run `kubb validate` to check the spec."
|
|
565
|
+
},
|
|
566
|
+
invalidServerVariable: {
|
|
567
|
+
code: "KUBB_INVALID_SERVER_VARIABLE",
|
|
568
|
+
title: "Invalid server variable",
|
|
569
|
+
cause: "A server variable value is not allowed by its `enum`.",
|
|
570
|
+
fix: "Use one of the values listed in the server variable `enum`, or update the spec."
|
|
571
|
+
},
|
|
572
|
+
pluginNotFound: {
|
|
573
|
+
code: "KUBB_PLUGIN_NOT_FOUND",
|
|
574
|
+
title: "Plugin not found",
|
|
575
|
+
cause: "A plugin that another plugin depends on is missing from the config.",
|
|
576
|
+
fix: "Add the required plugin to the `plugins` array in kubb.config.ts, or remove the dependency on it."
|
|
577
|
+
},
|
|
578
|
+
incompatibleExtension: {
|
|
579
|
+
code: "KUBB_INCOMPATIBLE_EXTENSION",
|
|
580
|
+
title: "Incompatible extension",
|
|
581
|
+
cause: "A plugin sets `meta.compatibility.kubb` or `meta.compatibility.node` to a range the running Kubb or Node.js version does not satisfy.",
|
|
582
|
+
fix: "Upgrade Kubb or Node.js to a version in the range, or install a version of the plugin that supports your current Kubb and Node.js."
|
|
583
|
+
},
|
|
584
|
+
missingDependency: {
|
|
585
|
+
code: "KUBB_MISSING_DEPENDENCY",
|
|
586
|
+
title: "Missing dependency",
|
|
587
|
+
cause: "A plugin lists another plugin in its `dependencies` record without `optional: true`, and the config does not include it.",
|
|
588
|
+
fix: "Add the missing plugin to the `plugins` array in kubb.config.ts."
|
|
589
|
+
},
|
|
590
|
+
incompatibleDependency: {
|
|
591
|
+
code: "KUBB_INCOMPATIBLE_DEPENDENCY",
|
|
592
|
+
title: "Incompatible dependency",
|
|
593
|
+
cause: "A plugin's `dependencies` record sets a `version` range, and the configured plugin's `meta.version` falls outside it.",
|
|
594
|
+
fix: "Install a version of the dependency inside the range, or a version of the dependent plugin that supports the installed dependency."
|
|
595
|
+
},
|
|
596
|
+
pluginFailed: {
|
|
597
|
+
code: "KUBB_PLUGIN_FAILED",
|
|
598
|
+
title: "Plugin failed",
|
|
599
|
+
cause: "A plugin threw while generating, or reported an error through `ctx.error`.",
|
|
600
|
+
fix: "Check the plugin options and the node at `at:`. If it is a bug, report it with the stack at `report:`."
|
|
601
|
+
},
|
|
602
|
+
adapterFailed: {
|
|
603
|
+
code: "KUBB_ADAPTER_FAILED",
|
|
604
|
+
title: "Adapter failed",
|
|
605
|
+
cause: "The adapter threw an unexpected error while parsing the input.",
|
|
606
|
+
fix: "Check the input and the adapter options. If it is a bug, report it with the stack at `report:`."
|
|
607
|
+
},
|
|
608
|
+
parserFailed: {
|
|
609
|
+
code: "KUBB_PARSER_FAILED",
|
|
610
|
+
title: "Parser failed",
|
|
611
|
+
cause: "A parser threw an unexpected error while printing a generated file.",
|
|
612
|
+
fix: "Check the parser options. If it is a bug, report it with the stack at `report:`."
|
|
613
|
+
},
|
|
614
|
+
pluginWarning: {
|
|
615
|
+
code: "KUBB_PLUGIN_WARNING",
|
|
616
|
+
title: "Plugin warning",
|
|
617
|
+
cause: "A plugin reported a non-fatal warning through `ctx.warn`.",
|
|
618
|
+
fix: "Review the message. It does not fail the build; adjust the plugin options or input if the warning is unwanted."
|
|
619
|
+
},
|
|
620
|
+
pluginInfo: {
|
|
621
|
+
code: "KUBB_PLUGIN_INFO",
|
|
622
|
+
title: "Plugin info",
|
|
623
|
+
cause: "A plugin reported an informational message through `ctx.info`.",
|
|
624
|
+
fix: "Informational only. No action is required."
|
|
625
|
+
},
|
|
626
|
+
noContext: {
|
|
627
|
+
code: "KUBB_NO_CONTEXT",
|
|
628
|
+
title: "No plugin context",
|
|
629
|
+
cause: "A `kubb/kit` composable such as `useKubb()` or `addGenerator()` ran outside the `setup` and `kubb:plugin:setup` of a plugin, so there is no plugin to apply it to.",
|
|
630
|
+
fix: "Call the composable inside `setup` or `kubb:plugin:setup`, including in code that setup awaits."
|
|
631
|
+
},
|
|
632
|
+
unsupportedFormat: {
|
|
633
|
+
code: "KUBB_UNSUPPORTED_FORMAT",
|
|
634
|
+
title: "Unsupported format",
|
|
635
|
+
cause: "A schema uses a `format` Kubb does not map to a specific type, so it falls back to the base type.",
|
|
636
|
+
fix: "Use a format Kubb supports, or handle the custom format with a parser or plugin."
|
|
637
|
+
},
|
|
638
|
+
aliasCycle: {
|
|
639
|
+
code: "KUBB_ALIAS_CYCLE",
|
|
640
|
+
title: "Alias cycle",
|
|
641
|
+
cause: "Schemas that only `$ref` each other form a loop, so none of them has a shape to generate. Kubb resolves them to `unknown`.",
|
|
642
|
+
fix: "Break the loop by giving one of the schemas a real definition, or remove the `$ref` that closes it."
|
|
643
|
+
},
|
|
644
|
+
deprecated: {
|
|
645
|
+
code: "KUBB_DEPRECATED",
|
|
646
|
+
title: "Deprecated",
|
|
647
|
+
cause: "A referenced schema or operation is marked `deprecated`.",
|
|
648
|
+
fix: "Migrate off the deprecated definition if the warning is unwanted."
|
|
649
|
+
},
|
|
650
|
+
adapterRequired: {
|
|
651
|
+
code: "KUBB_ADAPTER_REQUIRED",
|
|
652
|
+
title: "Adapter required",
|
|
653
|
+
cause: "An action needs an adapter but none is configured.",
|
|
654
|
+
fix: "Set `adapter` in kubb.config.ts, for example `adapterOas()`."
|
|
655
|
+
},
|
|
656
|
+
pathTraversal: {
|
|
657
|
+
code: "KUBB_PATH_TRAVERSAL",
|
|
658
|
+
title: "Path traversal",
|
|
659
|
+
cause: "A resolved output path escaped the output directory, which can stem from a path traversal in the spec or a misconfigured `group.name`.",
|
|
660
|
+
fix: "Keep generated paths within the output directory. Review the `group.name` function and the names coming from the spec."
|
|
661
|
+
},
|
|
662
|
+
cleanRoot: {
|
|
663
|
+
code: "KUBB_CLEAN_ROOT",
|
|
664
|
+
title: "Clean targets the project root",
|
|
665
|
+
cause: "`output.clean` is enabled and `output.path` resolves to the project root or a parent of it, so cleaning would delete `kubb.config` and every source file.",
|
|
666
|
+
fix: "Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code, or disable `output.clean`."
|
|
667
|
+
},
|
|
668
|
+
invalidPluginOptions: {
|
|
669
|
+
code: "KUBB_INVALID_PLUGIN_OPTIONS",
|
|
670
|
+
title: "Invalid plugin options",
|
|
671
|
+
cause: "A plugin was configured with options that cannot be honored, for example `output.mode: 'file'` paired with a `group` option.",
|
|
672
|
+
fix: "Fix the plugin options. A single-file output has nothing to group, so remove the `group` option or use `output.mode: 'directory'`."
|
|
673
|
+
},
|
|
674
|
+
postGenerateFailed: {
|
|
675
|
+
code: "KUBB_POST_GENERATE_FAILED",
|
|
676
|
+
title: "Post-generate command failed",
|
|
677
|
+
cause: "A post-generate command (`output.postGenerate`) exited with a non-zero status.",
|
|
678
|
+
fix: "Check the command is installed and correct, and run it manually to see the error."
|
|
679
|
+
},
|
|
680
|
+
formatFailed: {
|
|
681
|
+
code: "KUBB_FORMAT_FAILED",
|
|
682
|
+
title: "Format failed",
|
|
683
|
+
cause: "The formatter pass over the generated files failed.",
|
|
684
|
+
fix: "Check the formatter (oxfmt, biome, or prettier) is installed and its config is valid, then run it manually on the output."
|
|
685
|
+
},
|
|
686
|
+
lintFailed: {
|
|
687
|
+
code: "KUBB_LINT_FAILED",
|
|
688
|
+
title: "Lint failed",
|
|
689
|
+
cause: "The linter pass over the generated files failed.",
|
|
690
|
+
fix: "Check the linter (oxlint, biome, or eslint) is installed and its config is valid, then run it manually on the output."
|
|
691
|
+
},
|
|
692
|
+
barrelDuplicateExport: {
|
|
693
|
+
code: "KUBB_BARREL_DUPLICATE_EXPORT",
|
|
694
|
+
title: "Duplicate barrel export",
|
|
695
|
+
cause: "Two generated modules export the same name, so the barrel cannot re-export both.",
|
|
696
|
+
fix: "Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names."
|
|
697
|
+
},
|
|
698
|
+
inlineFailed: {
|
|
699
|
+
code: "KUBB_INLINE_FAILED",
|
|
700
|
+
title: "Inline definition failed",
|
|
701
|
+
cause: "A file imports a name from a file whose sources are all inline, and that name could not be inlined.",
|
|
702
|
+
fix: "Give every name the file imports an inline definition, register a parser with inline support for its extension, or stop marking the source as inline."
|
|
703
|
+
},
|
|
704
|
+
internalError: {
|
|
705
|
+
code: "KUBB_INTERNAL_ERROR",
|
|
706
|
+
title: "Internal error",
|
|
707
|
+
cause: "Kubb hit a state it does not expect. This is a bug in Kubb, not in your config.",
|
|
708
|
+
fix: "Rerun with `--reporter json` or `--verbose` to get the stack. Then report it at https://github.com/kubb-labs/kubb/issues with the spec and config that trigger it."
|
|
709
|
+
},
|
|
710
|
+
performance: {
|
|
711
|
+
code: "KUBB_PERFORMANCE",
|
|
712
|
+
title: "Performance",
|
|
713
|
+
cause: "Not a failure. Records a plugin’s elapsed time, summed into the run total.",
|
|
714
|
+
fix: "No action. This is an informational metric."
|
|
715
|
+
},
|
|
716
|
+
updateAvailable: {
|
|
717
|
+
code: "KUBB_UPDATE_AVAILABLE",
|
|
718
|
+
title: "Update available",
|
|
719
|
+
cause: "A newer Kubb version is published on npm than the one running.",
|
|
720
|
+
fix: "Update the `@kubb/*` packages, for example `npm install -g @kubb/cli`, to get the latest fixes."
|
|
721
|
+
}
|
|
722
|
+
};
|
|
723
|
+
/**
|
|
724
|
+
* Stable codes Kubb attaches to a `Diagnostic`, derived from {@link diagnosticCatalog}. Reference
|
|
725
|
+
* these instead of inlining the string at a throw site.
|
|
726
|
+
*/
|
|
727
|
+
const diagnosticCode = Object.fromEntries(Object.entries(diagnosticCatalog).map(([key, { code }]) => [key, code]));
|
|
728
|
+
// src/formatDiagnostic.ts
|
|
729
|
+
/** A problem's `help`, or the catalog fix. `info` gets none: its catalog fix says no action is needed. */
|
|
730
|
+
function getHelp(problem) {
|
|
731
|
+
if (problem.help || problem.severity === "info") return problem.help;
|
|
732
|
+
return Diagnostics.explain(problem.code).fix;
|
|
733
|
+
}
|
|
734
|
+
/** The `cause` chain's messages, outermost first, minus those `message` already contains. */
|
|
735
|
+
function getCauses(problem) {
|
|
736
|
+
return getErrorChain(problem.cause).filter((error) => !problem.message.includes(error.message)).map((error) => error.name === "Error" ? error.message : `${error.name}: ${error.message}`);
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Accent color per severity, which paints the icon in the `human` layout (red error, yellow
|
|
740
|
+
* warning, blue info). The code itself stays dim.
|
|
741
|
+
*/
|
|
742
|
+
const severityStyle = {
|
|
743
|
+
error: "red",
|
|
744
|
+
warning: "yellow",
|
|
745
|
+
info: "blue"
|
|
746
|
+
};
|
|
747
|
+
const severityIcon = {
|
|
748
|
+
error: "✖",
|
|
749
|
+
warning: "⚠",
|
|
750
|
+
info: "ℹ"
|
|
751
|
+
};
|
|
752
|
+
/**
|
|
753
|
+
* Codes for a crash, which carry the root cause's stack.
|
|
754
|
+
*/
|
|
755
|
+
const crashCodes = /* @__PURE__ */ new Set([
|
|
756
|
+
diagnosticCode.unknown,
|
|
757
|
+
diagnosticCode.internalError,
|
|
758
|
+
diagnosticCode.pluginFailed,
|
|
759
|
+
diagnosticCode.adapterFailed,
|
|
760
|
+
diagnosticCode.parserFailed
|
|
761
|
+
]);
|
|
762
|
+
/**
|
|
763
|
+
* Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable
|
|
764
|
+
* consumers, with the catalog `title`, `cause`, and fix, and the `cause` error as `causes` and
|
|
765
|
+
* `stack`. Absent optional fields are omitted.
|
|
766
|
+
*/
|
|
767
|
+
function serialize(diagnostic) {
|
|
768
|
+
const problem = Diagnostics.isProblem(diagnostic) ? diagnostic : void 0;
|
|
769
|
+
const doc = problem ? Diagnostics.explain(problem.code) : void 0;
|
|
770
|
+
const help = problem ? getHelp(problem) : void 0;
|
|
771
|
+
const causes = problem ? getCauses(problem) : [];
|
|
772
|
+
const stack = problem && crashCodes.has(problem.code) ? getErrorChain(problem.cause).at(-1)?.stack : void 0;
|
|
773
|
+
return {
|
|
774
|
+
code: diagnostic.code,
|
|
775
|
+
severity: diagnostic.severity,
|
|
776
|
+
message: diagnostic.message,
|
|
777
|
+
...doc ? {
|
|
778
|
+
title: doc.title,
|
|
779
|
+
cause: doc.cause
|
|
780
|
+
} : {},
|
|
781
|
+
...problem?.location ? { location: problem.location } : {},
|
|
782
|
+
...help ? { help } : {},
|
|
783
|
+
...problem?.plugin ? { plugin: problem.plugin } : {},
|
|
784
|
+
...problem?.issues ? { issues: problem.issues } : {},
|
|
785
|
+
...causes.length ? { causes } : {},
|
|
786
|
+
...stack ? { stack } : {},
|
|
787
|
+
...diagnostic.code === diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Renders a {@link Diagnostic} as lines: a headline, then indented detail rows. `agent` (the default)
|
|
792
|
+
* prints uncolored labeled rows (`at:`, `why:`, `fix:`, `caused by:`, `stack:` for a crash,
|
|
793
|
+
* `docs:`, `report:`). `human` prints an icon, the bold message, and the code aligned to `width`,
|
|
794
|
+
* with `at`, `fix`, the first cause, and `Learn more` for an error, and one row for a warning.
|
|
795
|
+
* `verbose` adds the full stack.
|
|
796
|
+
*/
|
|
797
|
+
function format(diagnostic, { audience = "agent", verbose = false, width = 0, position } = {}) {
|
|
798
|
+
const { code, severity, message } = diagnostic;
|
|
799
|
+
const problem = Diagnostics.isProblem(diagnostic) ? diagnostic : void 0;
|
|
800
|
+
const human = audience === "human";
|
|
801
|
+
const paint = human ? styleText : (_format, text) => text;
|
|
802
|
+
const [firstLine = "", ...rest] = message.split("\n");
|
|
803
|
+
const pointer = problem?.location && "pointer" in problem.location ? problem.location.pointer : void 0;
|
|
804
|
+
const at = position ? `${position.file}:${position.line}:${position.column}` : void 0;
|
|
805
|
+
const where = at ?? pointer;
|
|
806
|
+
const help = problem ? getHelp(problem) : void 0;
|
|
807
|
+
const causes = problem ? getCauses(problem) : [];
|
|
808
|
+
const crash = problem ? crashCodes.has(problem.code) : false;
|
|
809
|
+
const frames = (problem && (verbose || !human && crash) ? getErrorChain(problem.cause).at(-1)?.stack : void 0)?.split("\n").slice(1, verbose ? void 0 : 4).map((frame) => ` ${paint("dim", frame.trim())}`);
|
|
810
|
+
if (!human) {
|
|
811
|
+
const details = rest.filter((line) => line.trim()).map((line) => ` ${line}`);
|
|
812
|
+
const row = (label, value) => {
|
|
813
|
+
if (value) details.push(` ${label}: ${value}`);
|
|
814
|
+
};
|
|
815
|
+
row("at", at && pointer ? `${at} (${pointer})` : pointer);
|
|
816
|
+
if (problem && severity !== "info") row("why", Diagnostics.explain(problem.code).cause);
|
|
817
|
+
row("fix", help);
|
|
818
|
+
for (const cause of causes) row("caused by", cause);
|
|
819
|
+
if (frames?.length) details.push(" stack:", ...frames);
|
|
820
|
+
if (code !== diagnosticCode.unknown) row("docs", Diagnostics.docsUrl(code));
|
|
821
|
+
row("report", problem?.issues);
|
|
822
|
+
return [`${severity} ${code}${problem?.plugin ? ` [${problem.plugin}]` : ""}: ${firstLine}`, ...details];
|
|
823
|
+
}
|
|
824
|
+
const left = `${paint(severityStyle[severity], severityIcon[severity])} ${paint("bold", firstLine)}`;
|
|
825
|
+
const gap = width - stripVTControlCharacters(left).length - code.length;
|
|
826
|
+
const headline = width && gap < 2 ? [left, `${" ".repeat(Math.max(0, width - code.length))}${paint("dim", code)}`] : [`${left}${" ".repeat(Math.max(2, gap))}${paint("dim", code)}`];
|
|
827
|
+
const frame = rest.filter((line) => line.trim()).map((line) => ` ${paint("dim", line)}`);
|
|
828
|
+
const label = (name) => paint("dim", name.length < 4 ? name.padEnd(4) : `${name} `);
|
|
829
|
+
const rows = [["at", where && paint("cyan", where)], ["fix", help]];
|
|
830
|
+
if (severity !== "error") {
|
|
831
|
+
const first = rows.find(([, value]) => value);
|
|
832
|
+
return [
|
|
833
|
+
...headline,
|
|
834
|
+
...frame,
|
|
835
|
+
...first ? [` ${label(first[0])} ${first[1]}`] : []
|
|
836
|
+
];
|
|
837
|
+
}
|
|
838
|
+
rows.push(["caused by", causes[0]], ["report", problem?.issues && paint("cyan", problem.issues)]);
|
|
839
|
+
const codeFrame = (position?.frame ?? []).map((line) => ` ${line}`);
|
|
840
|
+
const details = [...frame, ...rows.flatMap(([name, value]) => value ? [` ${label(name)} ${value}`, ...name === "at" ? codeFrame : []] : [])];
|
|
841
|
+
if (frames?.length) details.push(` ${paint("dim", "stack")}`, ...frames);
|
|
842
|
+
if (code !== diagnosticCode.unknown) details.push(` ${paint("dim", "↳ Learn more")} ${paint("cyan", Diagnostics.docsUrl(code).replace(/^https:\/\//, ""))}`);
|
|
843
|
+
return [...headline, ...details];
|
|
844
|
+
}
|
|
845
|
+
// src/Diagnostics.ts
|
|
846
|
+
/**
|
|
847
|
+
* Docs major version, derived from the package version so the link tracks the published major.
|
|
848
|
+
*/
|
|
849
|
+
const docsMajor = version.split(".")[0] ?? "5";
|
|
850
|
+
/**
|
|
851
|
+
* Builds a type guard that narrows a {@link Diagnostic} to the variant for `kind`. A diagnostic
|
|
852
|
+
* with no `kind` is treated as a `problem`.
|
|
853
|
+
*/
|
|
854
|
+
function isKind(kind) {
|
|
855
|
+
return (diagnostic) => (diagnostic.kind ?? "problem") === kind;
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Returns `true` when the diagnostic is a build {@link ProblemDiagnostic}.
|
|
859
|
+
*
|
|
860
|
+
* @example
|
|
861
|
+
* ```ts
|
|
862
|
+
* if (isProblem(diagnostic)) {
|
|
863
|
+
* console.log(diagnostic.location)
|
|
864
|
+
* }
|
|
865
|
+
* ```
|
|
866
|
+
*/
|
|
867
|
+
const isProblem = isKind("problem");
|
|
868
|
+
/**
|
|
869
|
+
* Returns `true` when the diagnostic is a per-plugin {@link PerformanceDiagnostic}.
|
|
870
|
+
*
|
|
871
|
+
* @example
|
|
872
|
+
* ```ts
|
|
873
|
+
* const timings = diagnostics.filter(isPerformance)
|
|
874
|
+
* ```
|
|
875
|
+
*/
|
|
876
|
+
const isPerformance = isKind("performance");
|
|
877
|
+
/**
|
|
878
|
+
* Returns `true` when the diagnostic is a version-update {@link UpdateDiagnostic}.
|
|
879
|
+
*
|
|
880
|
+
* @example
|
|
881
|
+
* ```ts
|
|
882
|
+
* if (isUpdate(diagnostic)) {
|
|
883
|
+
* console.log(diagnostic.latestVersion)
|
|
884
|
+
* }
|
|
885
|
+
* ```
|
|
886
|
+
*/
|
|
887
|
+
const isUpdate = isKind("update");
|
|
888
|
+
const failedCode = {
|
|
889
|
+
plugin: diagnosticCode.pluginFailed,
|
|
890
|
+
adapter: diagnosticCode.adapterFailed,
|
|
891
|
+
parser: diagnosticCode.parserFailed
|
|
892
|
+
};
|
|
893
|
+
const docsByCode = new Map(Object.values(diagnosticCatalog).map((doc) => [doc.code, doc]));
|
|
894
|
+
const reporterKey = Symbol.for("kubb.diagnostics.reporter");
|
|
895
|
+
const countKey = {
|
|
896
|
+
error: "errors",
|
|
897
|
+
warning: "warnings",
|
|
898
|
+
info: "infos"
|
|
899
|
+
};
|
|
900
|
+
/**
|
|
901
|
+
* Static helpers for working with {@link Diagnostic}s, plus the run-scoped sink
|
|
902
|
+
* that lets deep code report a diagnostic without threading a callback.
|
|
903
|
+
*
|
|
904
|
+
* The sink lives in a single `AsyncLocalStorage` on `globalThis`, shared by every copy of `@kubb/core`.
|
|
905
|
+
* `Diagnostics.scope` activates it for a run, so anything inside that run (the
|
|
906
|
+
* adapter parse, a generator) reports through `Diagnostics.report` and lands
|
|
907
|
+
* in the same run.
|
|
908
|
+
*/
|
|
909
|
+
var Diagnostics = class Diagnostics {
|
|
910
|
+
static #reporterStorage = globalThis[reporterKey] ??= new AsyncLocalStorage();
|
|
911
|
+
/**
|
|
912
|
+
* The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).
|
|
913
|
+
*/
|
|
914
|
+
static code = diagnosticCode;
|
|
915
|
+
/**
|
|
916
|
+
* Type guard for a build {@link ProblemDiagnostic}.
|
|
917
|
+
*/
|
|
918
|
+
static isProblem = isProblem;
|
|
919
|
+
/**
|
|
920
|
+
* Type guard for a version-update {@link UpdateDiagnostic}.
|
|
921
|
+
*/
|
|
922
|
+
static isUpdate = isUpdate;
|
|
923
|
+
/**
|
|
924
|
+
* Type guard for a per-plugin {@link PerformanceDiagnostic}.
|
|
925
|
+
*/
|
|
926
|
+
static isPerformance = isPerformance;
|
|
927
|
+
/**
|
|
928
|
+
* An `Error` that carries a {@link Diagnostic}, so structured problems can flow
|
|
929
|
+
* through the existing throw/catch paths while keeping their code and location.
|
|
930
|
+
*
|
|
931
|
+
* @example
|
|
932
|
+
* ```ts
|
|
933
|
+
* throw new Diagnostics.Error({ code: diagnosticCode.refNotFound, severity: 'error', message: `Could not find ${ref}`, location: { kind: 'schema', pointer: ref, ref } })
|
|
934
|
+
* ```
|
|
935
|
+
*/
|
|
936
|
+
static Error = class DiagnosticError extends Error {
|
|
937
|
+
diagnostic;
|
|
938
|
+
constructor(diagnostic) {
|
|
939
|
+
super(diagnostic.message, { cause: diagnostic.cause });
|
|
940
|
+
this.name = "DiagnosticError";
|
|
941
|
+
this.diagnostic = diagnostic;
|
|
942
|
+
}
|
|
943
|
+
};
|
|
944
|
+
/**
|
|
945
|
+
* Structural check for a {@link Diagnostics.Error}, including one thrown from a duplicated
|
|
946
|
+
* `@kubb/core` copy where `instanceof` fails. Matches on the `name` and a `diagnostic`
|
|
947
|
+
* that carries a `code`.
|
|
948
|
+
*/
|
|
949
|
+
static isError(error) {
|
|
950
|
+
if (error instanceof Diagnostics.Error) return true;
|
|
951
|
+
if (!(error instanceof Error) || error.name !== "DiagnosticError") return false;
|
|
952
|
+
const { diagnostic } = error;
|
|
953
|
+
return typeof diagnostic === "object" && diagnostic !== null && typeof diagnostic.code === "string";
|
|
954
|
+
}
|
|
955
|
+
/**
|
|
956
|
+
* Runs `fn` with `sink` as the active diagnostic sink for the whole async
|
|
957
|
+
* subtree, so {@link Diagnostics.report} reaches it from anywhere inside.
|
|
958
|
+
*/
|
|
959
|
+
static scope(sink, fn) {
|
|
960
|
+
return Diagnostics.#reporterStorage.run(sink, fn);
|
|
961
|
+
}
|
|
962
|
+
/**
|
|
963
|
+
* Collects a diagnostic into the active build via the run-scoped sink, without throwing.
|
|
964
|
+
* Returns `true` when a run consumed it, `false` when called outside a {@link Diagnostics.scope}
|
|
965
|
+
* (so callers can fall back to throwing). Use a `warning`/`info` severity for non-fatal issues.
|
|
966
|
+
* For rendering a diagnostic live on the hook bus, use {@link Diagnostics.emit} instead.
|
|
967
|
+
*/
|
|
968
|
+
static report(diagnostic) {
|
|
969
|
+
const sink = Diagnostics.#reporterStorage.getStore();
|
|
970
|
+
if (!sink) return false;
|
|
971
|
+
sink(diagnostic);
|
|
972
|
+
return true;
|
|
973
|
+
}
|
|
974
|
+
/**
|
|
975
|
+
* Emits a diagnostic, or any thrown value, on the run's hooks so the loggers render it live.
|
|
976
|
+
* A coded problem or an update goes to `kubb:diagnostic`. An uncoded one goes to `kubb:error`
|
|
977
|
+
* whole, so every wrapper's message, its help, and the stack survive. To collect a diagnostic into
|
|
978
|
+
* the build result from deep in a run, use {@link Diagnostics.report} instead.
|
|
979
|
+
*/
|
|
980
|
+
static async emit(hooks, value) {
|
|
981
|
+
const thrown = value instanceof Error || typeof value?.code !== "string";
|
|
982
|
+
const diagnostic = thrown ? Diagnostics.from(value) : value;
|
|
983
|
+
if (!isProblem(diagnostic) || diagnostic.code !== diagnosticCode.unknown) {
|
|
984
|
+
await hooks.callHook("kubb:diagnostic", { diagnostic });
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
const { cause, help, message } = diagnostic;
|
|
988
|
+
const bare = cause && !help && cause.message === message;
|
|
989
|
+
await hooks.callHook("kubb:error", { error: thrown ? toError(value) : bare ? cause : new Diagnostics.Error(diagnostic) });
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* Coerces any thrown value into a {@link ProblemDiagnostic}. A {@link Diagnostics.Error}
|
|
993
|
+
* keeps its structured data, and anything else becomes a `KUBB_UNKNOWN` error.
|
|
994
|
+
*/
|
|
995
|
+
static from(error) {
|
|
996
|
+
const chain = getErrorChain(error);
|
|
997
|
+
const coded = chain.findLast((current) => Diagnostics.isError(current));
|
|
998
|
+
if (coded) {
|
|
999
|
+
const { diagnostic } = coded;
|
|
1000
|
+
return diagnostic.cause || !crashCodes.has(diagnostic.code) ? diagnostic : {
|
|
1001
|
+
...diagnostic,
|
|
1002
|
+
cause: coded
|
|
1003
|
+
};
|
|
1004
|
+
}
|
|
1005
|
+
const root = chain.at(-1);
|
|
1006
|
+
return {
|
|
1007
|
+
code: diagnosticCode.unknown,
|
|
1008
|
+
severity: "error",
|
|
1009
|
+
message: root ? root.message : getErrorMessage(error),
|
|
1010
|
+
cause: root
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
/**
|
|
1014
|
+
* Coerces an error thrown by a plugin, adapter, or parser into a diagnostic attributed to it.
|
|
1015
|
+
* A structured {@link Diagnostics.Error} keeps its code. Any other error is a crash: it gets the
|
|
1016
|
+
* kind's `*_FAILED` code and the extension's `meta.issues` link, so the user reports it to the
|
|
1017
|
+
* extension's maintainers instead of to Kubb.
|
|
1018
|
+
*/
|
|
1019
|
+
static fromExtension(error, { kind, extension }) {
|
|
1020
|
+
const diagnostic = Diagnostics.from(error);
|
|
1021
|
+
const name = extension.meta?.name ?? extension.name;
|
|
1022
|
+
const owner = kind === "plugin" ? { plugin: diagnostic.plugin ?? name } : {};
|
|
1023
|
+
const crashed = diagnostic.code === diagnosticCode.unknown && diagnostic.cause?.name !== "AbortError";
|
|
1024
|
+
const failed = Object.values(failedCode).includes(diagnostic.code);
|
|
1025
|
+
if (!crashed && !failed) return {
|
|
1026
|
+
...diagnostic,
|
|
1027
|
+
...owner
|
|
1028
|
+
};
|
|
1029
|
+
const issues = extension.meta?.issues;
|
|
1030
|
+
return {
|
|
1031
|
+
...diagnostic,
|
|
1032
|
+
...owner,
|
|
1033
|
+
code: crashed ? failedCode[kind] : diagnostic.code,
|
|
1034
|
+
message: crashed && kind !== "plugin" ? `${kind} "${name}" crashed: ${diagnostic.message}` : diagnostic.message,
|
|
1035
|
+
...issues ? { issues } : {}
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
/**
|
|
1039
|
+
* Builds a per-plugin performance record. Reporters sum these into the run total.
|
|
1040
|
+
*/
|
|
1041
|
+
static performance({ plugin, duration }) {
|
|
1042
|
+
return {
|
|
1043
|
+
kind: "performance",
|
|
1044
|
+
code: diagnosticCode.performance,
|
|
1045
|
+
severity: "info",
|
|
1046
|
+
message: `${plugin} generated in ${Math.round(duration)}ms`,
|
|
1047
|
+
plugin,
|
|
1048
|
+
duration
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
/**
|
|
1052
|
+
* Builds the version-update notice shown when a newer Kubb is published on npm.
|
|
1053
|
+
*/
|
|
1054
|
+
static update({ currentVersion, latestVersion }) {
|
|
1055
|
+
return {
|
|
1056
|
+
kind: "update",
|
|
1057
|
+
code: diagnosticCode.updateAvailable,
|
|
1058
|
+
severity: "info",
|
|
1059
|
+
message: `Update available: v${currentVersion} → v${latestVersion}. Run \`npm install -g @kubb/cli\` to update.`,
|
|
1060
|
+
currentVersion,
|
|
1061
|
+
latestVersion
|
|
1062
|
+
};
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* True when any diagnostic is an error, the severity that fails a build. Non-error
|
|
1066
|
+
* diagnostics are ignored.
|
|
1067
|
+
*/
|
|
1068
|
+
static hasError(diagnostics) {
|
|
1069
|
+
return diagnostics.some((diagnostic) => diagnostic.severity === "error");
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* Names of the plugins that failed, deduped, derived from the error diagnostics
|
|
1073
|
+
* that carry a `plugin`.
|
|
1074
|
+
*/
|
|
1075
|
+
static failedPlugins(diagnostics) {
|
|
1076
|
+
return [...new Set(diagnostics.flatMap((diagnostic) => diagnostic.severity === "error" && diagnostic.plugin ? [diagnostic.plugin] : []))];
|
|
1077
|
+
}
|
|
1078
|
+
/**
|
|
1079
|
+
* Counts `problem` diagnostics by severity for the run summary. `performance` and
|
|
1080
|
+
* `update` diagnostics are ignored.
|
|
1081
|
+
*/
|
|
1082
|
+
static count(diagnostics) {
|
|
1083
|
+
const counts = {
|
|
1084
|
+
errors: 0,
|
|
1085
|
+
warnings: 0,
|
|
1086
|
+
infos: 0
|
|
1087
|
+
};
|
|
1088
|
+
for (const diagnostic of diagnostics.filter(isProblem)) counts[countKey[diagnostic.severity]] += 1;
|
|
1089
|
+
return counts;
|
|
1090
|
+
}
|
|
1091
|
+
/**
|
|
1092
|
+
* Drops duplicate `problem` diagnostics that share a code, location pointer, and
|
|
1093
|
+
* plugin, so the same issue reported across several passes is shown once. Non-problem
|
|
1094
|
+
* diagnostics are always kept.
|
|
1095
|
+
*/
|
|
1096
|
+
static dedupe(diagnostics) {
|
|
1097
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1098
|
+
return diagnostics.filter((diagnostic) => {
|
|
1099
|
+
if (!isProblem(diagnostic)) return true;
|
|
1100
|
+
const pointer = diagnostic.location && "pointer" in diagnostic.location ? diagnostic.location.pointer : "";
|
|
1101
|
+
const key = `${diagnostic.code} ${pointer} ${diagnostic.plugin ?? ""}`;
|
|
1102
|
+
if (seen.has(key)) return false;
|
|
1103
|
+
seen.add(key);
|
|
1104
|
+
return true;
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* Builds the kubb.dev docs URL for a diagnostic code, e.g.
|
|
1109
|
+
* `KUBB_REF_NOT_FOUND` → `https://kubb.dev/docs/5.x/reference/diagnostics#kubb-ref-not-found`.
|
|
1110
|
+
*/
|
|
1111
|
+
static docsUrl(code) {
|
|
1112
|
+
const slug = code.toLowerCase().replaceAll("_", "-");
|
|
1113
|
+
return `https://kubb.dev/docs/${docsMajor}.x/reference/diagnostics#${slug}`;
|
|
1114
|
+
}
|
|
1115
|
+
/**
|
|
1116
|
+
* The catalog entry for a code: its title, cause, and fix. Mirrors the kubb.dev
|
|
1117
|
+
* `/reference/diagnostics#<slug>` section.
|
|
1118
|
+
*/
|
|
1119
|
+
static explain(code) {
|
|
1120
|
+
return docsByCode.get(code);
|
|
1121
|
+
}
|
|
1122
|
+
/**
|
|
1123
|
+
* Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable
|
|
1124
|
+
* consumers, with the catalog `title`, `cause`, and fix, and the `cause` error as `causes` and
|
|
1125
|
+
* `stack`. Absent optional fields are omitted.
|
|
1126
|
+
*/
|
|
1127
|
+
static serialize = serialize;
|
|
1128
|
+
/**
|
|
1129
|
+
* Renders a diagnostic as lines for an `agent` (the default) or a `human`. See {@link format}.
|
|
1130
|
+
*/
|
|
1131
|
+
static format = format;
|
|
1132
|
+
};
|
|
1133
|
+
// src/defineExtension.ts
|
|
1134
|
+
/**
|
|
1135
|
+
* Returns `meta`, or `{ name }` for an extension that only sets the deprecated `name`. Throws `KUBB_INVALID_PLUGIN_OPTIONS` when it has neither.
|
|
1136
|
+
*/
|
|
1137
|
+
function resolveMeta(extension) {
|
|
1138
|
+
const { name, meta } = extension;
|
|
1139
|
+
if (meta) return meta;
|
|
1140
|
+
if (name) return { name };
|
|
1141
|
+
const keys = Object.keys(extension);
|
|
1142
|
+
throw new Diagnostics.Error({
|
|
1143
|
+
code: Diagnostics.code.invalidPluginOptions,
|
|
1144
|
+
severity: "error",
|
|
1145
|
+
message: `An extension has neither \`meta.name\` nor \`name\`. Received keys: ${keys.length ? keys.join(", ") : "none"}.`,
|
|
1146
|
+
help: "Set `meta: { name }` on the plugin or parser.",
|
|
1147
|
+
location: { kind: "config" }
|
|
1148
|
+
});
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* Throws `KUBB_INCOMPATIBLE_EXTENSION` when the running Kubb or Node.js version is outside `meta.compatibility`.
|
|
1152
|
+
*/
|
|
1153
|
+
function checkCompatibility(meta) {
|
|
1154
|
+
const checks = [{
|
|
1155
|
+
target: "Kubb",
|
|
1156
|
+
range: version.startsWith("0.0.0-") ? void 0 : meta.compatibility?.kubb,
|
|
1157
|
+
version
|
|
1158
|
+
}, {
|
|
1159
|
+
target: "Node.js",
|
|
1160
|
+
range: meta.compatibility?.node,
|
|
1161
|
+
version: process.versions.node
|
|
1162
|
+
}];
|
|
1163
|
+
for (const { target, range, version } of checks) {
|
|
1164
|
+
if (!range || satisfies(version, range, { includePrerelease: true })) continue;
|
|
1165
|
+
throw new Diagnostics.Error({
|
|
1166
|
+
code: Diagnostics.code.incompatibleExtension,
|
|
1167
|
+
severity: "error",
|
|
1168
|
+
message: `"${meta.name}" requires ${target} ${range}, but ${version} is running.`,
|
|
1169
|
+
help: `Use a ${target} version that satisfies ${range}, or a version of "${meta.name}" that supports ${target} ${version}.`,
|
|
1170
|
+
location: { kind: "config" },
|
|
1171
|
+
plugin: meta.name
|
|
1172
|
+
});
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* Throws `KUBB_MISSING_DEPENDENCY` for a missing required entry in a `dependencies` record, and
|
|
1177
|
+
* `KUBB_INCOMPATIBLE_DEPENDENCY` when an entry's `meta.version` is out of range. Arrays are not checked.
|
|
1178
|
+
*/
|
|
1179
|
+
function checkDependencies({ name, dependencies, plugins }) {
|
|
1180
|
+
if (!dependencies || Array.isArray(dependencies)) return;
|
|
1181
|
+
for (const [dependencyName, dependency] of Object.entries(dependencies)) {
|
|
1182
|
+
const target = plugins.get(dependencyName);
|
|
1183
|
+
if (!target) {
|
|
1184
|
+
if (dependency?.optional) continue;
|
|
1185
|
+
throw new Diagnostics.Error({
|
|
1186
|
+
code: Diagnostics.code.missingDependency,
|
|
1187
|
+
severity: "error",
|
|
1188
|
+
message: `Plugin "${dependencyName}" is required by "${name}" but not found.`,
|
|
1189
|
+
help: `Add "${dependencyName}" to the \`plugins\` array in kubb.config.ts.`,
|
|
1190
|
+
location: { kind: "config" },
|
|
1191
|
+
plugin: name
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
const range = dependency?.version;
|
|
1195
|
+
const version = target.meta?.version;
|
|
1196
|
+
if (!range || !version || satisfies(version, range, { includePrerelease: true })) continue;
|
|
1197
|
+
throw new Diagnostics.Error({
|
|
1198
|
+
code: Diagnostics.code.incompatibleDependency,
|
|
1199
|
+
severity: "error",
|
|
1200
|
+
message: `"${name}" requires "${dependencyName}" ${range}, but ${version} is configured.`,
|
|
1201
|
+
help: `Install a version of "${dependencyName}" that satisfies ${range}.`,
|
|
1202
|
+
location: { kind: "config" },
|
|
1203
|
+
plugin: name
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
/**
|
|
1208
|
+
* Builds the factory behind `defineExtension`. It passes `{}` when called without options, and carries `kind` and
|
|
1209
|
+
* `meta` so tools can read them without calling it.
|
|
1210
|
+
*
|
|
1211
|
+
* @internal
|
|
1212
|
+
*/
|
|
1213
|
+
function createExtensionFactory({ kind, meta, build }) {
|
|
1214
|
+
return Object.assign((options = {}) => build(options), {
|
|
1215
|
+
kind,
|
|
1216
|
+
meta
|
|
1217
|
+
});
|
|
1218
|
+
}
|
|
1219
|
+
function defineExtension(definition) {
|
|
1220
|
+
switch (definition.kind) {
|
|
1221
|
+
case "plugin": {
|
|
1222
|
+
const { meta, dependencies, enforce, hooks = {}, setup } = definition;
|
|
1223
|
+
return createExtensionFactory({
|
|
1224
|
+
kind: "plugin",
|
|
1225
|
+
meta,
|
|
1226
|
+
build: (options) => ({
|
|
1227
|
+
name: meta.name,
|
|
1228
|
+
meta,
|
|
1229
|
+
options,
|
|
1230
|
+
dependencies,
|
|
1231
|
+
enforce,
|
|
1232
|
+
hooks,
|
|
1233
|
+
setup
|
|
1234
|
+
})
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
case "adapter": {
|
|
1238
|
+
const { meta, setup, build } = definition;
|
|
1239
|
+
return createExtensionFactory({
|
|
1240
|
+
kind: "adapter",
|
|
1241
|
+
meta,
|
|
1242
|
+
build: (raw) => {
|
|
1243
|
+
const options = setup ? setup(raw) : raw;
|
|
1244
|
+
return Object.assign(build(options), {
|
|
1245
|
+
name: meta.name,
|
|
1246
|
+
meta,
|
|
1247
|
+
options: raw
|
|
1248
|
+
});
|
|
1249
|
+
}
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
case "parser": {
|
|
1253
|
+
const { meta, build } = definition;
|
|
1254
|
+
return createExtensionFactory({
|
|
1255
|
+
kind: "parser",
|
|
1256
|
+
meta,
|
|
1257
|
+
build: (options) => ({
|
|
1258
|
+
...build(options),
|
|
1259
|
+
name: meta.name,
|
|
1260
|
+
meta,
|
|
1261
|
+
options
|
|
1262
|
+
})
|
|
1263
|
+
});
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
// src/createAdapter.ts
|
|
1268
|
+
/**
|
|
1269
|
+
* Defines a custom adapter that translates a spec format into Kubb's universal
|
|
1270
|
+
* AST, for example GraphQL, gRPC, or AsyncAPI. The built-in `@kubb/adapter-oas`
|
|
1271
|
+
* handles OpenAPI/Swagger documents.
|
|
1272
|
+
*
|
|
1273
|
+
* Adapters must return an `InputNode` from `parse`. That node is what every
|
|
1274
|
+
* plugin in the build consumes.
|
|
1275
|
+
*
|
|
1276
|
+
* @deprecated Use `defineExtension` with `kind: 'adapter'` instead.
|
|
1277
|
+
*/
|
|
1278
|
+
function createAdapter(definition) {
|
|
1279
|
+
return defineExtension({
|
|
1280
|
+
kind: "adapter",
|
|
1281
|
+
...definition
|
|
1282
|
+
});
|
|
1283
|
+
}
|
|
1284
|
+
// src/composables.ts
|
|
1285
|
+
const kubbContextKey = Symbol.for("kubb.context");
|
|
1286
|
+
const host = globalThis;
|
|
1287
|
+
/**
|
|
1288
|
+
* Holds the setup context of the plugin whose `setup` or `kubb:plugin:setup` is running. `KubbDriver` sets it for each plugin.
|
|
1289
|
+
*
|
|
1290
|
+
* The store lives on `globalThis`, so the ESM and CommonJS builds of `@kubb/core` share one. A plugin that a
|
|
1291
|
+
* CommonJS config loads would otherwise read an empty store and fail with `KUBB_NO_CONTEXT`.
|
|
1292
|
+
*/
|
|
1293
|
+
const kubbContext = host[kubbContextKey] ??= new AsyncLocalStorage();
|
|
1294
|
+
function requireContext(caller) {
|
|
1295
|
+
const ctx = kubbContext.getStore();
|
|
1296
|
+
if (ctx) return ctx;
|
|
1297
|
+
throw new Diagnostics.Error({
|
|
1298
|
+
code: Diagnostics.code.noContext,
|
|
1299
|
+
severity: "error",
|
|
1300
|
+
message: `\`${caller}()\` was called outside a plugin setup.`,
|
|
1301
|
+
help: `Call \`${caller}()\` inside \`setup\` or \`kubb:plugin:setup\`, including in code that setup awaits.`
|
|
1302
|
+
});
|
|
1303
|
+
}
|
|
1304
|
+
/**
|
|
1305
|
+
* Returns the context of the plugin whose `kubb:plugin:setup` is running. It stays available after an `await`.
|
|
1306
|
+
* Throws `KUBB_NO_CONTEXT` outside setup.
|
|
1307
|
+
*/
|
|
1308
|
+
function useKubb() {
|
|
1309
|
+
return requireContext("useKubb");
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* Returns the same context as {@link useKubb}, or `undefined` outside `setup` and `kubb:plugin:setup`.
|
|
1313
|
+
*/
|
|
1314
|
+
function tryUseKubb() {
|
|
1315
|
+
return kubbContext.getStore();
|
|
1316
|
+
}
|
|
1317
|
+
/**
|
|
1318
|
+
* Registers generators on the plugin being set up, like `ctx.addGenerator`.
|
|
1319
|
+
*
|
|
1320
|
+
* @example
|
|
1321
|
+
* `addGenerator(typeGenerator, enumGenerator)`
|
|
1322
|
+
*/
|
|
1323
|
+
function addGenerator(...generators) {
|
|
1324
|
+
requireContext("addGenerator").addGenerator(...generators);
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* Sets the resolver of the plugin being set up, like `ctx.setResolver`.
|
|
1328
|
+
*/
|
|
1329
|
+
function setResolver(resolver) {
|
|
1330
|
+
requireContext("setResolver").setResolver(resolver);
|
|
1331
|
+
}
|
|
1332
|
+
/**
|
|
1333
|
+
* Adds a macro to the plugin being set up, like `ctx.addMacro`.
|
|
1334
|
+
*/
|
|
1335
|
+
function addMacro(macro) {
|
|
1336
|
+
requireContext("addMacro").addMacro(macro);
|
|
1337
|
+
}
|
|
1338
|
+
/**
|
|
1339
|
+
* Replaces the macros of the plugin being set up, like `ctx.setMacros`.
|
|
1340
|
+
*/
|
|
1341
|
+
function setMacros(macros) {
|
|
1342
|
+
requireContext("setMacros").setMacros(macros);
|
|
1343
|
+
}
|
|
1344
|
+
/**
|
|
1345
|
+
* Adds a raw file to the build output, like `ctx.injectFile`.
|
|
1346
|
+
*/
|
|
1347
|
+
function injectFile(file) {
|
|
1348
|
+
requireContext("injectFile").injectFile(file);
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Returns a value computed once per build and shared by every plugin, like `ctx.memo`.
|
|
1352
|
+
*/
|
|
1353
|
+
const memo = (key, compute) => requireContext("memo").memo(key, compute);
|
|
1354
|
+
/**
|
|
1355
|
+
* Returns the options the user passed to the plugin being set up, like `ctx.options`.
|
|
1356
|
+
*/
|
|
1357
|
+
function useOptions() {
|
|
1358
|
+
return requireContext("useOptions").options;
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Sets the resolved options of the plugin being set up, like `ctx.setOptions`.
|
|
1362
|
+
*/
|
|
1363
|
+
function setOptions(options) {
|
|
1364
|
+
requireContext("setOptions").setOptions(options);
|
|
1365
|
+
}
|
|
1366
|
+
/**
|
|
1367
|
+
* Returns the resolved build configuration, like `ctx.config`.
|
|
1368
|
+
*/
|
|
1369
|
+
function useConfig() {
|
|
1370
|
+
return requireContext("useConfig").config;
|
|
1371
|
+
}
|
|
1372
|
+
/**
|
|
1373
|
+
* Returns another plugin from the config, typed through `Kubb.PluginRegistry`, like `ctx.requirePlugin`.
|
|
1374
|
+
*/
|
|
1375
|
+
function requirePlugin(name) {
|
|
1376
|
+
return requireContext("requirePlugin").requirePlugin(name);
|
|
1377
|
+
}
|
|
1378
|
+
// src/definePlugin.ts
|
|
1379
|
+
/**
|
|
1380
|
+
* Merges the `output.mode` default into the output config and validates the combination.
|
|
1381
|
+
* Throws `KUBB_INVALID_PLUGIN_OPTIONS` when `mode: 'file'` is paired with a `group` option,
|
|
1382
|
+
* since a single-file output has nothing to group.
|
|
1383
|
+
*
|
|
1384
|
+
* An omitted `mode` follows the shape of `path`: an extension means a single file, anything
|
|
1385
|
+
* else is a directory. Plugin defaults such as `path: 'types'` name a directory, so they
|
|
1386
|
+
* generate without the caller spelling out `mode`.
|
|
1387
|
+
*/
|
|
1388
|
+
function normalizeOutput({ output, group, pluginName }) {
|
|
1389
|
+
const mode = output.mode ?? (path.extname(output.path) ? "file" : "directory");
|
|
1390
|
+
if (mode === "file" && group) throw new Diagnostics.Error({
|
|
1391
|
+
code: Diagnostics.code.invalidPluginOptions,
|
|
1392
|
+
severity: "error",
|
|
1393
|
+
message: `Plugin "${pluginName}" resolves \`output.mode\` to 'file' but also configures a \`group\` option.`,
|
|
1394
|
+
help: "A single-file output has nothing to group. Remove the `group` option, give `output.path` an extensionless directory name, or set `output.mode: 'directory'` explicitly.",
|
|
1395
|
+
location: { kind: "config" },
|
|
1396
|
+
plugin: pluginName
|
|
1397
|
+
});
|
|
1398
|
+
return {
|
|
1399
|
+
...output,
|
|
1400
|
+
mode
|
|
1401
|
+
};
|
|
1402
|
+
}
|
|
1403
|
+
/** Throws `KUBB_INVALID_PLUGIN_OPTIONS`, listing the allowed values, when `value` is not one of `allowed`. */
|
|
1404
|
+
function assertPluginOption({ plugin, option, value, allowed }) {
|
|
1405
|
+
if (allowed.includes(value)) return;
|
|
1406
|
+
const format = (item) => typeof item === "string" ? JSON.stringify(item) : String(item);
|
|
1407
|
+
const expected = allowed.map(format).join(", ");
|
|
1408
|
+
throw new Diagnostics.Error({
|
|
1409
|
+
code: Diagnostics.code.invalidPluginOptions,
|
|
1410
|
+
severity: "error",
|
|
1411
|
+
message: `Plugin "${plugin}" option \`${option}\` is ${format(value)}, but it must be one of ${expected}.`,
|
|
1412
|
+
help: `Set \`${option}\` to one of ${expected}.`,
|
|
1413
|
+
location: { kind: "config" },
|
|
1414
|
+
plugin
|
|
1415
|
+
});
|
|
1416
|
+
}
|
|
1417
|
+
/**
|
|
1418
|
+
* Defines a plugin from one object and returns a factory that takes the user's options.
|
|
1419
|
+
*
|
|
1420
|
+
* @deprecated Use `defineExtension` with `kind: 'plugin'` instead.
|
|
1421
|
+
*/
|
|
1422
|
+
function definePlugin(definition) {
|
|
1423
|
+
return defineExtension({
|
|
1424
|
+
kind: "plugin",
|
|
1425
|
+
...definition
|
|
1426
|
+
});
|
|
1427
|
+
}
|
|
1428
|
+
// src/publicAddress.ts
|
|
1429
|
+
function createBlockList() {
|
|
1430
|
+
const list = new net.BlockList();
|
|
1431
|
+
for (const [address, prefix] of [
|
|
1432
|
+
["0.0.0.0", 8],
|
|
1433
|
+
["10.0.0.0", 8],
|
|
1434
|
+
["100.64.0.0", 10],
|
|
1435
|
+
["127.0.0.0", 8],
|
|
1436
|
+
["169.254.0.0", 16],
|
|
1437
|
+
["172.16.0.0", 12],
|
|
1438
|
+
["192.0.0.0", 24],
|
|
1439
|
+
["192.168.0.0", 16],
|
|
1440
|
+
["198.18.0.0", 15],
|
|
1441
|
+
["224.0.0.0", 3]
|
|
1442
|
+
]) list.addSubnet(address, prefix, "ipv4");
|
|
1443
|
+
for (const [address, prefix] of [
|
|
1444
|
+
["::", 128],
|
|
1445
|
+
["::1", 128],
|
|
1446
|
+
["64:ff9b::", 96],
|
|
1447
|
+
["fc00::", 7],
|
|
1448
|
+
["fe80::", 10],
|
|
1449
|
+
["ff00::", 8]
|
|
1450
|
+
]) list.addSubnet(address, prefix, "ipv6");
|
|
1451
|
+
return list;
|
|
1452
|
+
}
|
|
1453
|
+
const privateAddresses = createBlockList();
|
|
1454
|
+
/**
|
|
1455
|
+
* Whether `address` is a routable public IP. Loopback, private, link-local, cloud metadata, and
|
|
1456
|
+
* multicast ranges are not, and an IPv4-mapped IPv6 address counts as the IPv4 address it wraps.
|
|
1457
|
+
* Pass `blocked` to replace the ranges.
|
|
1458
|
+
*/
|
|
1459
|
+
function isPublicAddress(address, blocked = privateAddresses) {
|
|
1460
|
+
const family = net.isIP(address);
|
|
1461
|
+
return family !== 0 && !blocked.check(address, family === 4 ? "ipv4" : "ipv6");
|
|
1462
|
+
}
|
|
1463
|
+
// src/gitInput.ts
|
|
1464
|
+
/** Matches a git `input`: the `git+` prefix npm uses for git dependencies. */
|
|
1465
|
+
const gitInputRegExp = /^git\+/i;
|
|
1466
|
+
function gitError(message, cause) {
|
|
1467
|
+
return new Diagnostics.Error({
|
|
1468
|
+
code: Diagnostics.code.gitInputFailed,
|
|
1469
|
+
severity: "error",
|
|
1470
|
+
message,
|
|
1471
|
+
help: "Write a git `input` as `git+<repo>#<ref>:<path>`, for example `git+https://github.com/org/api.git#main:specs/openapi.yaml`. Check that `git` is installed and that `git fetch` can reach the repository with your credentials.",
|
|
1472
|
+
location: { kind: "config" },
|
|
1473
|
+
cause: cause === void 0 ? void 0 : toError(cause)
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
/** The repository URL without a user or password, safe to print. */
|
|
1477
|
+
function redact(repo) {
|
|
1478
|
+
if (!URL.canParse(repo)) return repo;
|
|
1479
|
+
const url = new URL(repo);
|
|
1480
|
+
url.username = "";
|
|
1481
|
+
url.password = "";
|
|
1482
|
+
return url.href;
|
|
1483
|
+
}
|
|
1484
|
+
/**
|
|
1485
|
+
* Splits `git+<repo>#<ref>:<path>` into its parts. Git refs cannot contain `:`, so the first one
|
|
1486
|
+
* in the fragment ends the ref. Throws `KUBB_GIT_INPUT_FAILED` when the fragment or path is missing.
|
|
1487
|
+
*/
|
|
1488
|
+
function parseGitInput(input) {
|
|
1489
|
+
const hashIndex = input.indexOf("#");
|
|
1490
|
+
const repo = input.slice(4, hashIndex === -1 ? void 0 : hashIndex);
|
|
1491
|
+
const fragment = hashIndex === -1 ? "" : input.slice(hashIndex + 1);
|
|
1492
|
+
const colonIndex = fragment.indexOf(":");
|
|
1493
|
+
const ref = colonIndex === -1 ? void 0 : fragment.slice(0, colonIndex);
|
|
1494
|
+
const path = colonIndex === -1 ? fragment : fragment.slice(colonIndex + 1);
|
|
1495
|
+
if (!repo || !path || ref === "") throw gitError(`The git \`input\` for ${redact(repo)} has no repository, ref, or spec path after \`#\`.`);
|
|
1496
|
+
return {
|
|
1497
|
+
repo,
|
|
1498
|
+
ref,
|
|
1499
|
+
path
|
|
1500
|
+
};
|
|
1501
|
+
}
|
|
1502
|
+
/**
|
|
1503
|
+
* The `git -c` settings that confine a fetch to https and to `addresses`: the connection goes to
|
|
1504
|
+
* the addresses already checked, whatever the host answers to a second lookup, and a redirect to
|
|
1505
|
+
* another host is an error. Needs git 2.37 for the pinning.
|
|
1506
|
+
*
|
|
1507
|
+
* @internal
|
|
1508
|
+
*/
|
|
1509
|
+
function publicFetchConfig({ host, port, addresses }) {
|
|
1510
|
+
const pinned = addresses.map((address) => net.isIPv6(address) ? `[${address}]` : address).join(",");
|
|
1511
|
+
const config = [
|
|
1512
|
+
"http.followRedirects=false",
|
|
1513
|
+
"protocol.allow=never",
|
|
1514
|
+
"protocol.https.allow=always"
|
|
1515
|
+
];
|
|
1516
|
+
if (!net.isIP(host)) config.push(`http.curloptResolve=${host}:${port}:${pinned}`);
|
|
1517
|
+
return config.flatMap((setting) => ["-c", setting]);
|
|
1518
|
+
}
|
|
1519
|
+
async function resolvePublicFetchConfig(repo, signal) {
|
|
1520
|
+
if (!URL.canParse(repo) || new URL(repo).protocol !== "https:") throw gitError("A public git `input` must be an https repository URL, not an ssh, git, or file address.");
|
|
1521
|
+
const url = new URL(repo);
|
|
1522
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
1523
|
+
const isLiteral = net.isIP(host) !== 0;
|
|
1524
|
+
const addresses = isLiteral ? [host] : (await dns.promises.lookup(host, { all: true })).map(({ address }) => address);
|
|
1525
|
+
if (!addresses.length || addresses.some((address) => !isPublicAddress(address))) throw gitError(`${host} is not a public address, so this git \`input\` is not fetched.`);
|
|
1526
|
+
if (!isLiteral) {
|
|
1527
|
+
const { stdout } = await x("git", ["--version"], {
|
|
1528
|
+
nodeOptions: { signal },
|
|
1529
|
+
throwOnError: true
|
|
1530
|
+
});
|
|
1531
|
+
const [, major = 0, minor = 0] = /(\d+)\.(\d+)/.exec(stdout)?.map(Number) ?? [];
|
|
1532
|
+
if (major < 2 || major === 2 && minor < 37) throw gitError(`Fetching a public git \`input\` needs git 2.37 or newer, found ${stdout.trim()}.`);
|
|
1533
|
+
}
|
|
1534
|
+
return publicFetchConfig({
|
|
1535
|
+
host,
|
|
1536
|
+
port: url.port || "443",
|
|
1537
|
+
addresses
|
|
1538
|
+
});
|
|
1539
|
+
}
|
|
1540
|
+
/**
|
|
1541
|
+
* The `GIT_CONFIG_*` pair that sends an `Authorization` header to `repo`'s origin, numbered after
|
|
1542
|
+
* the pairs already in `env`, so the token stays out of the process arguments. Throws
|
|
1543
|
+
* `KUBB_GIT_INPUT_FAILED` for a value with a line break, which would add another header.
|
|
1544
|
+
*/
|
|
1545
|
+
function gitAuthEnv(env, { repo, authorization }) {
|
|
1546
|
+
if (/[\r\n]/.test(authorization) || !URL.canParse(repo)) throw gitError("The authorization for a git `input` must be one line, for an https repository.");
|
|
1547
|
+
const index = Math.max(0, Number.parseInt(env.GIT_CONFIG_COUNT ?? "", 10) || 0);
|
|
1548
|
+
return {
|
|
1549
|
+
GIT_CONFIG_COUNT: String(index + 1),
|
|
1550
|
+
[`GIT_CONFIG_KEY_${index}`]: `http.${new URL(repo).origin}/.extraheader`,
|
|
1551
|
+
[`GIT_CONFIG_VALUE_${index}`]: `Authorization: ${authorization}`
|
|
1552
|
+
};
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
1555
|
+
* Fetches one commit of a git repository into a temporary directory with a shallow `git fetch`,
|
|
1556
|
+
* so any host and the user's own git credentials work, and relative `$ref` files resolve.
|
|
1557
|
+
* Resolves to the spec path on disk and a `dispose` that deletes the checkout.
|
|
1558
|
+
*
|
|
1559
|
+
* With `publicOnly`, the repository must be an https URL on public addresses, the fetch connects to
|
|
1560
|
+
* the addresses checked, and it does not follow a redirect. `authorization` adds that header to this
|
|
1561
|
+
* fetch only, through {@link gitAuthEnv}.
|
|
1562
|
+
*/
|
|
1563
|
+
async function checkoutGitInput(input, signal, { publicOnly = false, authorization } = {}) {
|
|
1564
|
+
const { repo, ref, path } = parseGitInput(input);
|
|
1565
|
+
const authEnv = authorization ? gitAuthEnv(process$1.env, {
|
|
1566
|
+
repo,
|
|
1567
|
+
authorization
|
|
1568
|
+
}) : {};
|
|
1569
|
+
const fetchConfig = publicOnly ? await resolvePublicFetchConfig(repo, signal) : [];
|
|
1570
|
+
const dir = await mkdtemp(join(tmpdir(), "kubb-git-"));
|
|
1571
|
+
const dispose = () => rm(dir, {
|
|
1572
|
+
recursive: true,
|
|
1573
|
+
force: true
|
|
1574
|
+
});
|
|
1575
|
+
const specPath = resolve(dir, path);
|
|
1576
|
+
const relativePath = relative(dir, specPath);
|
|
1577
|
+
if (relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) {
|
|
1578
|
+
await dispose();
|
|
1579
|
+
throw gitError(`The spec path "${path}" in the git \`input\` points outside the repository.`);
|
|
1580
|
+
}
|
|
1581
|
+
const label = `${redact(repo)}${ref ? ` at ${ref}` : ""}`;
|
|
1582
|
+
const env = {
|
|
1583
|
+
...process$1.env,
|
|
1584
|
+
...authEnv,
|
|
1585
|
+
GIT_TERMINAL_PROMPT: "0"
|
|
1586
|
+
};
|
|
1587
|
+
const steps = [
|
|
1588
|
+
["init", "--quiet"],
|
|
1589
|
+
[
|
|
1590
|
+
"config",
|
|
1591
|
+
"core.symlinks",
|
|
1592
|
+
"false"
|
|
1593
|
+
],
|
|
1594
|
+
[
|
|
1595
|
+
...fetchConfig,
|
|
1596
|
+
"fetch",
|
|
1597
|
+
"--quiet",
|
|
1598
|
+
"--depth",
|
|
1599
|
+
"1",
|
|
1600
|
+
"--end-of-options",
|
|
1601
|
+
repo,
|
|
1602
|
+
ref ?? "HEAD"
|
|
1603
|
+
],
|
|
1604
|
+
[
|
|
1605
|
+
"checkout",
|
|
1606
|
+
"--quiet",
|
|
1607
|
+
"FETCH_HEAD"
|
|
1608
|
+
]
|
|
1609
|
+
];
|
|
1610
|
+
try {
|
|
1611
|
+
for (const args of steps) {
|
|
1612
|
+
const result = await x("git", args, {
|
|
1613
|
+
nodeOptions: {
|
|
1614
|
+
cwd: dir,
|
|
1615
|
+
env,
|
|
1616
|
+
signal
|
|
1617
|
+
},
|
|
1618
|
+
throwOnError: false
|
|
1619
|
+
});
|
|
1620
|
+
if (result.exitCode !== 0) {
|
|
1621
|
+
const stderr = result.stderr.replaceAll(repo, redact(repo)).trim();
|
|
1622
|
+
throw gitError(`\`git ${args[0]}\` failed for ${label}: ${stderr || `exit code ${result.exitCode}`}`);
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
} catch (error) {
|
|
1626
|
+
await dispose();
|
|
1627
|
+
if (Diagnostics.isError(error)) throw error;
|
|
1628
|
+
throw gitError(`Cannot run \`git\` for ${label}: ${getErrorMessage(error)}`, error);
|
|
1629
|
+
}
|
|
1630
|
+
return {
|
|
1631
|
+
path: specPath,
|
|
1632
|
+
dispose
|
|
1633
|
+
};
|
|
1634
|
+
}
|
|
1635
|
+
// src/input.ts
|
|
1636
|
+
/**
|
|
1637
|
+
* Classifies an `input` value so callers branch on it once instead of repeating the checks.
|
|
1638
|
+
*
|
|
1639
|
+
* A non-string is a parsed spec (`object`). A string is `inline` when it holds OpenAPI content,
|
|
1640
|
+
* meaning it starts with `{` or `[`, spans multiple lines, or opens with a YAML `openapi:` or
|
|
1641
|
+
* `swagger:` key. Otherwise a string is `git` when it starts with `git+`, a `url` when it parses as
|
|
1642
|
+
* one, or a `file` path.
|
|
1643
|
+
*/
|
|
1644
|
+
function getInputKind(input) {
|
|
1645
|
+
if (typeof input !== "string") return "object";
|
|
1646
|
+
const trimmed = input.trimStart();
|
|
1647
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[") || input.includes("\n") || /^(openapi|swagger)\s*:/i.test(trimmed)) return "inline";
|
|
1648
|
+
if (gitInputRegExp.test(input)) return "git";
|
|
1649
|
+
if (URL.canParse(input)) return "url";
|
|
1650
|
+
return "file";
|
|
1651
|
+
}
|
|
1652
|
+
/**
|
|
1653
|
+
* The v4 `input` wrapper keys. v4 typed `input` as `{ path }` or `{ data }`; v5 takes the value
|
|
1654
|
+
* directly, so the wrapper now matches the "already-parsed document" branch and silently yields
|
|
1655
|
+
* an empty build.
|
|
1656
|
+
*/
|
|
1657
|
+
const legacyInputKeys = ["path", "data"];
|
|
1658
|
+
/**
|
|
1659
|
+
* Detects the v4 `{ path }` / `{ data }` wrapper so it fails loudly instead of being read as a
|
|
1660
|
+
* document. A real spec always carries more than these keys, so an object whose keys are drawn
|
|
1661
|
+
* only from them is the old shape rather than a document that happens to have a `path` property.
|
|
1662
|
+
*/
|
|
1663
|
+
function isLegacyInput(input) {
|
|
1664
|
+
if (Array.isArray(input)) return input.some(isLegacyInput);
|
|
1665
|
+
if (typeof input !== "object" || input === null) return false;
|
|
1666
|
+
const keys = Object.keys(input);
|
|
1667
|
+
return keys.length > 0 && keys.every((key) => legacyInputKeys.includes(key));
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* Normalizes `config.input` into an `AdapterSource` the adapter can parse.
|
|
1671
|
+
*
|
|
1672
|
+
* A parsed object and inline content become `{ type: 'data' }` with `config.root` as the folder
|
|
1673
|
+
* their relative `$ref`s resolve from; a URL or git input is kept
|
|
1674
|
+
* verbatim and a local path is resolved against `config.root`, all as `{ type: 'path' }`. The
|
|
1675
|
+
* driver checks out a git input before the adapter parses it.
|
|
1676
|
+
*/
|
|
1677
|
+
function inputToAdapterSource(config) {
|
|
1678
|
+
const input = config.input;
|
|
1679
|
+
if (input && isLegacyInput(input)) throw new Diagnostics.Error({
|
|
1680
|
+
code: Diagnostics.code.legacyInput,
|
|
1681
|
+
severity: "error",
|
|
1682
|
+
message: "The `input` option uses the v4 `{ path }` / `{ data }` wrapper.",
|
|
1683
|
+
help: "Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`.",
|
|
1684
|
+
location: { kind: "config" }
|
|
1685
|
+
});
|
|
1686
|
+
if (!input) throw new Diagnostics.Error({
|
|
1687
|
+
code: Diagnostics.code.inputRequired,
|
|
1688
|
+
severity: "error",
|
|
1689
|
+
message: "An adapter is configured without an input.",
|
|
1690
|
+
help: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.",
|
|
1691
|
+
location: { kind: "config" }
|
|
1692
|
+
});
|
|
1693
|
+
if (typeof input !== "string") return {
|
|
1694
|
+
type: "data",
|
|
1695
|
+
data: input,
|
|
1696
|
+
root: resolve(config.root)
|
|
1697
|
+
};
|
|
1698
|
+
const kind = getInputKind(input);
|
|
1699
|
+
if (kind === "inline") return {
|
|
1700
|
+
type: "data",
|
|
1701
|
+
data: input,
|
|
1702
|
+
root: resolve(config.root)
|
|
1703
|
+
};
|
|
1704
|
+
if (kind === "url" || kind === "git") return {
|
|
1705
|
+
type: "path",
|
|
1706
|
+
path: input
|
|
1707
|
+
};
|
|
1708
|
+
return {
|
|
1709
|
+
type: "path",
|
|
1710
|
+
path: resolve(config.root, input)
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
// src/resolveOptions.ts
|
|
1714
|
+
const patterns = /* @__PURE__ */ new Map();
|
|
1715
|
+
const nodeCaches = /* @__PURE__ */ new WeakMap();
|
|
1716
|
+
function testPattern(value, pattern) {
|
|
1717
|
+
if (typeof pattern === "string") return memo$1(patterns, pattern, () => new RegExp(pattern)).test(value);
|
|
1718
|
+
return value.match(pattern) !== null;
|
|
1719
|
+
}
|
|
1720
|
+
function matchesOperation(node, filter) {
|
|
1721
|
+
if (filter.type === "extension") {
|
|
1722
|
+
const { extensions } = node;
|
|
1723
|
+
return extensions !== void 0 && Object.hasOwn(extensions, filter.key) && (filter.value === void 0 || extensions[filter.key] === filter.value);
|
|
1724
|
+
}
|
|
1725
|
+
const { type, pattern } = filter;
|
|
1726
|
+
if (type === "tag") return node.tags.some((tag) => testPattern(tag, pattern));
|
|
1727
|
+
if (type === "operationId") return testPattern(node.operationId, pattern);
|
|
1728
|
+
if (type === "path") return node.path !== void 0 && testPattern(node.path, pattern);
|
|
1729
|
+
if (type === "method") return node.method !== void 0 && testPattern(node.method.toLowerCase(), pattern);
|
|
1730
|
+
if (type === "contentType") return node.requestBody?.content?.some((c) => testPattern(c.contentType, pattern)) ?? false;
|
|
1731
|
+
return false;
|
|
1732
|
+
}
|
|
1733
|
+
function matchesSchema(node, filter) {
|
|
1734
|
+
if (filter.type === "schemaName") return node.name ? testPattern(node.name, filter.pattern) : false;
|
|
1735
|
+
return null;
|
|
1736
|
+
}
|
|
1737
|
+
function computeOptions(node, { options, exclude = [], include, override = [] }) {
|
|
1738
|
+
if (node.kind === ast.nodeKinds.operation) {
|
|
1739
|
+
if (exclude.some((filter) => matchesOperation(node, filter))) return null;
|
|
1740
|
+
if (include && !include.some((filter) => matchesOperation(node, filter))) return null;
|
|
1741
|
+
return {
|
|
1742
|
+
...options,
|
|
1743
|
+
...override.find((filter) => matchesOperation(node, filter))?.options
|
|
1744
|
+
};
|
|
1745
|
+
}
|
|
1746
|
+
if (node.kind === ast.nodeKinds.schema) {
|
|
1747
|
+
if (exclude.some((filter) => matchesSchema(node, filter) === true)) return null;
|
|
1748
|
+
if (include) {
|
|
1749
|
+
const applicable = include.map((filter) => matchesSchema(node, filter)).filter((result) => result !== null);
|
|
1750
|
+
if (applicable.length > 0 && !applicable.includes(true)) return null;
|
|
1751
|
+
}
|
|
1752
|
+
return {
|
|
1753
|
+
...options,
|
|
1754
|
+
...override.find((filter) => matchesSchema(node, filter) === true)?.options
|
|
1755
|
+
};
|
|
1756
|
+
}
|
|
1757
|
+
return options;
|
|
1758
|
+
}
|
|
1759
|
+
/**
|
|
1760
|
+
* Returns `null` for filtered nodes. Caches merged options per options object and node.
|
|
1761
|
+
*/
|
|
1762
|
+
function resolveOptions(node, context) {
|
|
1763
|
+
const { options } = context;
|
|
1764
|
+
if (typeof options !== "object" || options === null) return computeOptions(node, context);
|
|
1765
|
+
return memo$1(memo$1(nodeCaches, options, () => /* @__PURE__ */ new WeakMap()), node, () => computeOptions(node, context));
|
|
1766
|
+
}
|
|
1767
|
+
// src/Resolver.ts
|
|
1768
|
+
function isNamespace(value) {
|
|
1769
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1770
|
+
}
|
|
1771
|
+
/**
|
|
1772
|
+
* Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of
|
|
1773
|
+
* relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own
|
|
1774
|
+
* copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay
|
|
1775
|
+
* reachable and a `file` override is never dropped.
|
|
1776
|
+
*/
|
|
1777
|
+
const resolverOptions = Symbol.for("@kubb/core/resolver/options");
|
|
1778
|
+
/**
|
|
1779
|
+
* Builds a nested file path from a dotted name. Splits on dots that precede a letter
|
|
1780
|
+
* (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
|
|
1781
|
+
* every segment, and joins with `/`.
|
|
1782
|
+
*
|
|
1783
|
+
* Empty segments are dropped before joining. They arise when the name starts with a dot
|
|
1784
|
+
* followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to
|
|
1785
|
+
* an empty string). Without this a leading `/` would form, which `path.resolve` reads as an
|
|
1786
|
+
* absolute path, letting generated files escape the configured output directory.
|
|
1787
|
+
*
|
|
1788
|
+
* @example Nested path from a dotted name
|
|
1789
|
+
* `toFilePath('pet.petId') // 'pet/petId'`
|
|
1790
|
+
*/
|
|
1791
|
+
function toFilePath(name) {
|
|
1792
|
+
return name.split(/\.(?=[a-zA-Z])/).map((part) => camelCase(part)).filter(Boolean).join("/");
|
|
1793
|
+
}
|
|
1794
|
+
/** Throws `KUBB_PATH_TRAVERSAL` when `target` lies outside `parent`; `target === parent` stays allowed. */
|
|
1795
|
+
function assertInside({ target, parent, message, help }) {
|
|
1796
|
+
const parentWithSep = parent.endsWith(path.sep) ? parent : `${parent}${path.sep}`;
|
|
1797
|
+
if (target === parent || target.startsWith(parentWithSep)) return;
|
|
1798
|
+
throw new Diagnostics.Error({
|
|
1799
|
+
code: Diagnostics.code.pathTraversal,
|
|
1800
|
+
severity: "error",
|
|
1801
|
+
message,
|
|
1802
|
+
help,
|
|
1803
|
+
location: { kind: "config" }
|
|
1804
|
+
});
|
|
1805
|
+
}
|
|
1806
|
+
/**
|
|
1807
|
+
* Built-in `file.baseName`: casts the identifier with `toFilePath` and appends the extension.
|
|
1808
|
+
*/
|
|
1809
|
+
function toBaseName({ name, extname }) {
|
|
1810
|
+
return `${toFilePath(name)}${extname}`;
|
|
1811
|
+
}
|
|
1812
|
+
/**
|
|
1813
|
+
* Base constraint for all plugin resolver objects.
|
|
1814
|
+
*
|
|
1815
|
+
* The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,
|
|
1816
|
+
* and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with
|
|
1817
|
+
* top-level helpers (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
|
|
1818
|
+
*
|
|
1819
|
+
* @example Top-level helper
|
|
1820
|
+
* ```ts
|
|
1821
|
+
* type MyResolver = Resolver & {
|
|
1822
|
+
* typeName(name: string): string
|
|
1823
|
+
* }
|
|
1824
|
+
* ```
|
|
1825
|
+
*
|
|
1826
|
+
* @example Grouped namespace
|
|
1827
|
+
* ```ts
|
|
1828
|
+
* type MyResolver = Resolver & {
|
|
1829
|
+
* query: {
|
|
1830
|
+
* name(node: OperationNode): string
|
|
1831
|
+
* keyName(node: OperationNode): string
|
|
1832
|
+
* }
|
|
1833
|
+
* }
|
|
1834
|
+
* ```
|
|
1835
|
+
*/
|
|
1836
|
+
var Resolver = class Resolver {
|
|
1837
|
+
pluginName;
|
|
1838
|
+
/** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
|
|
1839
|
+
default;
|
|
1840
|
+
#options;
|
|
1841
|
+
#memo = /* @__PURE__ */ new Map();
|
|
1842
|
+
#usedNames = /* @__PURE__ */ new Set();
|
|
1843
|
+
#baseName;
|
|
1844
|
+
#filePath;
|
|
1845
|
+
constructor(options) {
|
|
1846
|
+
this.pluginName = options.pluginName;
|
|
1847
|
+
this.#options = options;
|
|
1848
|
+
this.#baseName = options.file?.baseName ? options.file.baseName.bind(this) : toBaseName;
|
|
1849
|
+
this.#filePath = options.file?.path ? options.file.path.bind(this) : void 0;
|
|
1850
|
+
this.default = {
|
|
1851
|
+
name: camelCase,
|
|
1852
|
+
options: resolveOptions,
|
|
1853
|
+
path: this.#resolvePath.bind(this),
|
|
1854
|
+
file: this.#resolveFile.bind(this),
|
|
1855
|
+
banner: this.#resolveBanner.bind(this),
|
|
1856
|
+
footer: this.#resolveFooter.bind(this)
|
|
1857
|
+
};
|
|
1858
|
+
this.#apply(options);
|
|
1859
|
+
}
|
|
1860
|
+
/** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
|
|
1861
|
+
get [resolverOptions]() {
|
|
1862
|
+
return this.#options;
|
|
1863
|
+
}
|
|
1864
|
+
name(name) {
|
|
1865
|
+
return this.default.name(name);
|
|
1866
|
+
}
|
|
1867
|
+
/**
|
|
1868
|
+
* Returns what `compute` produced the first time this build asked for `key`. A resolver lives for one build.
|
|
1869
|
+
*/
|
|
1870
|
+
memo(key, compute) {
|
|
1871
|
+
return memo$1(this.#memo, key, compute);
|
|
1872
|
+
}
|
|
1873
|
+
/**
|
|
1874
|
+
* Reserves emitted identifiers before allocating other declarations. The driver reserves component
|
|
1875
|
+
* names. Reserve extra identifiers, such as enum type aliases, before calling `resolveName`.
|
|
1876
|
+
*
|
|
1877
|
+
* @example Reserve an enum's type and value names
|
|
1878
|
+
* ```ts
|
|
1879
|
+
* resolver.reserveNames(['petStatusEnum', 'PetStatusEnumKey'])
|
|
1880
|
+
* ```
|
|
1881
|
+
*/
|
|
1882
|
+
reserveNames(names) {
|
|
1883
|
+
for (const name of names) this.#usedNames.add(name);
|
|
1884
|
+
}
|
|
1885
|
+
/**
|
|
1886
|
+
* Returns the same name for repeated declaration keys. Adds numeric suffixes starting at `2`
|
|
1887
|
+
* when the preferred name is taken. Array segment order and boundaries matter. String and array
|
|
1888
|
+
* keys are distinct. Pass an already-cased name or use `normalize` to compare emitted identifiers
|
|
1889
|
+
* while returning raw names. `Resolver.merge` creates a resolver with no reservations.
|
|
1890
|
+
*
|
|
1891
|
+
* @example Resolve a request body that collides with a component
|
|
1892
|
+
* ```ts
|
|
1893
|
+
* resolver.reserveNames(['CreateContainerBody'])
|
|
1894
|
+
* resolver.resolveName({ key: ['operation', 'POST', '/containers', 'body'], name: 'CreateContainerBody' })
|
|
1895
|
+
* // 'CreateContainerBody2'
|
|
1896
|
+
* ```
|
|
1897
|
+
*
|
|
1898
|
+
* @example Resolve a name that has to be free as both an enum value and a type alias
|
|
1899
|
+
* ```ts
|
|
1900
|
+
* resolver.resolveName({ key: ['enum', 'Pet', 'status'], name: 'Status', normalize: (name) => [camelCase(name), `${name}Key`] })
|
|
1901
|
+
* ```
|
|
1902
|
+
*/
|
|
1903
|
+
resolveName({ key, name, normalize = (name) => name }) {
|
|
1904
|
+
const cacheKey = typeof key === "string" ? `s:${key}` : `a:${key.map((segment) => segment === void 0 ? "u" : `${segment.length}:${segment}`).join("")}`;
|
|
1905
|
+
const allocate = (suffix) => {
|
|
1906
|
+
const candidate = suffix === 1 ? name : `${name}${suffix}`;
|
|
1907
|
+
const normalized = normalize(candidate);
|
|
1908
|
+
const names = typeof normalized === "string" ? [normalized] : normalized;
|
|
1909
|
+
if (names.some((emittedName) => this.#usedNames.has(emittedName))) return allocate(suffix + 1);
|
|
1910
|
+
this.reserveNames(names);
|
|
1911
|
+
return candidate;
|
|
1912
|
+
};
|
|
1913
|
+
return this.memo(`resolveName:${cacheKey}`, () => allocate(1));
|
|
1914
|
+
}
|
|
1915
|
+
file(options) {
|
|
1916
|
+
return this.#resolveFile(options);
|
|
1917
|
+
}
|
|
1918
|
+
/**
|
|
1919
|
+
* Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence
|
|
1920
|
+
* order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed
|
|
1921
|
+
* schemas (`targetName`) import the emitted name. Names and paths go through the top-level
|
|
1922
|
+
* `name` and `file`, so import entries follow the plugin's conventions, and a per-call
|
|
1923
|
+
* `name` override wins over both.
|
|
1924
|
+
*
|
|
1925
|
+
* The subtree scan runs through `collectImportedRefNames`, which memoizes by node identity, so a
|
|
1926
|
+
* schema shared across the ts, zod, and faker plugins is walked once and every plugin's resolver
|
|
1927
|
+
* reads the same ref set instead of re-scanning it per plugin.
|
|
1928
|
+
*/
|
|
1929
|
+
imports(options) {
|
|
1930
|
+
const { node, root, output, group, extname = ".ts", name } = options;
|
|
1931
|
+
const resolveName = name ?? ((schemaName) => this.name(schemaName));
|
|
1932
|
+
return collectImportedRefNames(node).map((schemaName) => ast.factory.createImport({
|
|
1933
|
+
name: [resolveName(schemaName)],
|
|
1934
|
+
path: this.#resolveFilePath({
|
|
1935
|
+
name: schemaName,
|
|
1936
|
+
extname,
|
|
1937
|
+
root,
|
|
1938
|
+
output,
|
|
1939
|
+
group
|
|
1940
|
+
})
|
|
1941
|
+
}));
|
|
1942
|
+
}
|
|
1943
|
+
/**
|
|
1944
|
+
* Folds each `override` over `base`, left to right, and returns a new resolver with helpers
|
|
1945
|
+
* re-bound. Top-level keys replace, and a namespace (or `file`) merges per method, so overriding
|
|
1946
|
+
* `query.name` keeps the base `query.keyName`. The last override wins per key. Used when applying
|
|
1947
|
+
* `setResolver` partial overrides, and to compose shared resolver fragments without spreading each
|
|
1948
|
+
* namespace by hand. Reads a resolver's options through the shared brand rather than `instanceof`,
|
|
1949
|
+
* so a `file` override survives even when `base` and `override` come from different `@kubb/core`
|
|
1950
|
+
* copies.
|
|
1951
|
+
*
|
|
1952
|
+
* @example Fold several partial overrides onto a resolver
|
|
1953
|
+
* ```ts
|
|
1954
|
+
* const resolver = Resolver.merge(defaultResolver, sharedNamingPatch, { name: (name) => name.toUpperCase() })
|
|
1955
|
+
* ```
|
|
1956
|
+
*/
|
|
1957
|
+
static merge(base, ...overrides) {
|
|
1958
|
+
const merged = overrides.reduce((acc, override) => {
|
|
1959
|
+
const patch = resolverOptions in override ? override[resolverOptions] : override;
|
|
1960
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
1961
|
+
if (value === void 0) continue;
|
|
1962
|
+
const current = acc[key];
|
|
1963
|
+
acc[key] = isNamespace(value) && isNamespace(current) ? {
|
|
1964
|
+
...current,
|
|
1965
|
+
...value
|
|
1966
|
+
} : value;
|
|
1967
|
+
}
|
|
1968
|
+
return acc;
|
|
1969
|
+
}, { ...base[resolverOptions] });
|
|
1970
|
+
return new Resolver(merged);
|
|
1971
|
+
}
|
|
1972
|
+
/**
|
|
1973
|
+
* Binds each entry of `options` onto the resolver, so `this.name`, `this.default`, and
|
|
1974
|
+
* `this.file` resolve there for top-level helpers and namespace methods alike. `default`
|
|
1975
|
+
* is skipped so it can't be shadowed.
|
|
1976
|
+
*/
|
|
1977
|
+
#apply(options) {
|
|
1978
|
+
const root = this;
|
|
1979
|
+
const bind = (value) => typeof value === "function" ? value.bind(root) : value;
|
|
1980
|
+
for (const [key, value] of Object.entries(options)) {
|
|
1981
|
+
if (key === "pluginName" || key === "default" || key === "file" || value === void 0) continue;
|
|
1982
|
+
root[key] = isNamespace(value) ? Object.fromEntries(Object.entries(value).map(([method, member]) => [method, bind(member)])) : bind(value);
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
/**
|
|
1986
|
+
* A custom `group.name` wins; otherwise `tag` groups use the camelCased tag and `path`
|
|
1987
|
+
* groups use the first non-traversal segment (`''` when none remain, placing the file in
|
|
1988
|
+
* the output root, kept safe by the caller's boundary check).
|
|
1989
|
+
*/
|
|
1990
|
+
static #resolveGroupDir(group, groupValue) {
|
|
1991
|
+
if (group.name) return group.name({ group: groupValue });
|
|
1992
|
+
if (group.type === "tag") return camelCase(groupValue);
|
|
1993
|
+
const segment = groupValue.split("/").filter((part) => part !== "" && part !== "." && part !== "..")[0];
|
|
1994
|
+
return segment ? camelCase(segment) : "";
|
|
1995
|
+
}
|
|
1996
|
+
/**
|
|
1997
|
+
* `mode: 'file'` (default) resolves directly to `output.path`. `mode: 'directory'` resolves
|
|
1998
|
+
* to `output.path/{baseName}`, or into a subdirectory when `group` and a `tag`/`path` value
|
|
1999
|
+
* are provided.
|
|
2000
|
+
*/
|
|
2001
|
+
#resolvePath({ baseName, tag, path: groupPath, root, output, group }) {
|
|
2002
|
+
if (output.mode !== "directory") return path.resolve(root, output.path);
|
|
2003
|
+
const outputDir = path.resolve(root, output.path);
|
|
2004
|
+
const groupValue = group?.type === "path" ? groupPath : tag;
|
|
2005
|
+
const result = group && groupValue ? path.resolve(outputDir, Resolver.#resolveGroupDir(group, groupValue), baseName) : path.resolve(outputDir, baseName);
|
|
2006
|
+
assertInside({
|
|
2007
|
+
target: result,
|
|
2008
|
+
parent: outputDir,
|
|
2009
|
+
message: `Resolved path "${result}" is outside the output directory "${outputDir}".`,
|
|
2010
|
+
help: "This can stem from a path traversal in the OpenAPI specification or a misconfigured `group.name` function. Keep generated paths within the output directory."
|
|
2011
|
+
});
|
|
2012
|
+
return result;
|
|
2013
|
+
}
|
|
2014
|
+
/**
|
|
2015
|
+
* Resolves a resolver-supplied full path (`file.path`) against `root`, bypassing `output.path`
|
|
2016
|
+
* and `group`. The path may not escape `root`, which keeps a `file.path` that interpolates
|
|
2017
|
+
* spec-derived values from writing outside the project.
|
|
2018
|
+
*/
|
|
2019
|
+
#resolveOverridePath(filePath, root) {
|
|
2020
|
+
const resolved = path.resolve(root, filePath);
|
|
2021
|
+
assertInside({
|
|
2022
|
+
target: resolved,
|
|
2023
|
+
parent: root,
|
|
2024
|
+
message: `Resolved path "${resolved}" is outside the project root "${root}".`,
|
|
2025
|
+
help: "A resolver `file.path` must return a path inside the project root."
|
|
2026
|
+
});
|
|
2027
|
+
return resolved;
|
|
2028
|
+
}
|
|
2029
|
+
/** The absolute path `#resolveFile` places a file at. */
|
|
2030
|
+
#resolveFilePath({ name, extname, tag, path: groupPath, root, output, group }) {
|
|
2031
|
+
const baseName = this.#baseName({
|
|
2032
|
+
name,
|
|
2033
|
+
extname
|
|
2034
|
+
});
|
|
2035
|
+
return this.#filePath ? this.#resolveOverridePath(this.#filePath({
|
|
2036
|
+
baseName,
|
|
2037
|
+
output
|
|
2038
|
+
}), root) : this.#resolvePath({
|
|
2039
|
+
baseName,
|
|
2040
|
+
tag,
|
|
2041
|
+
path: groupPath,
|
|
2042
|
+
root,
|
|
2043
|
+
output,
|
|
2044
|
+
group
|
|
2045
|
+
});
|
|
2046
|
+
}
|
|
2047
|
+
/**
|
|
2048
|
+
* Builds a `FileNode`. When `#filePath` (the resolver's `file.path`) is set it owns the whole
|
|
2049
|
+
* path; otherwise the base name (from `#baseName`, the resolver's `file.baseName` or the
|
|
2050
|
+
* built-in `toBaseName`) is placed by the `output.path`/`group` layout. The resolved file starts
|
|
2051
|
+
* with empty `sources`, `imports`, and `exports`, which consumers populate separately.
|
|
2052
|
+
*/
|
|
2053
|
+
#resolveFile(options) {
|
|
2054
|
+
const filePath = this.#resolveFilePath(options);
|
|
2055
|
+
return ast.factory.createFile({
|
|
2056
|
+
path: filePath,
|
|
2057
|
+
baseName: path.basename(filePath),
|
|
2058
|
+
meta: { pluginName: this.pluginName },
|
|
2059
|
+
sources: [],
|
|
2060
|
+
imports: [],
|
|
2061
|
+
exports: []
|
|
2062
|
+
});
|
|
2063
|
+
}
|
|
2064
|
+
/**
|
|
2065
|
+
* Missing fields default to empty/`false` so the `BannerMeta` shape stays stable even when
|
|
2066
|
+
* a caller (e.g. the barrel plugin) has no document metadata.
|
|
2067
|
+
*/
|
|
2068
|
+
static #buildBannerMeta(meta, file) {
|
|
2069
|
+
return {
|
|
2070
|
+
title: meta?.title,
|
|
2071
|
+
description: meta?.description,
|
|
2072
|
+
version: meta?.version,
|
|
2073
|
+
baseURL: meta?.baseURL,
|
|
2074
|
+
filePath: file?.path ?? "",
|
|
2075
|
+
baseName: file?.baseName ?? "",
|
|
2076
|
+
isBarrel: file?.isBarrel ?? false,
|
|
2077
|
+
isAggregation: file?.isAggregation ?? false
|
|
2078
|
+
};
|
|
2079
|
+
}
|
|
2080
|
+
/**
|
|
2081
|
+
* Resolves a user-configured banner/footer value. `undefined` means not configured.
|
|
2082
|
+
*/
|
|
2083
|
+
static #resolveUserText(value, meta, file) {
|
|
2084
|
+
if (typeof value === "function") return value(Resolver.#buildBannerMeta(meta, file));
|
|
2085
|
+
if (typeof value === "string") return value;
|
|
2086
|
+
}
|
|
2087
|
+
static #buildDefaultBanner({ title, version, config }) {
|
|
2088
|
+
const lines = [
|
|
2089
|
+
"/**",
|
|
2090
|
+
"* Generated by Kubb (https://kubb.dev/).",
|
|
2091
|
+
"* Do not edit manually."
|
|
2092
|
+
];
|
|
2093
|
+
if (config.output.defaultBanner !== "simple") {
|
|
2094
|
+
const input = config.input;
|
|
2095
|
+
const source = typeof input === "string" ? getInputKind(input) === "inline" ? "text content" : path.basename(input) : input ? "text content" : "";
|
|
2096
|
+
if (source) lines.push(`* Source: ${source}`);
|
|
2097
|
+
if (title) lines.push(`* Title: ${title}`);
|
|
2098
|
+
if (version) lines.push(`* OpenAPI spec version: ${version}`);
|
|
2099
|
+
}
|
|
2100
|
+
return `${lines.join("\n")}\n*/\n`;
|
|
2101
|
+
}
|
|
2102
|
+
/**
|
|
2103
|
+
* A user-supplied `output.banner` overrides the default Kubb notice. When
|
|
2104
|
+
* `config.output.defaultBanner` is `false` and no user banner is set, returns `null`.
|
|
2105
|
+
*/
|
|
2106
|
+
#resolveBanner(meta, { output, config, file }) {
|
|
2107
|
+
const userBanner = Resolver.#resolveUserText(output?.banner, meta, file);
|
|
2108
|
+
if (userBanner !== void 0) return userBanner;
|
|
2109
|
+
if (config.output.defaultBanner === false) return null;
|
|
2110
|
+
return Resolver.#buildDefaultBanner({
|
|
2111
|
+
title: meta?.title,
|
|
2112
|
+
version: meta?.version,
|
|
2113
|
+
config
|
|
2114
|
+
});
|
|
2115
|
+
}
|
|
2116
|
+
#resolveFooter(meta, { output, file }) {
|
|
2117
|
+
return Resolver.#resolveUserText(output?.footer, meta, file) ?? null;
|
|
2118
|
+
}
|
|
2119
|
+
};
|
|
2120
|
+
// src/createResolver.ts
|
|
2121
|
+
/**
|
|
2122
|
+
* Defines a plugin resolver, the object that decides what every generated symbol and file
|
|
2123
|
+
* path is called. Override the top-level `name` and `file` to set the plugin's conventions,
|
|
2124
|
+
* and add your own naming helpers, top-level (`typeName`, …) or grouped in namespaces
|
|
2125
|
+
* (`query`, `schema`, …). Every method reaches sibling helpers and the built-in machinery
|
|
2126
|
+
* through `this.name`, `this.file`, and `this.default`.
|
|
2127
|
+
*
|
|
2128
|
+
* @example Custom identifier casing
|
|
2129
|
+
* ```ts
|
|
2130
|
+
* export const resolverTs = createResolver<PluginTs>({
|
|
2131
|
+
* pluginName: 'plugin-ts',
|
|
2132
|
+
* name(name) {
|
|
2133
|
+
* return this.memo(`name:${name}`, () => ensureValidVarName(pascalCase(name)))
|
|
2134
|
+
* },
|
|
2135
|
+
* })
|
|
2136
|
+
* ```
|
|
2137
|
+
*
|
|
2138
|
+
* @example Rename generated files with `file.baseName`
|
|
2139
|
+
* ```ts
|
|
2140
|
+
* export const resolverFaker = createResolver<PluginFaker>({
|
|
2141
|
+
* pluginName: 'plugin-faker',
|
|
2142
|
+
* name(name) {
|
|
2143
|
+
* return camelCase(name, { prefix: 'create' })
|
|
2144
|
+
* },
|
|
2145
|
+
* file: {
|
|
2146
|
+
* baseName({ name, extname }) {
|
|
2147
|
+
* return `${camelCase(name, { prefix: 'create' })}${extname}`
|
|
2148
|
+
* },
|
|
2149
|
+
* },
|
|
2150
|
+
* })
|
|
2151
|
+
* ```
|
|
2152
|
+
*
|
|
2153
|
+
* @example Own the full path with `file.path`
|
|
2154
|
+
* ```ts
|
|
2155
|
+
* export const resolverFaker = createResolver<PluginFaker>({
|
|
2156
|
+
* pluginName: 'plugin-faker',
|
|
2157
|
+
* file: {
|
|
2158
|
+
* path({ baseName, output }) {
|
|
2159
|
+
* return `${output.path}/mocks/${baseName}`
|
|
2160
|
+
* },
|
|
2161
|
+
* },
|
|
2162
|
+
* })
|
|
2163
|
+
* ```
|
|
2164
|
+
*/
|
|
2165
|
+
function createResolver(options) {
|
|
2166
|
+
return new Resolver(options);
|
|
2167
|
+
}
|
|
2168
|
+
// \0@oxc-project+runtime@0.155.0/helpers/esm/usingCtx.js
|
|
2169
|
+
function _usingCtx() {
|
|
2170
|
+
var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
|
|
2171
|
+
var n = Error();
|
|
2172
|
+
return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
|
|
2173
|
+
};
|
|
2174
|
+
var e = {};
|
|
2175
|
+
var n = [];
|
|
2176
|
+
function using(r, e) {
|
|
2177
|
+
if (null != e) {
|
|
2178
|
+
if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
|
|
2179
|
+
if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
|
|
2180
|
+
if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
|
|
2181
|
+
if ("function" != typeof o) throw new TypeError("Object is not disposable.");
|
|
2182
|
+
t && (o = function o() {
|
|
2183
|
+
try {
|
|
2184
|
+
t.call(e);
|
|
2185
|
+
} catch (r) {
|
|
2186
|
+
return Promise.reject(r);
|
|
2187
|
+
}
|
|
2188
|
+
}), n.push({
|
|
2189
|
+
v: e,
|
|
2190
|
+
d: o,
|
|
2191
|
+
a: r
|
|
2192
|
+
});
|
|
2193
|
+
} else r && n.push({
|
|
2194
|
+
d: e,
|
|
2195
|
+
a: r
|
|
2196
|
+
});
|
|
2197
|
+
return e;
|
|
2198
|
+
}
|
|
2199
|
+
return {
|
|
2200
|
+
e,
|
|
2201
|
+
u: using.bind(null, !1),
|
|
2202
|
+
a: using.bind(null, !0),
|
|
2203
|
+
d: function d() {
|
|
2204
|
+
var o;
|
|
2205
|
+
var t = this.e;
|
|
2206
|
+
var s = 0;
|
|
2207
|
+
function next() {
|
|
2208
|
+
for (; o = n.pop();) try {
|
|
2209
|
+
if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
|
|
2210
|
+
if (o.d) {
|
|
2211
|
+
var r = o.d.call(o.v);
|
|
2212
|
+
if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
|
|
2213
|
+
} else s |= 1;
|
|
2214
|
+
} catch (r) {
|
|
2215
|
+
return err(r);
|
|
2216
|
+
}
|
|
2217
|
+
if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
|
|
2218
|
+
if (t !== e) throw t;
|
|
2219
|
+
}
|
|
2220
|
+
function err(n) {
|
|
2221
|
+
return t = t !== e ? new r(n, t) : n, next();
|
|
2222
|
+
}
|
|
2223
|
+
return next();
|
|
2224
|
+
}
|
|
2225
|
+
};
|
|
2226
|
+
}
|
|
2227
|
+
function joinSources(file) {
|
|
2228
|
+
return file.sources.map((source) => extractStringsFromNodes(source.nodes)).filter(Boolean).join("\n\n");
|
|
2229
|
+
}
|
|
2230
|
+
/** Runs a parser call and turns a crash into a `KUBB_PARSER_FAILED` diagnostic that names the parser. */
|
|
2231
|
+
function runParser(parser, print) {
|
|
2232
|
+
try {
|
|
2233
|
+
return print();
|
|
2234
|
+
} catch (error) {
|
|
2235
|
+
throw new Diagnostics.Error(Diagnostics.fromExtension(error, {
|
|
2236
|
+
kind: "parser",
|
|
2237
|
+
extension: parser
|
|
2238
|
+
}));
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
/**
|
|
2242
|
+
* Reads a `copy` file and prints it through the parser's `copy` hook, or verbatim with `banner`/`footer` when there is none.
|
|
2243
|
+
*/
|
|
2244
|
+
async function parseCopy(file, parser) {
|
|
2245
|
+
const content = await readFile(file.copy, "utf8").catch((err) => {
|
|
2246
|
+
throw new Diagnostics.Error({
|
|
2247
|
+
code: Diagnostics.code.pluginFailed,
|
|
2248
|
+
severity: "error",
|
|
2249
|
+
message: `Could not copy file into output: ${file.copy}`,
|
|
2250
|
+
help: "Check that the file a plugin copies into the output exists and is readable.",
|
|
2251
|
+
cause: toError(err)
|
|
2252
|
+
});
|
|
2253
|
+
});
|
|
2254
|
+
if (parser?.copy) return runParser(parser, () => parser.parse(ast.factory.createFile(parser.copy(file, content))));
|
|
2255
|
+
return [
|
|
2256
|
+
file.banner,
|
|
2257
|
+
content,
|
|
2258
|
+
file.footer
|
|
2259
|
+
].filter((segment) => Boolean(segment)).map((segment) => segment.trimEnd()).join("\n");
|
|
2260
|
+
}
|
|
2261
|
+
function mergeFile(a, b) {
|
|
2262
|
+
return {
|
|
2263
|
+
...a,
|
|
2264
|
+
banner: b.banner,
|
|
2265
|
+
footer: b.footer,
|
|
2266
|
+
copy: b.copy ?? a.copy,
|
|
2267
|
+
sources: [...a.sources, ...b.sources],
|
|
2268
|
+
imports: [...a.imports, ...b.imports],
|
|
2269
|
+
exports: [...a.exports, ...b.exports]
|
|
2270
|
+
};
|
|
2271
|
+
}
|
|
2272
|
+
function isIndexPath(path) {
|
|
2273
|
+
return path.endsWith("/index.ts") || path === "index.ts";
|
|
2274
|
+
}
|
|
2275
|
+
function compareFiles(a, b) {
|
|
2276
|
+
return a.path.length - b.path.length || Number(isIndexPath(a.path)) - Number(isIndexPath(b.path));
|
|
2277
|
+
}
|
|
2278
|
+
/**
|
|
2279
|
+
* Writes `source` to `file.path` unless the storage already holds it, either verbatim or, per the
|
|
2280
|
+
* manifest, as what the output passes make of it. Checking here rather than in a driver gives a
|
|
2281
|
+
* storage writing to S3 or a database the same guarantee `fsStorage` has. `false` when skipped.
|
|
2282
|
+
*/
|
|
2283
|
+
async function writeChanged({ storage, manifest, file, source, signal, cleaned }) {
|
|
2284
|
+
signal?.throwIfAborted();
|
|
2285
|
+
const stored = cleaned && isPathInside(file.path, cleaned) ? null : await storage.readItem(file.path);
|
|
2286
|
+
if (stored !== null && (matchesStored({
|
|
2287
|
+
stored,
|
|
2288
|
+
source
|
|
2289
|
+
}) || manifest?.isUpToDate({
|
|
2290
|
+
key: file.path,
|
|
2291
|
+
source,
|
|
2292
|
+
disk: stored
|
|
2293
|
+
}))) return false;
|
|
2294
|
+
signal?.throwIfAborted();
|
|
2295
|
+
await storage.writeItem(file.path, source, { stored });
|
|
2296
|
+
manifest?.track({
|
|
2297
|
+
key: file.path,
|
|
2298
|
+
source
|
|
2299
|
+
});
|
|
2300
|
+
return true;
|
|
2301
|
+
}
|
|
2302
|
+
/** Reports finished files in input order: each finished file flushes the run of finished files ahead of it as one update. */
|
|
2303
|
+
function createProgress(files, config, hooks) {
|
|
2304
|
+
const finished = [];
|
|
2305
|
+
let flushed = 0;
|
|
2306
|
+
return async (index) => {
|
|
2307
|
+
finished[index] = true;
|
|
2308
|
+
const updates = [];
|
|
2309
|
+
while (finished[flushed]) {
|
|
2310
|
+
flushed++;
|
|
2311
|
+
updates.push({
|
|
2312
|
+
file: files[flushed - 1],
|
|
2313
|
+
processed: flushed,
|
|
2314
|
+
total: files.length,
|
|
2315
|
+
percentage: flushed / files.length * 100,
|
|
2316
|
+
config
|
|
2317
|
+
});
|
|
2318
|
+
}
|
|
2319
|
+
if (updates.length) await hooks.callHook("kubb:files:processing:update", { files: updates });
|
|
2320
|
+
};
|
|
2321
|
+
}
|
|
2322
|
+
/** Links each source without a pointer to the node its file was generated from. */
|
|
2323
|
+
function withPointer(files, pointer) {
|
|
2324
|
+
if (!pointer) return files;
|
|
2325
|
+
return files.map((file) => ({
|
|
2326
|
+
...file,
|
|
2327
|
+
sources: file.sources.map((source) => source.pointer ? source : {
|
|
2328
|
+
...source,
|
|
2329
|
+
pointer
|
|
2330
|
+
})
|
|
2331
|
+
}));
|
|
2332
|
+
}
|
|
2333
|
+
/**
|
|
2334
|
+
* In-memory file store for generated files, and the writer that turns them into source
|
|
2335
|
+
* strings on `storage`. Files sharing a `path` are merged (sources/imports/exports
|
|
2336
|
+
* concatenated). The `files` getter is sorted by path length (barrel `index.ts` last
|
|
2337
|
+
* within a bucket).
|
|
2338
|
+
*
|
|
2339
|
+
* @example
|
|
2340
|
+
* ```ts
|
|
2341
|
+
* const manager = new FileManager()
|
|
2342
|
+
* manager.upsert(myFile)
|
|
2343
|
+
* manager.files // sorted view
|
|
2344
|
+
* await manager.write(manager.files, { storage: fsStorage() })
|
|
2345
|
+
* ```
|
|
2346
|
+
*/
|
|
2347
|
+
var FileManager = class {
|
|
2348
|
+
#cache = /* @__PURE__ */ new Map();
|
|
2349
|
+
#pending = /* @__PURE__ */ new Set();
|
|
2350
|
+
#sorted = null;
|
|
2351
|
+
#merges = /* @__PURE__ */ new WeakSet();
|
|
2352
|
+
add(...files) {
|
|
2353
|
+
return this.#store(files, false);
|
|
2354
|
+
}
|
|
2355
|
+
upsert(...files) {
|
|
2356
|
+
return this.#store(files, true);
|
|
2357
|
+
}
|
|
2358
|
+
/** Stores a generator result: a file array is upserted as is, an element renders through `renderer` first, falsy is a no-op. */
|
|
2359
|
+
async dispatch({ result, renderer, pointer }) {
|
|
2360
|
+
try {
|
|
2361
|
+
var _usingCtx$2 = _usingCtx();
|
|
2362
|
+
if (!result) return;
|
|
2363
|
+
if (Array.isArray(result)) {
|
|
2364
|
+
this.#defer(withPointer(result, pointer));
|
|
2365
|
+
return;
|
|
2366
|
+
}
|
|
2367
|
+
if (!renderer) return;
|
|
2368
|
+
const instance = _usingCtx$2.u(renderer());
|
|
2369
|
+
await instance.render(result);
|
|
2370
|
+
this.#defer(withPointer(instance.files, pointer));
|
|
2371
|
+
} catch (_) {
|
|
2372
|
+
_usingCtx$2.e = _;
|
|
2373
|
+
} finally {
|
|
2374
|
+
_usingCtx$2.d();
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
/** Upserts without normalizing: the raw merge waits in `#pending` until the file is read. */
|
|
2378
|
+
#defer(files) {
|
|
2379
|
+
for (const file of files) {
|
|
2380
|
+
this.#pending.add(file.path);
|
|
2381
|
+
const existing = this.#cache.get(file.path);
|
|
2382
|
+
if (!existing) {
|
|
2383
|
+
this.#cache.set(file.path, file);
|
|
2384
|
+
continue;
|
|
2385
|
+
}
|
|
2386
|
+
if (!this.#merges.has(existing)) {
|
|
2387
|
+
const merged = mergeFile(existing, file);
|
|
2388
|
+
this.#merges.add(merged);
|
|
2389
|
+
this.#cache.set(file.path, merged);
|
|
2390
|
+
continue;
|
|
2391
|
+
}
|
|
2392
|
+
existing.banner = file.banner;
|
|
2393
|
+
existing.footer = file.footer;
|
|
2394
|
+
existing.copy = file.copy ?? existing.copy;
|
|
2395
|
+
existing.sources.push(...file.sources);
|
|
2396
|
+
existing.imports.push(...file.imports);
|
|
2397
|
+
existing.exports.push(...file.exports);
|
|
2398
|
+
}
|
|
2399
|
+
if (files.length > 0) this.#sorted = null;
|
|
2400
|
+
}
|
|
2401
|
+
/** Normalizes the pending raw merges, so every entry in `#cache` is a `createFile` result. */
|
|
2402
|
+
#flush() {
|
|
2403
|
+
for (const path of this.#pending) this.#cache.set(path, ast.factory.createFile(this.#cache.get(path)));
|
|
2404
|
+
this.#pending.clear();
|
|
2405
|
+
}
|
|
2406
|
+
#store(files, mergeExisting) {
|
|
2407
|
+
this.#flush();
|
|
2408
|
+
const batch = /* @__PURE__ */ new Set();
|
|
2409
|
+
const resolved = files.map((file) => {
|
|
2410
|
+
const existing = this.#cache.get(file.path);
|
|
2411
|
+
const merged = ast.factory.createFile(existing && (mergeExisting || batch.has(file.path)) ? mergeFile(existing, file) : file);
|
|
2412
|
+
this.#cache.set(merged.path, merged);
|
|
2413
|
+
batch.add(merged.path);
|
|
2414
|
+
return merged;
|
|
2415
|
+
});
|
|
2416
|
+
if (resolved.length > 0) this.#sorted = null;
|
|
2417
|
+
return resolved;
|
|
2418
|
+
}
|
|
2419
|
+
/**
|
|
2420
|
+
* Removes the files at `paths`, so they are neither listed nor written.
|
|
2421
|
+
*/
|
|
2422
|
+
delete(...paths) {
|
|
2423
|
+
for (const path of paths) {
|
|
2424
|
+
this.#cache.delete(path);
|
|
2425
|
+
this.#pending.delete(path);
|
|
2426
|
+
}
|
|
2427
|
+
if (paths.length > 0) this.#sorted = null;
|
|
2428
|
+
}
|
|
2429
|
+
/**
|
|
2430
|
+
* Releases all stored files. Called by the core after `kubb:build:end`.
|
|
2431
|
+
*/
|
|
2432
|
+
dispose() {
|
|
2433
|
+
this.#cache.clear();
|
|
2434
|
+
this.#pending.clear();
|
|
2435
|
+
this.#sorted = null;
|
|
2436
|
+
}
|
|
2437
|
+
/**
|
|
2438
|
+
* All stored files in stable sort order (shortest path first, barrel files
|
|
2439
|
+
* last within a length bucket). Returns a cached view, do not mutate.
|
|
2440
|
+
*/
|
|
2441
|
+
get files() {
|
|
2442
|
+
this.#flush();
|
|
2443
|
+
return this.#sorted ??= [...this.#cache.values()].sort(compareFiles);
|
|
2444
|
+
}
|
|
2445
|
+
/**
|
|
2446
|
+
* Converts a file's AST sources (or its `copy` source) into the final on-disk string.
|
|
2447
|
+
*/
|
|
2448
|
+
async parse(file, { parsers } = {}) {
|
|
2449
|
+
const parser = parsers?.get(file.extname);
|
|
2450
|
+
if (file.copy) return parseCopy(file, parser);
|
|
2451
|
+
if (!parser) return joinSources(file);
|
|
2452
|
+
return runParser(parser, () => parser.parse(file));
|
|
2453
|
+
}
|
|
2454
|
+
/**
|
|
2455
|
+
* Parses and writes every file through a bounded pool of workers. A small spec runs all its files
|
|
2456
|
+
* at once; a spec with thousands of files keeps at most {@link FILE_CONCURRENCY} parsed sources in
|
|
2457
|
+
* memory rather than holding every source, while still overlapping each file's write with the
|
|
2458
|
+
* next file's parse. Files finish in whatever order they parse, so each finished file flushes the
|
|
2459
|
+
* run of finished files ahead of it as one `kubb:files:processing:update`, keeping rows in input order.
|
|
2460
|
+
*
|
|
2461
|
+
* A file the storage already holds is skipped, so a rebuild that generates identical output
|
|
2462
|
+
* writes nothing and leaves every mtime where it was. `kubb:files:processing:end` lists the
|
|
2463
|
+
* skipped paths as `unchanged`.
|
|
2464
|
+
*/
|
|
2465
|
+
async write(files, { storage, parsers, manifest, signal, hooks, config, cleaned }) {
|
|
2466
|
+
if (files.length === 0) return;
|
|
2467
|
+
await hooks?.callHook("kubb:files:processing:start", { files });
|
|
2468
|
+
const unchanged = [];
|
|
2469
|
+
const progress = hooks && config ? createProgress(files, config, hooks) : void 0;
|
|
2470
|
+
await inParallel({
|
|
2471
|
+
items: files,
|
|
2472
|
+
limit: 50,
|
|
2473
|
+
run: async (file, index) => {
|
|
2474
|
+
signal?.throwIfAborted();
|
|
2475
|
+
const source = await this.parse(file, { parsers });
|
|
2476
|
+
if (source && !await writeChanged({
|
|
2477
|
+
storage,
|
|
2478
|
+
manifest,
|
|
2479
|
+
file,
|
|
2480
|
+
source,
|
|
2481
|
+
signal,
|
|
2482
|
+
cleaned
|
|
2483
|
+
})) unchanged.push(file.path);
|
|
2484
|
+
await progress?.(index);
|
|
2485
|
+
}
|
|
2486
|
+
});
|
|
2487
|
+
await hooks?.callHook("kubb:files:processing:end", {
|
|
2488
|
+
files,
|
|
2489
|
+
unchanged
|
|
2490
|
+
});
|
|
2491
|
+
}
|
|
2492
|
+
};
|
|
2493
|
+
// src/KubbDriver.ts
|
|
2494
|
+
/** `include` filter types that select operations, and so prune the schemas they do not reach. */
|
|
2495
|
+
const OPERATION_FILTER_TYPES = /* @__PURE__ */ new Set([
|
|
2496
|
+
"tag",
|
|
2497
|
+
"operationId",
|
|
2498
|
+
"path",
|
|
2499
|
+
"method",
|
|
2500
|
+
"contentType",
|
|
2501
|
+
"extension"
|
|
2502
|
+
]);
|
|
2503
|
+
/**
|
|
2504
|
+
* The options bag a `NormalizedPlugin` starts with before a plugin refines it: a directory output
|
|
2505
|
+
* at the plugin root and empty filter lists.
|
|
2506
|
+
*/
|
|
2507
|
+
const defaultPluginOptions = () => ({
|
|
2508
|
+
output: {
|
|
2509
|
+
path: ".",
|
|
2510
|
+
mode: "directory"
|
|
2511
|
+
},
|
|
2512
|
+
exclude: [],
|
|
2513
|
+
override: []
|
|
2514
|
+
});
|
|
2515
|
+
/**
|
|
2516
|
+
* Fills in the `output`, `exclude`, and `override` a `NormalizedPlugin` needs from a plugin's raw
|
|
2517
|
+
* options, running `output` through `normalizeOutput`. Idempotent, so the driver can apply it after
|
|
2518
|
+
* `setOptions` has already run without disturbing an already-normalized bag.
|
|
2519
|
+
*/
|
|
2520
|
+
function normalizePluginOptions(rawOptions, pluginName) {
|
|
2521
|
+
const options = {
|
|
2522
|
+
...defaultPluginOptions(),
|
|
2523
|
+
...rawOptions ?? {}
|
|
2524
|
+
};
|
|
2525
|
+
const group = "group" in options ? options.group : void 0;
|
|
2526
|
+
options.output = normalizeOutput({
|
|
2527
|
+
output: options.output,
|
|
2528
|
+
group,
|
|
2529
|
+
pluginName
|
|
2530
|
+
});
|
|
2531
|
+
return options;
|
|
2532
|
+
}
|
|
2533
|
+
/**
|
|
2534
|
+
* Throws `KUBB_INVALID_PLUGIN_OPTIONS` when a `plugins` entry is not a plugin object, such as a
|
|
2535
|
+
* factory passed without calling it.
|
|
2536
|
+
*/
|
|
2537
|
+
function assertPluginEntry(entry, index) {
|
|
2538
|
+
if (typeof entry === "object" && entry !== null) return;
|
|
2539
|
+
const name = typeof entry === "function" ? entry.name || "pluginName" : void 0;
|
|
2540
|
+
throw new Diagnostics.Error({
|
|
2541
|
+
code: Diagnostics.code.invalidPluginOptions,
|
|
2542
|
+
severity: "error",
|
|
2543
|
+
message: name ? `plugins[${index}] is a function ("${name}"), not a plugin.` : `plugins[${index}] is ${entry === null ? "null" : typeof entry}, not a plugin.`,
|
|
2544
|
+
help: name ? `Call it: ${name}()` : "Pass the result of a plugin factory, for example `pluginTs()`, or remove the entry.",
|
|
2545
|
+
location: { kind: "config" }
|
|
2546
|
+
});
|
|
2547
|
+
}
|
|
2548
|
+
/**
|
|
2549
|
+
* Where a generator crashed: a label naming the node and, when the adapter set one, the node's
|
|
2550
|
+
* pointer into the input.
|
|
2551
|
+
*/
|
|
2552
|
+
function getCrashSite(node) {
|
|
2553
|
+
if (node.kind === ast.nodeKinds.schema) return {
|
|
2554
|
+
label: node.name ? `schema "${node.name}"` : "an inline schema",
|
|
2555
|
+
location: node.pointer ? {
|
|
2556
|
+
kind: "schema",
|
|
2557
|
+
pointer: node.pointer
|
|
2558
|
+
} : void 0
|
|
2559
|
+
};
|
|
2560
|
+
return {
|
|
2561
|
+
label: node.method && node.path ? `operation "${node.operationId}" (${node.method.toUpperCase()} ${node.path})` : `operation "${node.operationId}"`,
|
|
2562
|
+
location: node.pointer ? {
|
|
2563
|
+
kind: "operation",
|
|
2564
|
+
pointer: node.pointer
|
|
2565
|
+
} : void 0
|
|
2566
|
+
};
|
|
2567
|
+
}
|
|
2568
|
+
var KubbDriver = class {
|
|
2569
|
+
config;
|
|
2570
|
+
options;
|
|
2571
|
+
/**
|
|
2572
|
+
* The `InputNode` produced by the adapter. Set after adapter setup.
|
|
2573
|
+
*/
|
|
2574
|
+
inputNode = null;
|
|
2575
|
+
adapter = null;
|
|
2576
|
+
/**
|
|
2577
|
+
* Raw adapter source so `adapter.parse()` can run lazily.
|
|
2578
|
+
* Intentionally outlives the build, cleared by `dispose()`.
|
|
2579
|
+
*/
|
|
2580
|
+
#adapterSource = null;
|
|
2581
|
+
/**
|
|
2582
|
+
* Central file store for all generated files.
|
|
2583
|
+
* Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
|
|
2584
|
+
* add files. This property gives direct read/write access when needed.
|
|
2585
|
+
*/
|
|
2586
|
+
fileManager = new FileManager();
|
|
2587
|
+
plugins = /* @__PURE__ */ new Map();
|
|
2588
|
+
#memo = /* @__PURE__ */ new Map();
|
|
2589
|
+
/**
|
|
2590
|
+
* Removers for every listener the driver added (plugin, generator) so `dispose()` can detach
|
|
2591
|
+
* them in one pass. External `hooks.hook(...)` listeners are not tracked.
|
|
2592
|
+
*/
|
|
2593
|
+
#unhooks = [];
|
|
2594
|
+
constructor(config, options) {
|
|
2595
|
+
this.config = config;
|
|
2596
|
+
this.options = options;
|
|
2597
|
+
this.adapter = config.adapter ?? null;
|
|
2598
|
+
}
|
|
2599
|
+
/**
|
|
2600
|
+
* Checks the adapter's and parsers' `meta.compatibility`, then normalizes and checks every configured plugin, orders them, and registers their lifecycle handlers.
|
|
2601
|
+
* A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
|
|
2602
|
+
* `'post'`. When the config has an adapter, the adapter source is resolved from the input
|
|
2603
|
+
* so `run` can parse it later.
|
|
2604
|
+
*/
|
|
2605
|
+
async setup() {
|
|
2606
|
+
this.options.signal?.throwIfAborted();
|
|
2607
|
+
for (const extension of [this.config.adapter, ...this.config.parsers]) if (extension?.meta) checkCompatibility(extension.meta);
|
|
2608
|
+
const names = /* @__PURE__ */ new Set();
|
|
2609
|
+
const normalized = this.#sortPlugins(this.config.plugins.map((rawPlugin, index) => {
|
|
2610
|
+
assertPluginEntry(rawPlugin, index);
|
|
2611
|
+
if (rawPlugin.meta) checkCompatibility(rawPlugin.meta);
|
|
2612
|
+
const meta = resolveMeta(rawPlugin);
|
|
2613
|
+
if (names.has(meta.name)) throw new Diagnostics.Error({
|
|
2614
|
+
code: Diagnostics.code.invalidPluginOptions,
|
|
2615
|
+
severity: "error",
|
|
2616
|
+
message: `Plugin "${meta.name}" appears twice in \`plugins\`.`,
|
|
2617
|
+
help: "Remove the duplicate, or merge its options.",
|
|
2618
|
+
location: { kind: "config" }
|
|
2619
|
+
});
|
|
2620
|
+
names.add(meta.name);
|
|
2621
|
+
return {
|
|
2622
|
+
name: meta.name,
|
|
2623
|
+
meta,
|
|
2624
|
+
dependencies: typeof rawPlugin.dependencies === "function" ? rawPlugin.dependencies(rawPlugin.options ?? {}, { config: this.config }) : rawPlugin.dependencies,
|
|
2625
|
+
enforce: rawPlugin.enforce,
|
|
2626
|
+
hooks: rawPlugin.hooks,
|
|
2627
|
+
setup: rawPlugin.setup,
|
|
2628
|
+
options: rawPlugin.options ?? defaultPluginOptions(),
|
|
2629
|
+
resolver: createResolver({ pluginName: meta.name })
|
|
2630
|
+
};
|
|
2631
|
+
}));
|
|
2632
|
+
const byName = new Map(normalized.map((plugin) => [plugin.name, plugin]));
|
|
2633
|
+
for (const plugin of normalized) checkDependencies({
|
|
2634
|
+
name: plugin.name,
|
|
2635
|
+
dependencies: plugin.dependencies,
|
|
2636
|
+
plugins: byName
|
|
2637
|
+
});
|
|
2638
|
+
for (const plugin of normalized) {
|
|
2639
|
+
this.#registerPlugin(plugin);
|
|
2640
|
+
this.plugins.set(plugin.name, plugin);
|
|
2641
|
+
}
|
|
2642
|
+
if (this.config.adapter) this.#adapterSource = inputToAdapterSource(this.config);
|
|
2643
|
+
}
|
|
2644
|
+
/**
|
|
2645
|
+
* Orders plugins so every dependency runs before its dependents (Kahn's algorithm), with
|
|
2646
|
+
* `enforce` (`'pre'` before normal before `'post'`) and declaration order as tiebreaks.
|
|
2647
|
+
* A pairwise `Array.sort` comparator cannot do this: dependency relations are not transitive
|
|
2648
|
+
* at the comparator level, so a chain where A depends on B and B depends on C could come out
|
|
2649
|
+
* wrong when A and C are never compared directly. Dependencies on plugins missing from the
|
|
2650
|
+
* config are ignored here and surface later through `requirePlugin`.
|
|
2651
|
+
*/
|
|
2652
|
+
#sortPlugins(plugins) {
|
|
2653
|
+
const queue = [...plugins].sort((a, b) => compareEnforce(a.enforce, b.enforce));
|
|
2654
|
+
const names = new Set(queue.map((plugin) => plugin.name));
|
|
2655
|
+
const blockedBy = new Map(queue.map((plugin) => {
|
|
2656
|
+
const dependencies = Array.isArray(plugin.dependencies) ? plugin.dependencies : Object.keys(plugin.dependencies ?? {});
|
|
2657
|
+
return [plugin.name, new Set(dependencies.filter((name) => names.has(name) && name !== plugin.name))];
|
|
2658
|
+
}));
|
|
2659
|
+
const sorted = [];
|
|
2660
|
+
for (const _ of plugins) {
|
|
2661
|
+
const index = queue.findIndex((plugin) => blockedBy.get(plugin.name)?.size === 0);
|
|
2662
|
+
if (index === -1) throw new Diagnostics.Error({
|
|
2663
|
+
code: Diagnostics.code.invalidPluginOptions,
|
|
2664
|
+
severity: "error",
|
|
2665
|
+
message: `Plugin dependencies form a cycle: ${queue.map((plugin) => plugin.name).join(" → ")}.`,
|
|
2666
|
+
help: "Remove one of the `dependencies` entries so the plugins can be ordered.",
|
|
2667
|
+
location: { kind: "config" }
|
|
2668
|
+
});
|
|
2669
|
+
const [plugin] = queue.splice(index, 1);
|
|
2670
|
+
if (!plugin) break;
|
|
2671
|
+
sorted.push(plugin);
|
|
2672
|
+
for (const blockers of blockedBy.values()) blockers.delete(plugin.name);
|
|
2673
|
+
}
|
|
2674
|
+
return sorted;
|
|
2675
|
+
}
|
|
2676
|
+
get hooks() {
|
|
2677
|
+
return this.options.hooks;
|
|
2678
|
+
}
|
|
2679
|
+
/**
|
|
2680
|
+
* Parses the adapter source into `this.inputNode`. Idempotent, so repeated calls from
|
|
2681
|
+
* `run` do not re-parse.
|
|
2682
|
+
*/
|
|
2683
|
+
async #parseInput() {
|
|
2684
|
+
if (this.inputNode || !this.adapter || !this.#adapterSource) return;
|
|
2685
|
+
this.options.signal?.throwIfAborted();
|
|
2686
|
+
const source = this.#adapterSource;
|
|
2687
|
+
const checkout = source.type === "path" && gitInputRegExp.test(source.path) ? await checkoutGitInput(source.path, this.options.signal) : void 0;
|
|
2688
|
+
try {
|
|
2689
|
+
this.inputNode = await this.adapter.parse(checkout ? {
|
|
2690
|
+
type: "path",
|
|
2691
|
+
path: checkout.path
|
|
2692
|
+
} : source, { signal: this.options.signal });
|
|
2693
|
+
} catch (caughtError) {
|
|
2694
|
+
throw new Diagnostics.Error(Diagnostics.fromExtension(caughtError, {
|
|
2695
|
+
kind: "adapter",
|
|
2696
|
+
extension: this.adapter
|
|
2697
|
+
}));
|
|
2698
|
+
} finally {
|
|
2699
|
+
await checkout?.dispose();
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2702
|
+
/**
|
|
2703
|
+
* Registers a plugin's lifecycle hooks on the shared `Hookable` as pass-through listeners that
|
|
2704
|
+
* external tooling can observe via `hooks.hook(...)`. The returned remover is tracked for
|
|
2705
|
+
* `dispose`. `kubb:plugin:setup` is skipped here; `setupHooks` invokes it directly with a
|
|
2706
|
+
* plugin-scoped context.
|
|
2707
|
+
*
|
|
2708
|
+
* @internal
|
|
2709
|
+
*/
|
|
2710
|
+
#registerPlugin(plugin) {
|
|
2711
|
+
const { hooks } = plugin;
|
|
2712
|
+
if (!hooks) return;
|
|
2713
|
+
const { "kubb:plugin:setup": _setup, ...configHooks } = hooks;
|
|
2714
|
+
this.#unhooks.push(this.hooks.addHooks(configHooks));
|
|
2715
|
+
}
|
|
2716
|
+
/**
|
|
2717
|
+
* Runs each plugin's `setup` and `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
|
|
2718
|
+
* plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
|
|
2719
|
+
* `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
|
|
2720
|
+
* plugins can configure generators, resolvers, macros, and options before `buildStart`.
|
|
2721
|
+
*/
|
|
2722
|
+
async setupHooks() {
|
|
2723
|
+
for (const plugin of this.plugins.values()) {
|
|
2724
|
+
const setupHook = plugin.hooks?.["kubb:plugin:setup"];
|
|
2725
|
+
if (!plugin.setup && !setupHook) continue;
|
|
2726
|
+
const ctx = {
|
|
2727
|
+
config: this.config,
|
|
2728
|
+
options: plugin.options ?? {},
|
|
2729
|
+
addGenerator: (...generators) => {
|
|
2730
|
+
plugin.generators = [...plugin.generators ?? [], ...generators];
|
|
2731
|
+
},
|
|
2732
|
+
setResolver: (resolver) => {
|
|
2733
|
+
plugin.resolver = Resolver.merge(createResolver({ pluginName: plugin.name }), resolver);
|
|
2734
|
+
},
|
|
2735
|
+
addMacro: (macro) => {
|
|
2736
|
+
plugin.macros = [...plugin.macros ?? [], macro];
|
|
2737
|
+
},
|
|
2738
|
+
setMacros: (macros) => {
|
|
2739
|
+
plugin.macros = [...macros];
|
|
2740
|
+
},
|
|
2741
|
+
setOptions: (opts) => {
|
|
2742
|
+
plugin.options = normalizePluginOptions({
|
|
2743
|
+
...plugin.options,
|
|
2744
|
+
...opts
|
|
2745
|
+
}, plugin.name);
|
|
2746
|
+
},
|
|
2747
|
+
injectFile: (userFileNode) => {
|
|
2748
|
+
this.fileManager.add(ast.factory.createFile(userFileNode));
|
|
2749
|
+
},
|
|
2750
|
+
requirePlugin: ((name) => this.requirePlugin(name, { requiredBy: plugin.name })),
|
|
2751
|
+
memo: this.memo.bind(this)
|
|
2752
|
+
};
|
|
2753
|
+
try {
|
|
2754
|
+
await kubbContext.run(ctx, async () => {
|
|
2755
|
+
if (plugin.setup) plugin.options = normalizePluginOptions(await plugin.setup(ctx.options, ctx), plugin.name);
|
|
2756
|
+
await setupHook?.(ctx);
|
|
2757
|
+
});
|
|
2758
|
+
} catch (caughtError) {
|
|
2759
|
+
throw new Diagnostics.Error(Diagnostics.fromExtension(caughtError, {
|
|
2760
|
+
kind: "plugin",
|
|
2761
|
+
extension: plugin
|
|
2762
|
+
}));
|
|
2763
|
+
}
|
|
2764
|
+
}
|
|
2765
|
+
}
|
|
2766
|
+
/**
|
|
2767
|
+
* Runs the full plugin pipeline. Returns the diagnostics collected so far even
|
|
2768
|
+
* when an outer hook throws, since the orchestrator preserves partial state by capturing
|
|
2769
|
+
* the failure as a {@link Diagnostic} instead of propagating. Each plugin also
|
|
2770
|
+
* contributes a `timing` diagnostic for the run summary.
|
|
2771
|
+
*/
|
|
2772
|
+
async run() {
|
|
2773
|
+
const { hooks, config, fileManager } = this;
|
|
2774
|
+
const diagnostics = [];
|
|
2775
|
+
const parsersMap = /* @__PURE__ */ new Map();
|
|
2776
|
+
for (const parser of config.parsers) if (parser.extNames) for (const ext of parser.extNames) parsersMap.set(ext, parser);
|
|
2777
|
+
return Diagnostics.scope((diagnostic) => diagnostics.push(diagnostic), async () => {
|
|
2778
|
+
try {
|
|
2779
|
+
this.options.signal?.throwIfAborted();
|
|
2780
|
+
const outputRoot = resolve(config.root, config.output.path);
|
|
2781
|
+
await this.#parseInput();
|
|
2782
|
+
await this.setupHooks();
|
|
2783
|
+
for (const plugin of this.plugins.values()) {
|
|
2784
|
+
this.options.signal?.throwIfAborted();
|
|
2785
|
+
plugin.options = normalizePluginOptions(plugin.options, plugin.name);
|
|
2786
|
+
}
|
|
2787
|
+
if (this.adapter && this.inputNode) {
|
|
2788
|
+
const { meta, schemas, operations } = this.inputNode;
|
|
2789
|
+
const buildStartContext = this.#withFiles({
|
|
2790
|
+
config,
|
|
2791
|
+
adapter: this.adapter,
|
|
2792
|
+
meta,
|
|
2793
|
+
nodeCounts: {
|
|
2794
|
+
schemas: schemas.length,
|
|
2795
|
+
operations: operations.length
|
|
2796
|
+
},
|
|
2797
|
+
getPlugin: this.getPlugin.bind(this)
|
|
2798
|
+
});
|
|
2799
|
+
await hooks.callHook("kubb:build:start", buildStartContext);
|
|
2800
|
+
}
|
|
2801
|
+
const generatorPlugins = [];
|
|
2802
|
+
for (const plugin of this.plugins.values()) {
|
|
2803
|
+
const context = this.getContext(plugin);
|
|
2804
|
+
const hrStart = process.hrtime();
|
|
2805
|
+
try {
|
|
2806
|
+
await hooks.callHook("kubb:plugin:start", { plugin });
|
|
2807
|
+
} catch (caughtError) {
|
|
2808
|
+
diagnostics.push(...await this.#finishPlugin({
|
|
2809
|
+
plugin,
|
|
2810
|
+
hrStart,
|
|
2811
|
+
error: toError(caughtError)
|
|
2812
|
+
}));
|
|
2813
|
+
continue;
|
|
2814
|
+
}
|
|
2815
|
+
if ((plugin.generators?.length ?? 0) > 0) {
|
|
2816
|
+
generatorPlugins.push({
|
|
2817
|
+
plugin,
|
|
2818
|
+
context,
|
|
2819
|
+
hrStart
|
|
2820
|
+
});
|
|
2821
|
+
continue;
|
|
2822
|
+
}
|
|
2823
|
+
diagnostics.push(...await this.#finishPlugin({
|
|
2824
|
+
plugin,
|
|
2825
|
+
hrStart
|
|
2826
|
+
}));
|
|
2827
|
+
}
|
|
2828
|
+
diagnostics.push(...await this.#runGenerators(generatorPlugins));
|
|
2829
|
+
this.#inlineFiles(parsersMap);
|
|
2830
|
+
await hooks.callHook("kubb:plugins:end", this.#withFiles({ config }));
|
|
2831
|
+
if (this.options.cleanPath) await config.storage.empty(this.options.cleanPath);
|
|
2832
|
+
await fileManager.write(fileManager.files, {
|
|
2833
|
+
storage: config.storage,
|
|
2834
|
+
parsers: parsersMap,
|
|
2835
|
+
manifest: this.options.manifest,
|
|
2836
|
+
signal: this.options.signal,
|
|
2837
|
+
cleaned: this.options.cleanPath,
|
|
2838
|
+
hooks,
|
|
2839
|
+
config
|
|
2840
|
+
});
|
|
2841
|
+
await this.adapter?.settle?.();
|
|
2842
|
+
await hooks.callHook("kubb:build:end", {
|
|
2843
|
+
files: this.fileManager.files,
|
|
2844
|
+
config,
|
|
2845
|
+
outputDir: outputRoot
|
|
2846
|
+
});
|
|
2847
|
+
return { diagnostics: Diagnostics.dedupe(diagnostics) };
|
|
2848
|
+
} catch (caughtError) {
|
|
2849
|
+
await this.adapter?.settle?.();
|
|
2850
|
+
diagnostics.push(Diagnostics.from(caughtError));
|
|
2851
|
+
return { diagnostics: Diagnostics.dedupe(diagnostics) };
|
|
2852
|
+
}
|
|
2853
|
+
});
|
|
2854
|
+
}
|
|
2855
|
+
/**
|
|
2856
|
+
* Moves inline sources into the files that import them and drops the virtual files, before barrels
|
|
2857
|
+
* (`kubb:plugins:end`) and the write see them.
|
|
2858
|
+
*/
|
|
2859
|
+
#inlineFiles(parsers) {
|
|
2860
|
+
const { files, virtualPaths, problems } = ast.inlineFiles(this.fileManager.files, { language: (file) => parsers.get(file.extname)?.inline });
|
|
2861
|
+
if (virtualPaths.length === 0) return;
|
|
2862
|
+
this.fileManager.add(...files);
|
|
2863
|
+
this.fileManager.delete(...virtualPaths);
|
|
2864
|
+
if (problems.length > 0) Diagnostics.report({
|
|
2865
|
+
code: Diagnostics.code.inlineFailed,
|
|
2866
|
+
severity: "error",
|
|
2867
|
+
message: problems.map(({ path, message }) => `${path}: ${message}`).join("\n"),
|
|
2868
|
+
help: "Give every name the file imports an inline definition, register a parser with inline support for its extension, or stop marking the source as inline."
|
|
2869
|
+
});
|
|
2870
|
+
}
|
|
2871
|
+
/**
|
|
2872
|
+
* Widens `extra` with the files present at emit time and a bound `upsertFile`, the shape every
|
|
2873
|
+
* file-carrying hook context shares. Building it here in one place keeps the `files` and
|
|
2874
|
+
* `upsertFile` keys from being dropped by a stray spread at the call site.
|
|
2875
|
+
*/
|
|
2876
|
+
#withFiles(extra) {
|
|
2877
|
+
return {
|
|
2878
|
+
...extra,
|
|
2879
|
+
files: this.fileManager.files,
|
|
2880
|
+
upsertFile: (...files) => this.fileManager.upsert(...files)
|
|
2881
|
+
};
|
|
2882
|
+
}
|
|
2883
|
+
async #finishPlugin({ plugin, hrStart, error, crashSite }) {
|
|
2884
|
+
const duration = getElapsedMs(hrStart);
|
|
2885
|
+
await this.hooks.callHook("kubb:plugin:end", this.#withFiles({
|
|
2886
|
+
plugin,
|
|
2887
|
+
duration,
|
|
2888
|
+
success: !error,
|
|
2889
|
+
...error ? { error } : {},
|
|
2890
|
+
config: this.config
|
|
2891
|
+
}));
|
|
2892
|
+
const timing = Diagnostics.performance({
|
|
2893
|
+
plugin: plugin.name,
|
|
2894
|
+
duration
|
|
2895
|
+
});
|
|
2896
|
+
if (!error) return [timing];
|
|
2897
|
+
const diagnostic = Diagnostics.fromExtension(error, {
|
|
2898
|
+
kind: "plugin",
|
|
2899
|
+
extension: plugin
|
|
2900
|
+
});
|
|
2901
|
+
const site = diagnostic.code === Diagnostics.code.pluginFailed && !diagnostic.location ? crashSite : void 0;
|
|
2902
|
+
return [site ? {
|
|
2903
|
+
...diagnostic,
|
|
2904
|
+
message: `While generating ${site.label}: ${diagnostic.message}`,
|
|
2905
|
+
...site.location ? { location: site.location } : {}
|
|
2906
|
+
} : diagnostic, timing];
|
|
2907
|
+
}
|
|
2908
|
+
/**
|
|
2909
|
+
* Runs schemas and operations through every plugin's generators. The walk is node-outer: each
|
|
2910
|
+
* schema is visited once and each operation once, and the node fans out to the matching
|
|
2911
|
+
* generators of every plugin in dependency order. Each node still runs through the plugin's macros
|
|
2912
|
+
* and its exclude/include/override filters before that plugin's
|
|
2913
|
+
* generator sees it, so plugins stay isolated. Schemas run before operations so file output
|
|
2914
|
+
* stays deterministic across runs. A generator with a `match` predicate that resolves `false`
|
|
2915
|
+
* for a node is skipped for that node, without calling `schema`/`operation`.
|
|
2916
|
+
*
|
|
2917
|
+
* A failing plugin is dropped from the remaining walk, contributes an error diagnostic, and no
|
|
2918
|
+
* longer aborts the other plugins. `kubb:plugin:end` and each plugin's `timing` diagnostic fire
|
|
2919
|
+
* in dependency order once the walk finishes, driving the CLI's `Plugins N/M` counter. The
|
|
2920
|
+
* `operations` batch fires once per plugin after the single operation walk.
|
|
2921
|
+
*
|
|
2922
|
+
* When `this.inputNode` is `null`, every entry still gets a `kubb:plugin:end` so
|
|
2923
|
+
* post-plugin listeners (the barrel writer and friends) complete.
|
|
2924
|
+
*/
|
|
2925
|
+
async #runGenerators(entries) {
|
|
2926
|
+
const diagnostics = [];
|
|
2927
|
+
if (entries.length === 0) return diagnostics;
|
|
2928
|
+
if (!this.inputNode) {
|
|
2929
|
+
for (const { plugin, hrStart } of entries) diagnostics.push(...await this.#finishPlugin({
|
|
2930
|
+
plugin,
|
|
2931
|
+
hrStart
|
|
2932
|
+
}));
|
|
2933
|
+
return diagnostics;
|
|
2934
|
+
}
|
|
2935
|
+
const { schemas, operations } = this.inputNode;
|
|
2936
|
+
const allowedSchemaNamesByPlugin = /* @__PURE__ */ new Map();
|
|
2937
|
+
for (const { plugin } of entries) {
|
|
2938
|
+
const { exclude, include, override } = plugin.options;
|
|
2939
|
+
if (!((include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === "schemaName") ?? false))) continue;
|
|
2940
|
+
const resolver = this.getResolver(plugin.name);
|
|
2941
|
+
const includedOps = operations.filter((operation) => resolver.default.options(operation, {
|
|
2942
|
+
options: plugin.options,
|
|
2943
|
+
exclude,
|
|
2944
|
+
include,
|
|
2945
|
+
override
|
|
2946
|
+
}) !== null);
|
|
2947
|
+
allowedSchemaNamesByPlugin.set(plugin.name, collectUsedSchemaNames(includedOps, schemas));
|
|
2948
|
+
}
|
|
2949
|
+
const states = entries.map(({ plugin, context, hrStart }) => {
|
|
2950
|
+
const generatorContext = {
|
|
2951
|
+
...context,
|
|
2952
|
+
resolver: this.getResolver(plugin.name)
|
|
2953
|
+
};
|
|
2954
|
+
const { exclude, include, override } = plugin.options;
|
|
2955
|
+
const generators = plugin.generators ?? [];
|
|
2956
|
+
return {
|
|
2957
|
+
plugin,
|
|
2958
|
+
hrStart,
|
|
2959
|
+
generatorContext,
|
|
2960
|
+
exclude,
|
|
2961
|
+
include,
|
|
2962
|
+
override,
|
|
2963
|
+
optionsAreStatic: !exclude?.length && !include?.length && !override?.length,
|
|
2964
|
+
allowedSchemaNames: allowedSchemaNamesByPlugin.get(plugin.name) ?? null,
|
|
2965
|
+
schemaGenerators: generators.filter((generator) => generator.schema),
|
|
2966
|
+
schemas: /* @__PURE__ */ new Map(),
|
|
2967
|
+
operationGenerators: generators.filter((generator) => generator.operation),
|
|
2968
|
+
operationsGenerators: generators.filter((generator) => generator.operations),
|
|
2969
|
+
pluginOperations: [],
|
|
2970
|
+
error: null,
|
|
2971
|
+
crashSite: void 0
|
|
2972
|
+
};
|
|
2973
|
+
});
|
|
2974
|
+
const resolveForPlugin = (state, node) => {
|
|
2975
|
+
const transformedNode = ast.applyMacros(node, state.plugin.macros ?? []);
|
|
2976
|
+
if (state.optionsAreStatic) return {
|
|
2977
|
+
transformedNode,
|
|
2978
|
+
options: state.plugin.options
|
|
2979
|
+
};
|
|
2980
|
+
const options = state.generatorContext.resolver.default.options(transformedNode, {
|
|
2981
|
+
options: state.plugin.options,
|
|
2982
|
+
exclude: state.exclude,
|
|
2983
|
+
include: state.include,
|
|
2984
|
+
override: state.override
|
|
2985
|
+
});
|
|
2986
|
+
if (options === null) return null;
|
|
2987
|
+
return {
|
|
2988
|
+
transformedNode,
|
|
2989
|
+
options
|
|
2990
|
+
};
|
|
2991
|
+
};
|
|
2992
|
+
for (const state of states) {
|
|
2993
|
+
if (!state.schemaGenerators.length) continue;
|
|
2994
|
+
for (const node of schemas) try {
|
|
2995
|
+
const resolved = resolveForPlugin(state, node);
|
|
2996
|
+
if (!resolved) continue;
|
|
2997
|
+
const name = resolved.transformedNode.name;
|
|
2998
|
+
if (state.allowedSchemaNames !== null && name && !state.allowedSchemaNames.has(name)) continue;
|
|
2999
|
+
state.schemas.set(node, resolved);
|
|
3000
|
+
if (name) state.generatorContext.resolver.reserveNames([state.generatorContext.resolver.name(name)]);
|
|
3001
|
+
} catch (caughtError) {
|
|
3002
|
+
state.schemas.set(node, toError(caughtError));
|
|
3003
|
+
break;
|
|
3004
|
+
}
|
|
3005
|
+
}
|
|
3006
|
+
for (const node of schemas) for (const state of states) {
|
|
3007
|
+
if (state.error || !state.schemaGenerators.length) continue;
|
|
3008
|
+
try {
|
|
3009
|
+
const resolved = state.schemas.get(node);
|
|
3010
|
+
if (resolved instanceof Error) throw resolved;
|
|
3011
|
+
if (!resolved) continue;
|
|
3012
|
+
const { transformedNode, options } = resolved;
|
|
3013
|
+
const ctx = {
|
|
3014
|
+
...state.generatorContext,
|
|
3015
|
+
options
|
|
3016
|
+
};
|
|
3017
|
+
await this.#dispatchNode({
|
|
3018
|
+
generators: state.schemaGenerators,
|
|
3019
|
+
node: transformedNode,
|
|
3020
|
+
ctx,
|
|
3021
|
+
generate: (generator) => generator.schema(transformedNode, ctx)
|
|
3022
|
+
});
|
|
3023
|
+
await this.hooks.callHook("kubb:generate:schema", transformedNode, ctx);
|
|
3024
|
+
} catch (caughtError) {
|
|
3025
|
+
state.error = toError(caughtError);
|
|
3026
|
+
state.crashSite = getCrashSite(node);
|
|
3027
|
+
}
|
|
3028
|
+
}
|
|
3029
|
+
for (const node of operations) for (const state of states) {
|
|
3030
|
+
if (state.error || !state.operationGenerators.length && !state.operationsGenerators.length) continue;
|
|
3031
|
+
try {
|
|
3032
|
+
const resolved = resolveForPlugin(state, node);
|
|
3033
|
+
if (!resolved) continue;
|
|
3034
|
+
state.pluginOperations.push(resolved.transformedNode);
|
|
3035
|
+
if (state.operationGenerators.length) {
|
|
3036
|
+
const { transformedNode } = resolved;
|
|
3037
|
+
const ctx = {
|
|
3038
|
+
...state.generatorContext,
|
|
3039
|
+
options: resolved.options
|
|
3040
|
+
};
|
|
3041
|
+
await this.#dispatchNode({
|
|
3042
|
+
generators: state.operationGenerators,
|
|
3043
|
+
node: transformedNode,
|
|
3044
|
+
ctx,
|
|
3045
|
+
generate: (generator) => generator.operation(transformedNode, ctx)
|
|
3046
|
+
});
|
|
3047
|
+
await this.hooks.callHook("kubb:generate:operation", transformedNode, ctx);
|
|
3048
|
+
}
|
|
3049
|
+
} catch (caughtError) {
|
|
3050
|
+
state.error = toError(caughtError);
|
|
3051
|
+
state.crashSite = getCrashSite(node);
|
|
3052
|
+
}
|
|
3053
|
+
}
|
|
3054
|
+
for (const state of states) {
|
|
3055
|
+
if (state.error || !state.operationsGenerators.length) continue;
|
|
3056
|
+
try {
|
|
3057
|
+
const ctx = {
|
|
3058
|
+
...state.generatorContext,
|
|
3059
|
+
options: state.plugin.options
|
|
3060
|
+
};
|
|
3061
|
+
for (const generator of state.operationsGenerators) await this.fileManager.dispatch({
|
|
3062
|
+
result: await generator.operations(state.pluginOperations, ctx),
|
|
3063
|
+
renderer: generator.renderer
|
|
3064
|
+
});
|
|
3065
|
+
await this.hooks.callHook("kubb:generate:operations", state.pluginOperations, ctx);
|
|
3066
|
+
} catch (caughtError) {
|
|
3067
|
+
state.error = toError(caughtError);
|
|
3068
|
+
}
|
|
3069
|
+
}
|
|
3070
|
+
for (const { plugin, hrStart, error, crashSite } of states) diagnostics.push(...await this.#finishPlugin({
|
|
3071
|
+
plugin,
|
|
3072
|
+
hrStart,
|
|
3073
|
+
error: error ?? void 0,
|
|
3074
|
+
crashSite
|
|
3075
|
+
}));
|
|
3076
|
+
return diagnostics;
|
|
3077
|
+
}
|
|
3078
|
+
/**
|
|
3079
|
+
* Runs `node` through the generators whose `match` accepts it; `generate` picks the method for the
|
|
3080
|
+
* node kind.
|
|
3081
|
+
*/
|
|
3082
|
+
async #dispatchNode({ generators, node, ctx, generate }) {
|
|
3083
|
+
for (const generator of generators) {
|
|
3084
|
+
if (!(generator.match ? await generator.match(node, ctx) : true)) continue;
|
|
3085
|
+
await this.fileManager.dispatch({
|
|
3086
|
+
result: await generate(generator),
|
|
3087
|
+
renderer: generator.renderer,
|
|
3088
|
+
pointer: node.pointer
|
|
3089
|
+
});
|
|
3090
|
+
}
|
|
3091
|
+
}
|
|
3092
|
+
/**
|
|
3093
|
+
* Removes every listener the driver added. Listeners attached directly to `hooks` from outside
|
|
3094
|
+
* the driver survive. Called at the end of a build to prevent leaks across repeated builds.
|
|
3095
|
+
*
|
|
3096
|
+
* @internal
|
|
3097
|
+
*/
|
|
3098
|
+
dispose() {
|
|
3099
|
+
for (const unhook of this.#unhooks) unhook();
|
|
3100
|
+
this.#unhooks.length = 0;
|
|
3101
|
+
this.fileManager.dispose();
|
|
3102
|
+
this.inputNode = null;
|
|
3103
|
+
this.#adapterSource = null;
|
|
3104
|
+
this.#memo.clear();
|
|
3105
|
+
}
|
|
3106
|
+
[Symbol.dispose]() {
|
|
3107
|
+
this.dispose();
|
|
3108
|
+
}
|
|
3109
|
+
getResolver(pluginName) {
|
|
3110
|
+
return this.plugins.get(pluginName)?.resolver ?? createResolver({ pluginName });
|
|
3111
|
+
}
|
|
3112
|
+
memo(key, compute) {
|
|
3113
|
+
return memo$1(this.#memo, key, compute);
|
|
3114
|
+
}
|
|
3115
|
+
getContext(plugin) {
|
|
3116
|
+
const driver = this;
|
|
3117
|
+
const report = (diagnostic) => {
|
|
3118
|
+
Diagnostics.report({
|
|
3119
|
+
...diagnostic,
|
|
3120
|
+
plugin: plugin.name
|
|
3121
|
+
});
|
|
3122
|
+
};
|
|
3123
|
+
return {
|
|
3124
|
+
config: driver.config,
|
|
3125
|
+
signal: driver.options.signal,
|
|
3126
|
+
get root() {
|
|
3127
|
+
return resolve(driver.config.root, driver.config.output.path);
|
|
3128
|
+
},
|
|
3129
|
+
hooks: driver.hooks,
|
|
3130
|
+
plugin,
|
|
3131
|
+
getPlugin: driver.getPlugin.bind(driver),
|
|
3132
|
+
requirePlugin: ((name) => driver.requirePlugin(name, { requiredBy: plugin.name })),
|
|
3133
|
+
getResolver: driver.getResolver.bind(driver),
|
|
3134
|
+
memo: driver.memo.bind(driver),
|
|
3135
|
+
driver,
|
|
3136
|
+
addFile: async (...files) => {
|
|
3137
|
+
driver.fileManager.add(...files);
|
|
3138
|
+
},
|
|
3139
|
+
upsertFile: async (...files) => {
|
|
3140
|
+
driver.fileManager.upsert(...files);
|
|
3141
|
+
},
|
|
3142
|
+
get meta() {
|
|
3143
|
+
return driver.inputNode?.meta ?? {};
|
|
3144
|
+
},
|
|
3145
|
+
get adapter() {
|
|
3146
|
+
return driver.adapter;
|
|
3147
|
+
},
|
|
3148
|
+
get resolver() {
|
|
3149
|
+
return driver.getResolver(plugin.name);
|
|
3150
|
+
},
|
|
3151
|
+
warn(message, options) {
|
|
3152
|
+
report({
|
|
3153
|
+
code: Diagnostics.code.pluginWarning,
|
|
3154
|
+
severity: "warning",
|
|
3155
|
+
message,
|
|
3156
|
+
...options
|
|
3157
|
+
});
|
|
3158
|
+
},
|
|
3159
|
+
error(error, options) {
|
|
3160
|
+
if (Diagnostics.isError(error)) {
|
|
3161
|
+
report({
|
|
3162
|
+
...options,
|
|
3163
|
+
...error.diagnostic
|
|
3164
|
+
});
|
|
3165
|
+
return;
|
|
3166
|
+
}
|
|
3167
|
+
const cause = typeof error === "string" ? void 0 : error;
|
|
3168
|
+
report({
|
|
3169
|
+
code: Diagnostics.code.pluginFailed,
|
|
3170
|
+
severity: "error",
|
|
3171
|
+
message: typeof error === "string" ? error : error.message,
|
|
3172
|
+
cause,
|
|
3173
|
+
...options
|
|
3174
|
+
});
|
|
3175
|
+
},
|
|
3176
|
+
info(message, options) {
|
|
3177
|
+
report({
|
|
3178
|
+
code: Diagnostics.code.pluginInfo,
|
|
3179
|
+
severity: "info",
|
|
3180
|
+
message,
|
|
3181
|
+
...options
|
|
3182
|
+
});
|
|
3183
|
+
}
|
|
3184
|
+
};
|
|
3185
|
+
}
|
|
3186
|
+
getPlugin(pluginName) {
|
|
3187
|
+
return this.plugins.get(pluginName);
|
|
3188
|
+
}
|
|
3189
|
+
requirePlugin(pluginName, context) {
|
|
3190
|
+
const plugin = this.getPlugin(pluginName);
|
|
3191
|
+
if (plugin) return plugin;
|
|
3192
|
+
throw pluginNotFoundError({
|
|
3193
|
+
pluginName,
|
|
3194
|
+
requiredBy: context?.requiredBy
|
|
3195
|
+
});
|
|
3196
|
+
}
|
|
3197
|
+
};
|
|
3198
|
+
/** The `KUBB_PLUGIN_NOT_FOUND` error `requirePlugin` throws, naming the plugin that needed it. */
|
|
3199
|
+
function pluginNotFoundError({ pluginName, requiredBy }) {
|
|
3200
|
+
const by = requiredBy ? ` by "${requiredBy}"` : "";
|
|
3201
|
+
const help = requiredBy ? ` (required by "${requiredBy}")` : "";
|
|
3202
|
+
return new Diagnostics.Error({
|
|
3203
|
+
code: Diagnostics.code.pluginNotFound,
|
|
3204
|
+
severity: "error",
|
|
3205
|
+
message: `Plugin "${pluginName}" is required${by} but not found. Make sure it is included in your Kubb config.`,
|
|
3206
|
+
help: `Add "${pluginName}" to the \`plugins\` array in kubb.config.ts${help}, or remove the dependency on it.`,
|
|
3207
|
+
location: { kind: "config" },
|
|
3208
|
+
...requiredBy ? { plugin: requiredBy } : {}
|
|
164
3209
|
});
|
|
165
3210
|
}
|
|
166
3211
|
// src/outputManifest.ts
|
|
@@ -309,12 +3354,7 @@ const fsStorage = createStorage(() => ({
|
|
|
309
3354
|
await rm$1(resolve(key), { force: true });
|
|
310
3355
|
},
|
|
311
3356
|
async readKeys(base) {
|
|
312
|
-
|
|
313
|
-
const keys = [];
|
|
314
|
-
try {
|
|
315
|
-
for await (const path of listFiles(resolvedBase)) keys.push(path);
|
|
316
|
-
} catch (_error) {}
|
|
317
|
-
return keys;
|
|
3357
|
+
return Array.fromAsync(listFiles(resolve(base ?? process.cwd()))).catch(() => []);
|
|
318
3358
|
},
|
|
319
3359
|
async empty(base) {
|
|
320
3360
|
if (!base) return;
|
|
@@ -371,14 +3411,113 @@ const cacheStorage = createStorage(({ root = process.cwd() }) => {
|
|
|
371
3411
|
name: "cache",
|
|
372
3412
|
readItem: (key) => fs.readItem(toPath(key)),
|
|
373
3413
|
async writeItem(key, value) {
|
|
374
|
-
|
|
375
|
-
await writeRaw(filePath, value);
|
|
3414
|
+
await writeRaw(toPath(key), value);
|
|
376
3415
|
},
|
|
377
3416
|
removeItem: (key) => fs.removeItem(toPath(key)),
|
|
378
3417
|
readKeys: (base) => fs.readKeys(base ? toPath(base) : dir),
|
|
379
3418
|
empty: async (base) => base ? fs.empty(toPath(base)) : void 0
|
|
380
3419
|
};
|
|
381
3420
|
});
|
|
3421
|
+
// src/Hookable.ts
|
|
3422
|
+
/**
|
|
3423
|
+
* Typed hook emitter that awaits all async listeners before resolving.
|
|
3424
|
+
*
|
|
3425
|
+
* @example
|
|
3426
|
+
* ```ts
|
|
3427
|
+
* const hooks = new Hookable<{ build: [name: string] }>()
|
|
3428
|
+
* hooks.hook('build', async (name) => { console.log(name) })
|
|
3429
|
+
* await hooks.callHook('build', 'petstore') // all listeners awaited
|
|
3430
|
+
* ```
|
|
3431
|
+
*/
|
|
3432
|
+
var Hookable = class {
|
|
3433
|
+
#listeners = /* @__PURE__ */ new Map();
|
|
3434
|
+
/**
|
|
3435
|
+
* Calls `hookName` and awaits all registered listeners sequentially.
|
|
3436
|
+
* Throws if any listener rejects, wrapping the cause in an error that names the hook.
|
|
3437
|
+
*
|
|
3438
|
+
* @example
|
|
3439
|
+
* ```ts
|
|
3440
|
+
* await hooks.callHook('build', 'petstore')
|
|
3441
|
+
* ```
|
|
3442
|
+
*/
|
|
3443
|
+
callHook(hookName, ...hookArgs) {
|
|
3444
|
+
const listeners = this.#listeners.get(hookName);
|
|
3445
|
+
if (!listeners?.size) return;
|
|
3446
|
+
return this.#emitAll(hookName, [...listeners], hookArgs);
|
|
3447
|
+
}
|
|
3448
|
+
async #emitAll(hookName, listeners, hookArgs) {
|
|
3449
|
+
for (const listener of listeners) try {
|
|
3450
|
+
await listener(...hookArgs);
|
|
3451
|
+
} catch (err) {
|
|
3452
|
+
throw new Error(`Error in async listener for "${hookName}"`, { cause: toError(err) });
|
|
3453
|
+
}
|
|
3454
|
+
}
|
|
3455
|
+
/**
|
|
3456
|
+
* Registers a persistent listener for `hookName` and returns a function that removes it.
|
|
3457
|
+
*
|
|
3458
|
+
* @example
|
|
3459
|
+
* ```ts
|
|
3460
|
+
* const unhook = hooks.hook('build', async (name) => { console.log(name) })
|
|
3461
|
+
* unhook() // removes it
|
|
3462
|
+
* ```
|
|
3463
|
+
*/
|
|
3464
|
+
hook(hookName, handler) {
|
|
3465
|
+
let listeners = this.#listeners.get(hookName);
|
|
3466
|
+
if (!listeners) this.#listeners.set(hookName, listeners = /* @__PURE__ */ new Set());
|
|
3467
|
+
listeners.add(handler);
|
|
3468
|
+
return () => this.removeHook(hookName, handler);
|
|
3469
|
+
}
|
|
3470
|
+
/**
|
|
3471
|
+
* Registers every handler in `configHooks` at once and returns a function that removes them
|
|
3472
|
+
* all. Undefined entries are skipped, so a partial hook object registers only its present keys.
|
|
3473
|
+
*
|
|
3474
|
+
* @example
|
|
3475
|
+
* ```ts
|
|
3476
|
+
* const unhook = hooks.addHooks({ build: onBuild, done: onDone })
|
|
3477
|
+
* unhook() // removes both
|
|
3478
|
+
* ```
|
|
3479
|
+
*/
|
|
3480
|
+
addHooks(configHooks) {
|
|
3481
|
+
const unhooks = Object.keys(configHooks).filter((name) => configHooks[name]).map((name) => this.hook(name, configHooks[name]));
|
|
3482
|
+
return () => {
|
|
3483
|
+
for (const unhook of unhooks) unhook();
|
|
3484
|
+
};
|
|
3485
|
+
}
|
|
3486
|
+
/**
|
|
3487
|
+
* Removes a previously registered listener.
|
|
3488
|
+
*
|
|
3489
|
+
* @example
|
|
3490
|
+
* ```ts
|
|
3491
|
+
* hooks.removeHook('build', handler)
|
|
3492
|
+
* ```
|
|
3493
|
+
*/
|
|
3494
|
+
removeHook(hookName, handler) {
|
|
3495
|
+
this.#listeners.get(hookName)?.delete(handler);
|
|
3496
|
+
}
|
|
3497
|
+
/**
|
|
3498
|
+
* Returns the number of listeners registered for `hookName`.
|
|
3499
|
+
*
|
|
3500
|
+
* @example
|
|
3501
|
+
* ```ts
|
|
3502
|
+
* hooks.hook('build', handler)
|
|
3503
|
+
* hooks.listenerCount('build') // 1
|
|
3504
|
+
* ```
|
|
3505
|
+
*/
|
|
3506
|
+
listenerCount(hookName) {
|
|
3507
|
+
return this.#listeners.get(hookName)?.size ?? 0;
|
|
3508
|
+
}
|
|
3509
|
+
/**
|
|
3510
|
+
* Removes all listeners from every hook channel.
|
|
3511
|
+
*
|
|
3512
|
+
* @example
|
|
3513
|
+
* ```ts
|
|
3514
|
+
* hooks.removeAllHooks()
|
|
3515
|
+
* ```
|
|
3516
|
+
*/
|
|
3517
|
+
removeAllHooks() {
|
|
3518
|
+
this.#listeners.clear();
|
|
3519
|
+
}
|
|
3520
|
+
};
|
|
382
3521
|
// src/output/runHook.ts
|
|
383
3522
|
const KILL_GRACE_MS = 2e3;
|
|
384
3523
|
async function settle(proc, hooks, id, commandWithArgs) {
|
|
@@ -847,27 +3986,96 @@ const logLevel = {
|
|
|
847
3986
|
*/
|
|
848
3987
|
function createReporter(reporter) {
|
|
849
3988
|
const { name, needsPluginFiles, drain } = reporter;
|
|
850
|
-
if (!drain) return {
|
|
851
|
-
name,
|
|
852
|
-
needsPluginFiles,
|
|
853
|
-
async report(result, context) {
|
|
854
|
-
await reporter.report(result, context);
|
|
855
|
-
}
|
|
856
|
-
};
|
|
857
3989
|
const reports = [];
|
|
858
3990
|
return {
|
|
859
3991
|
name,
|
|
860
3992
|
needsPluginFiles,
|
|
861
3993
|
async report(result, context) {
|
|
862
|
-
|
|
3994
|
+
const report = await reporter.report(result, context);
|
|
3995
|
+
if (drain) reports.push(report);
|
|
863
3996
|
},
|
|
864
|
-
async drain(context) {
|
|
3997
|
+
...drain && { async drain(context) {
|
|
865
3998
|
await drain(context, reports.splice(0));
|
|
3999
|
+
} }
|
|
4000
|
+
};
|
|
4001
|
+
}
|
|
4002
|
+
// src/storages/kubbStorage.ts
|
|
4003
|
+
function ensurePrivateDir(dir) {
|
|
4004
|
+
mkdirSync(dir, {
|
|
4005
|
+
recursive: true,
|
|
4006
|
+
mode: 448
|
|
4007
|
+
});
|
|
4008
|
+
chmodSync(dir, 448);
|
|
4009
|
+
return dir;
|
|
4010
|
+
}
|
|
4011
|
+
/**
|
|
4012
|
+
* Folder Kubb keeps its own files in, created with mode 0700. `base` resolves inside `KUBB_HOME`
|
|
4013
|
+
* (default `~/.kubb`). When that folder is not writable, it falls back to a folder in the OS temp directory.
|
|
4014
|
+
*
|
|
4015
|
+
* @example
|
|
4016
|
+
* `resolveKubbDir('cache') // '/home/me/.kubb/cache'`
|
|
4017
|
+
*/
|
|
4018
|
+
function resolveKubbDir(base = "") {
|
|
4019
|
+
const dir = resolve(process$1.env.KUBB_HOME ?? join(homedir(), ".kubb"), base);
|
|
4020
|
+
try {
|
|
4021
|
+
return ensurePrivateDir(dir);
|
|
4022
|
+
} catch {
|
|
4023
|
+
return ensurePrivateDir(join(tmpdir(), "kubb", hash("sha256", dir).slice(0, 16)));
|
|
4024
|
+
}
|
|
4025
|
+
}
|
|
4026
|
+
/**
|
|
4027
|
+
* Key-value files rooted at {@link resolveKubbDir}. Each key is a file path inside that folder.
|
|
4028
|
+
* Strings are stored as is and other values as JSON. `getItem` parses JSON and falls back to the
|
|
4029
|
+
* raw string. The 0700 folder keeps files such as a stored token private.
|
|
4030
|
+
*
|
|
4031
|
+
* @example
|
|
4032
|
+
* ```ts
|
|
4033
|
+
* const storage = kubbStorage({ base: 'cache' })
|
|
4034
|
+
* await storage.setItem('machine-secret', secret)
|
|
4035
|
+
* ```
|
|
4036
|
+
*/
|
|
4037
|
+
function kubbStorage({ base } = {}) {
|
|
4038
|
+
const dir = resolveKubbDir(base);
|
|
4039
|
+
const pathOf = (key) => {
|
|
4040
|
+
const path = resolve(dir, key.replaceAll(":", "/"));
|
|
4041
|
+
if (path === dir || !isPathInside(path, dir)) throw new Error(`Invalid key: ${JSON.stringify(key)}. It should not leave the storage folder`);
|
|
4042
|
+
return path;
|
|
4043
|
+
};
|
|
4044
|
+
return {
|
|
4045
|
+
async getItem(key) {
|
|
4046
|
+
const path = pathOf(key);
|
|
4047
|
+
if (!await exists(path)) return null;
|
|
4048
|
+
const raw = await read(path);
|
|
4049
|
+
try {
|
|
4050
|
+
return JSON.parse(raw);
|
|
4051
|
+
} catch {
|
|
4052
|
+
return raw;
|
|
4053
|
+
}
|
|
4054
|
+
},
|
|
4055
|
+
async setItem(key, value) {
|
|
4056
|
+
await writeRaw(pathOf(key), typeof value === "string" ? value : JSON.stringify(value));
|
|
4057
|
+
},
|
|
4058
|
+
async removeItem(key) {
|
|
4059
|
+
await rm$1(pathOf(key), { force: true });
|
|
866
4060
|
}
|
|
867
4061
|
};
|
|
868
4062
|
}
|
|
869
4063
|
// src/reporters/report.ts
|
|
870
4064
|
/**
|
|
4065
|
+
* The `.kubb` folder and file name a reporter writes to; the sanitized name keeps the file inside the folder.
|
|
4066
|
+
*/
|
|
4067
|
+
function reportTarget(config) {
|
|
4068
|
+
const name = config.name?.replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
4069
|
+
return {
|
|
4070
|
+
dir: resolveKubbDir(resolve(process$1.cwd(), ".kubb")),
|
|
4071
|
+
name: [
|
|
4072
|
+
"kubb",
|
|
4073
|
+
name,
|
|
4074
|
+
Date.now()
|
|
4075
|
+
].filter(Boolean).join("-")
|
|
4076
|
+
};
|
|
4077
|
+
}
|
|
4078
|
+
/**
|
|
871
4079
|
* Builds the normalized {@link Report} for one config from its {@link GenerationResult}. Splits the
|
|
872
4080
|
* diagnostics into problems and per-plugin timings (slowest first) and derives the plugin and issue
|
|
873
4081
|
* counts, so every reporter renders the same data.
|
|
@@ -988,67 +4196,6 @@ function createCliReporter({ render = consoleRenderer } = {}) {
|
|
|
988
4196
|
* logger view.
|
|
989
4197
|
*/
|
|
990
4198
|
const cliReporter = createCliReporter();
|
|
991
|
-
// src/storages/kubbStorage.ts
|
|
992
|
-
function ensurePrivateDir(dir) {
|
|
993
|
-
mkdirSync(dir, {
|
|
994
|
-
recursive: true,
|
|
995
|
-
mode: 448
|
|
996
|
-
});
|
|
997
|
-
chmodSync(dir, 448);
|
|
998
|
-
return dir;
|
|
999
|
-
}
|
|
1000
|
-
/**
|
|
1001
|
-
* Folder Kubb keeps its own files in, created with mode 0700. `base` resolves inside `KUBB_HOME`
|
|
1002
|
-
* (default `~/.kubb`). When that folder is not writable, it falls back to a folder in the OS temp directory.
|
|
1003
|
-
*
|
|
1004
|
-
* @example
|
|
1005
|
-
* `resolveKubbDir('cache') // '/home/me/.kubb/cache'`
|
|
1006
|
-
*/
|
|
1007
|
-
function resolveKubbDir(base = "") {
|
|
1008
|
-
const dir = resolve(process$1.env.KUBB_HOME ?? join(homedir(), ".kubb"), base);
|
|
1009
|
-
try {
|
|
1010
|
-
return ensurePrivateDir(dir);
|
|
1011
|
-
} catch {
|
|
1012
|
-
return ensurePrivateDir(join(tmpdir(), "kubb", hash("sha256", dir).slice(0, 16)));
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
/**
|
|
1016
|
-
* Key-value files rooted at {@link resolveKubbDir}. Each key is a file path inside that folder.
|
|
1017
|
-
* Strings are stored as is and other values as JSON. `getItem` parses JSON and falls back to the
|
|
1018
|
-
* raw string. The 0700 folder keeps files such as a stored token private.
|
|
1019
|
-
*
|
|
1020
|
-
* @example
|
|
1021
|
-
* ```ts
|
|
1022
|
-
* const storage = kubbStorage({ base: 'cache' })
|
|
1023
|
-
* await storage.setItem('machine-secret', secret)
|
|
1024
|
-
* ```
|
|
1025
|
-
*/
|
|
1026
|
-
function kubbStorage({ base } = {}) {
|
|
1027
|
-
const dir = resolveKubbDir(base);
|
|
1028
|
-
const pathOf = (key) => {
|
|
1029
|
-
const path = resolve(dir, key.replaceAll(":", "/"));
|
|
1030
|
-
if (path === dir || !isPathInside(path, dir)) throw new Error(`Invalid key: ${JSON.stringify(key)}. It should not leave the storage folder`);
|
|
1031
|
-
return path;
|
|
1032
|
-
};
|
|
1033
|
-
return {
|
|
1034
|
-
async getItem(key) {
|
|
1035
|
-
const path = pathOf(key);
|
|
1036
|
-
if (!await exists(path)) return null;
|
|
1037
|
-
const raw = await read(path);
|
|
1038
|
-
try {
|
|
1039
|
-
return JSON.parse(raw);
|
|
1040
|
-
} catch {
|
|
1041
|
-
return raw;
|
|
1042
|
-
}
|
|
1043
|
-
},
|
|
1044
|
-
async setItem(key, value) {
|
|
1045
|
-
await writeRaw(pathOf(key), typeof value === "string" ? value : JSON.stringify(value));
|
|
1046
|
-
},
|
|
1047
|
-
async removeItem(key) {
|
|
1048
|
-
await rm$1(pathOf(key), { force: true });
|
|
1049
|
-
}
|
|
1050
|
-
};
|
|
1051
|
-
}
|
|
1052
4199
|
// src/reporters/fileReporter.ts
|
|
1053
4200
|
/**
|
|
1054
4201
|
* Builds the `## Problems` section: each problem rendered in the miette block format, blocks
|
|
@@ -1087,14 +4234,10 @@ const fileReporter = createReporter({
|
|
|
1087
4234
|
...formatSummary(report, { showTimings: true })
|
|
1088
4235
|
], buildProblemSection(diagnostics)].filter((section) => section.length > 0);
|
|
1089
4236
|
const content = stripVTControlCharacters([header, ...sections.map((section) => section.join("\n"))].join("\n\n"));
|
|
1090
|
-
const
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
].filter(Boolean).join("-")}.log`;
|
|
1095
|
-
const dir = resolveKubbDir(resolve(process$1.cwd(), ".kubb"));
|
|
1096
|
-
await kubbStorage({ base: dir }).setItem(baseName, `${content}\n`);
|
|
1097
|
-
console.error(`Debug log written to ${relative(process$1.cwd(), join(dir, baseName))}`);
|
|
4237
|
+
const { dir, name } = reportTarget(config);
|
|
4238
|
+
const path = join(dir, `${name}.log`);
|
|
4239
|
+
await writeRaw(path, `${content}\n`);
|
|
4240
|
+
console.error(`Debug log written to ${relative(process$1.cwd(), path)}`);
|
|
1098
4241
|
}
|
|
1099
4242
|
});
|
|
1100
4243
|
// src/reporters/jsonReporter.ts
|
|
@@ -1129,21 +4272,15 @@ const htmlReporter = createReporter({
|
|
|
1129
4272
|
name: "html",
|
|
1130
4273
|
needsPluginFiles: true,
|
|
1131
4274
|
async report(result) {
|
|
1132
|
-
const
|
|
1133
|
-
"kubb",
|
|
1134
|
-
result.config.name?.replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, ""),
|
|
1135
|
-
Date.now()
|
|
1136
|
-
].filter(Boolean).join("-");
|
|
1137
|
-
const dir = resolveKubbDir(resolve(process.cwd(), ".kubb"));
|
|
1138
|
-
const storage = kubbStorage({ base: dir });
|
|
4275
|
+
const { dir, name } = reportTarget(result.config);
|
|
1139
4276
|
const assets = new URL("./html/", import.meta.url);
|
|
1140
4277
|
const [html, ui] = await Promise.all([read(fileURLToPath(new URL("index.html", assets))), read(fileURLToPath(new URL("ui.iife.js", assets)))]);
|
|
1141
4278
|
await Promise.all([
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
4279
|
+
writeRaw(join(dir, name, "index.html"), html),
|
|
4280
|
+
writeRaw(join(dir, name, "ui.iife.js"), ui),
|
|
4281
|
+
writeRaw(join(dir, name, "data.js"), serializeReport(result))
|
|
1145
4282
|
]);
|
|
1146
|
-
const reportPath = join(dir,
|
|
4283
|
+
const reportPath = join(dir, name, "index.html");
|
|
1147
4284
|
console.error(`HTML report written to ${relative(process.cwd(), reportPath)}`);
|
|
1148
4285
|
openInBrowser(reportPath);
|
|
1149
4286
|
}
|
|
@@ -1264,11 +4401,7 @@ const memoryStorage = createStorage(() => {
|
|
|
1264
4401
|
return base ? keys.filter((k) => k.startsWith(base)) : keys;
|
|
1265
4402
|
},
|
|
1266
4403
|
async empty(base) {
|
|
1267
|
-
if (!base)
|
|
1268
|
-
store.clear();
|
|
1269
|
-
return;
|
|
1270
|
-
}
|
|
1271
|
-
for (const key of store.keys()) if (key.startsWith(base)) store.delete(key);
|
|
4404
|
+
for (const key of store.keys()) if (!base || key.startsWith(base)) store.delete(key);
|
|
1272
4405
|
}
|
|
1273
4406
|
};
|
|
1274
4407
|
});
|