@kubb/core 5.0.0-beta.11 → 5.0.0-beta.110

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.
Files changed (44) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +20 -123
  3. package/dist/index.cjs +2430 -1184
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.ts +136 -140
  6. package/dist/index.js +2419 -1173
  7. package/dist/index.js.map +1 -1
  8. package/dist/mocks.cjs +86 -32
  9. package/dist/mocks.cjs.map +1 -1
  10. package/dist/mocks.d.ts +37 -14
  11. package/dist/mocks.js +88 -36
  12. package/dist/mocks.js.map +1 -1
  13. package/dist/types-Ba5Mo-G8.d.ts +3016 -0
  14. package/dist/usingCtx-BdYw7ICK.cjs +954 -0
  15. package/dist/usingCtx-BdYw7ICK.cjs.map +1 -0
  16. package/dist/usingCtx-njZUKKsY.js +822 -0
  17. package/dist/usingCtx-njZUKKsY.js.map +1 -0
  18. package/package.json +7 -28
  19. package/dist/PluginDriver-C1OsqGBJ.cjs +0 -1086
  20. package/dist/PluginDriver-C1OsqGBJ.cjs.map +0 -1
  21. package/dist/PluginDriver-CGypdXHg.js +0 -989
  22. package/dist/PluginDriver-CGypdXHg.js.map +0 -1
  23. package/dist/createKubb-BSfMDBwR.d.ts +0 -2176
  24. package/src/FileManager.ts +0 -123
  25. package/src/FileProcessor.ts +0 -91
  26. package/src/PluginDriver.ts +0 -466
  27. package/src/constants.ts +0 -39
  28. package/src/createAdapter.ts +0 -108
  29. package/src/createKubb.ts +0 -1380
  30. package/src/createRenderer.ts +0 -57
  31. package/src/createStorage.ts +0 -70
  32. package/src/defineGenerator.ts +0 -175
  33. package/src/defineLogger.ts +0 -58
  34. package/src/defineMiddleware.ts +0 -62
  35. package/src/defineParser.ts +0 -44
  36. package/src/definePlugin.ts +0 -379
  37. package/src/defineResolver.ts +0 -654
  38. package/src/devtools.ts +0 -66
  39. package/src/index.ts +0 -20
  40. package/src/mocks.ts +0 -177
  41. package/src/storages/fsStorage.ts +0 -89
  42. package/src/storages/memoryStorage.ts +0 -55
  43. package/src/types.ts +0 -42
  44. /package/dist/{chunk--u3MIqq1.js → rolldown-runtime-C0LytTxp.js} +0 -0
@@ -1,123 +0,0 @@
1
- import type { FileNode } from '@kubb/ast'
2
- import { createFile } from '@kubb/ast'
3
-
4
- function mergeFile<TMeta extends object = object>(a: FileNode<TMeta>, b: FileNode<TMeta>): FileNode<TMeta> {
5
- return {
6
- ...a,
7
- // Incoming file (b) takes precedence for banner/footer so that barrel files,
8
- // which never carry a banner, can clear banners set by plugin-generated files
9
- // at the same path.
10
- banner: b.banner,
11
- footer: b.footer,
12
- sources: [...(a.sources || []), ...(b.sources || [])],
13
- imports: [...(a.imports || []), ...(b.imports || [])],
14
- exports: [...(a.exports || []), ...(b.exports || [])],
15
- }
16
- }
17
-
18
- /**
19
- * Collapses a list of files so that duplicates sharing the same `path` are merged
20
- * in arrival order. Keeps the original order of first occurrence.
21
- */
22
- function mergeFilesByPath(files: ReadonlyArray<FileNode>): Map<string, FileNode> {
23
- const merged = new Map<string, FileNode>()
24
- for (const file of files) {
25
- const existing = merged.get(file.path)
26
- merged.set(file.path, existing ? mergeFile(existing, file) : file)
27
- }
28
- return merged
29
- }
30
-
31
- /**
32
- * In-memory file store for generated files.
33
- *
34
- * Files with the same `path` are merged — sources, imports, and exports are concatenated.
35
- * The `files` getter returns all stored files sorted by path length (shortest first).
36
- *
37
- * @example
38
- * ```ts
39
- * import { FileManager } from '@kubb/core'
40
- *
41
- * const manager = new FileManager()
42
- * manager.upsert(myFile)
43
- * console.log(manager.files) // all stored files
44
- * ```
45
- */
46
- export class FileManager {
47
- readonly #cache = new Map<string, FileNode>()
48
- #filesCache: Array<FileNode> | null = null
49
-
50
- /**
51
- * Adds one or more files. Incoming files with the same path are merged
52
- * (sources/imports/exports concatenated), but existing cache entries are
53
- * replaced — use {@link upsert} when you want to merge into the cache too.
54
- */
55
- add(...files: Array<FileNode>): Array<FileNode> {
56
- return this.#store(files, false)
57
- }
58
-
59
- /**
60
- * Adds or merges one or more files.
61
- * If a file with the same path already exists in the cache, its
62
- * sources/imports/exports are merged into the incoming file.
63
- */
64
- upsert(...files: Array<FileNode>): Array<FileNode> {
65
- return this.#store(files, true)
66
- }
67
-
68
- #store(files: ReadonlyArray<FileNode>, mergeExisting: boolean): Array<FileNode> {
69
- const resolvedFiles: Array<FileNode> = []
70
- for (const file of mergeFilesByPath(files).values()) {
71
- const existing = mergeExisting ? this.#cache.get(file.path) : undefined
72
- const resolvedFile = createFile(existing ? mergeFile(existing, file) : file)
73
- this.#cache.set(resolvedFile.path, resolvedFile)
74
- resolvedFiles.push(resolvedFile)
75
- }
76
- this.#filesCache = null
77
- return resolvedFiles
78
- }
79
-
80
- getByPath(path: string): FileNode | null {
81
- return this.#cache.get(path) ?? null
82
- }
83
-
84
- deleteByPath(path: string): void {
85
- this.#cache.delete(path)
86
- this.#filesCache = null
87
- }
88
-
89
- clear(): void {
90
- this.#cache.clear()
91
- this.#filesCache = null
92
- }
93
-
94
- /**
95
- * Releases all stored files. Called by the core after `kubb:build:end` to
96
- * free the per-plugin FileNode caches for the rest of the process lifetime.
97
- */
98
- dispose(): void {
99
- this.clear()
100
- }
101
-
102
- /**
103
- * All stored files, sorted by path length (shorter paths first).
104
- */
105
- get files(): Array<FileNode> {
106
- if (this.#filesCache) {
107
- return this.#filesCache
108
- }
109
-
110
- this.#filesCache = [...this.#cache.values()].sort((a, b) => {
111
- const lenDiff = a.path.length - b.path.length
112
- if (lenDiff !== 0) return lenDiff
113
- // Within the same length bucket, index.ts barrel files go last so other
114
- // files are always processed before their barrel file.
115
- const aIsIndex = a.path.endsWith('/index.ts') || a.path === 'index.ts'
116
- const bIsIndex = b.path.endsWith('/index.ts') || b.path === 'index.ts'
117
- if (aIsIndex && !bIsIndex) return 1
118
- if (!aIsIndex && bIsIndex) return -1
119
- return 0
120
- })
121
- return this.#filesCache
122
- }
123
- }
@@ -1,91 +0,0 @@
1
- import type { CodeNode, FileNode } from '@kubb/ast'
2
- import { extractStringsFromNodes } from '@kubb/ast'
3
- import { AsyncEventEmitter } from '@internals/utils'
4
- import pLimit from 'p-limit'
5
- import { PARALLEL_CONCURRENCY_LIMIT } from './constants.ts'
6
- import type { Parser } from './defineParser.ts'
7
-
8
- type ParseOptions = {
9
- parsers?: Map<FileNode['extname'], Parser>
10
- extension?: Record<FileNode['extname'], FileNode['extname'] | ''>
11
- }
12
-
13
- type RunOptions = ParseOptions & {
14
- /**
15
- * @default 'sequential'
16
- */
17
- mode?: 'sequential' | 'parallel'
18
- }
19
-
20
- export type FileProcessorEvents = {
21
- start: [files: Array<FileNode>]
22
- update: [params: { file: FileNode; source?: string; processed: number; total: number; percentage: number }]
23
- end: [files: Array<FileNode>]
24
- }
25
-
26
- function joinSources(file: FileNode): string {
27
- return file.sources
28
- .map((item) => extractStringsFromNodes(item.nodes as Array<CodeNode>))
29
- .filter(Boolean)
30
- .join('\n\n')
31
- }
32
-
33
- /**
34
- * Converts a single file to a string using the registered parsers.
35
- * Falls back to joining source values when no matching parser is found.
36
- *
37
- * @internal
38
- */
39
- export class FileProcessor {
40
- readonly events = new AsyncEventEmitter<FileProcessorEvents>()
41
- readonly #limit = pLimit(PARALLEL_CONCURRENCY_LIMIT)
42
-
43
- async parse(file: FileNode, { parsers, extension }: ParseOptions = {}): Promise<string> {
44
- const parseExtName = extension?.[file.extname] || undefined
45
-
46
- if (!parsers || !file.extname) {
47
- return joinSources(file)
48
- }
49
-
50
- const parser = parsers.get(file.extname)
51
-
52
- if (!parser) {
53
- return joinSources(file)
54
- }
55
-
56
- return parser.parse(file, { extname: parseExtName })
57
- }
58
-
59
- async run(files: Array<FileNode>, { parsers, mode = 'sequential', extension }: RunOptions = {}): Promise<Array<FileNode>> {
60
- await this.events.emit('start', files)
61
-
62
- const total = files.length
63
- let processed = 0
64
-
65
- const processOne = async (file: FileNode) => {
66
- const source = await this.parse(file, { extension, parsers })
67
- const currentProcessed = ++processed
68
- const percentage = (currentProcessed / total) * 100
69
-
70
- await this.events.emit('update', {
71
- file,
72
- source,
73
- processed: currentProcessed,
74
- percentage,
75
- total,
76
- })
77
- }
78
-
79
- if (mode === 'sequential') {
80
- for (const file of files) {
81
- await processOne(file)
82
- }
83
- } else {
84
- await Promise.all(files.map((file) => this.#limit(() => processOne(file))))
85
- }
86
-
87
- await this.events.emit('end', files)
88
-
89
- return files
90
- }
91
- }
@@ -1,466 +0,0 @@
1
- import { resolve } from 'node:path'
2
- import type { AsyncEventEmitter } from '@internals/utils'
3
- import type { FileNode, InputNode, OperationNode, SchemaNode } from '@kubb/ast'
4
- import { createFile } from '@kubb/ast'
5
- import { DEFAULT_STUDIO_URL } from './constants.ts'
6
- import type { Generator } from './defineGenerator.ts'
7
- import type { Plugin } from './definePlugin.ts'
8
- import { getMode } from './definePlugin.ts'
9
- import { defineResolver } from './defineResolver.ts'
10
- import { openInStudio as openInStudioFn } from './devtools.ts'
11
- import { FileManager } from './FileManager.ts'
12
- import type { RendererFactory } from './createRenderer.ts'
13
-
14
- import type {
15
- Adapter,
16
- Config,
17
- DevtoolsOptions,
18
- GeneratorContext,
19
- KubbHooks,
20
- KubbPluginSetupContext,
21
- NormalizedPlugin,
22
- PluginFactoryOptions,
23
- Resolver,
24
- } from './types.ts'
25
-
26
- // inspired by: https://github.com/rollup/rollup/blob/master/src/utils/PluginDriver.ts#
27
-
28
- type Options = {
29
- hooks: AsyncEventEmitter<KubbHooks>
30
- }
31
-
32
- function enforceOrder(enforce: 'pre' | 'post' | undefined): number {
33
- return enforce === 'pre' ? -1 : enforce === 'post' ? 1 : 0
34
- }
35
-
36
- export class PluginDriver {
37
- readonly config: Config
38
- readonly options: Options
39
-
40
- /**
41
- * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
42
- *
43
- * @example
44
- * ```ts
45
- * PluginDriver.getMode('src/gen/types.ts') // 'single'
46
- * PluginDriver.getMode('src/gen/types') // 'split'
47
- * ```
48
- */
49
- static getMode(fileOrFolder: string | undefined | null): 'single' | 'split' {
50
- return getMode(fileOrFolder)
51
- }
52
-
53
- /**
54
- * The universal `@kubb/ast` `InputNode` produced by the adapter, set by
55
- * the build pipeline after the adapter's `parse()` resolves.
56
- */
57
- inputNode: InputNode | undefined = undefined
58
- adapter: Adapter | undefined = undefined
59
- #studioIsOpen = false
60
-
61
- /**
62
- * Central file store for all generated files.
63
- * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
64
- * add files; this property gives direct read/write access when needed.
65
- */
66
- readonly fileManager = new FileManager()
67
-
68
- readonly plugins = new Map<string, NormalizedPlugin>()
69
-
70
- /**
71
- * Tracks which plugins have generators registered via `addGenerator()` (event-based path).
72
- * Used by the build loop to decide whether to emit generator events for a given plugin.
73
- */
74
- readonly #pluginsWithEventGenerators = new Set<string>()
75
- readonly #resolvers = new Map<string, Resolver>()
76
- readonly #defaultResolvers = new Map<string, Resolver>()
77
- readonly #hookListeners = new Map<keyof KubbHooks, Set<(...args: never[]) => void | Promise<void>>>()
78
-
79
- constructor(config: Config, options: Options) {
80
- this.config = config
81
- this.options = options
82
- config.plugins
83
- .map((rawPlugin) => this.#normalizePlugin(rawPlugin as Plugin))
84
- .filter((plugin) => {
85
- if (typeof plugin.apply === 'function') {
86
- return plugin.apply(config)
87
- }
88
- return true
89
- })
90
- .sort((a, b) => {
91
- if (b.dependencies?.includes(a.name)) return -1
92
- if (a.dependencies?.includes(b.name)) return 1
93
- // enforce: 'pre' plugins run first, 'post' plugins run last
94
- return enforceOrder(a.enforce) - enforceOrder(b.enforce)
95
- })
96
- .forEach((plugin) => {
97
- this.plugins.set(plugin.name, plugin)
98
- })
99
- }
100
-
101
- get hooks() {
102
- return this.options.hooks
103
- }
104
-
105
- /**
106
- * Creates an `NormalizedPlugin` from a hook-style plugin and registers
107
- * its lifecycle handlers on the `AsyncEventEmitter`.
108
- */
109
- #normalizePlugin(hookPlugin: Plugin): NormalizedPlugin {
110
- const normalizedPlugin = {
111
- name: hookPlugin.name,
112
- dependencies: hookPlugin.dependencies,
113
- enforce: hookPlugin.enforce,
114
- options: { output: { path: '.' }, exclude: [], override: [] },
115
- } as unknown as NormalizedPlugin
116
-
117
- this.registerPluginHooks(hookPlugin, normalizedPlugin)
118
- return normalizedPlugin
119
- }
120
-
121
- /**
122
- * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
123
- *
124
- * For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
125
- * plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
126
- * `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
127
- *
128
- * All other hooks are iterated and registered directly as pass-through listeners.
129
- * Any event key present in the global `KubbHooks` interface can be subscribed to.
130
- *
131
- * External tooling can subscribe to any of these events via `hooks.on(...)` to observe
132
- * the plugin lifecycle without modifying plugin behavior.
133
- *
134
- * @internal
135
- */
136
- registerPluginHooks(hookPlugin: Plugin, normalizedPlugin: NormalizedPlugin): void {
137
- const { hooks } = hookPlugin
138
-
139
- if (!hooks) return
140
-
141
- // kubb:plugin:setup gets special treatment: the globally emitted context is wrapped with
142
- // plugin-specific implementations so that addGenerator / setResolver / etc. target
143
- // this plugin's normalizedPlugin entry rather than being no-ops.
144
- if (hooks['kubb:plugin:setup']) {
145
- const setupHandler = (globalCtx: KubbPluginSetupContext) => {
146
- const pluginCtx: KubbPluginSetupContext = {
147
- ...globalCtx,
148
- options: hookPlugin.options ?? {},
149
- addGenerator: (gen) => {
150
- this.registerGenerator(normalizedPlugin.name, gen)
151
- },
152
- setResolver: (resolver) => {
153
- this.setPluginResolver(normalizedPlugin.name, resolver)
154
- },
155
- setTransformer: (visitor) => {
156
- normalizedPlugin.transformer = visitor
157
- },
158
- setRenderer: (renderer) => {
159
- normalizedPlugin.renderer = renderer
160
- },
161
- setOptions: (opts) => {
162
- normalizedPlugin.options = { ...normalizedPlugin.options, ...opts }
163
- },
164
- injectFile: (userFileNode) => {
165
- this.fileManager.add(createFile(userFileNode))
166
- },
167
- }
168
- return hooks['kubb:plugin:setup']!(pluginCtx)
169
- }
170
-
171
- this.hooks.on('kubb:plugin:setup', setupHandler)
172
- this.#trackHookListener('kubb:plugin:setup', setupHandler as (...args: never[]) => void | Promise<void>)
173
- }
174
-
175
- // All other hooks are registered as direct pass-through listeners on the shared emitter.
176
- for (const [event, handler] of Object.entries(hooks) as Array<[keyof KubbHooks, ((...args: never[]) => void | Promise<void>) | undefined]>) {
177
- if (event === 'kubb:plugin:setup' || !handler) continue
178
-
179
- this.hooks.on(event, handler as never)
180
- this.#trackHookListener(event, handler as (...args: never[]) => void | Promise<void>)
181
- }
182
- }
183
-
184
- /**
185
- * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
186
- * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
187
- *
188
- * Call this once from `safeBuild` before the plugin execution loop begins.
189
- */
190
- async emitSetupHooks(): Promise<void> {
191
- const noop = () => {}
192
-
193
- await this.hooks.emit('kubb:plugin:setup', {
194
- config: this.config,
195
- options: {},
196
- addGenerator: noop,
197
- setResolver: noop,
198
- setTransformer: noop,
199
- setRenderer: noop,
200
- setOptions: noop,
201
- injectFile: noop,
202
- updateConfig: noop,
203
- })
204
- }
205
-
206
- /**
207
- * Registers a generator for the given plugin on the shared event emitter.
208
- *
209
- * The generator's `schema`, `operation`, and `operations` methods are registered as
210
- * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
211
- * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
212
- * so that generators from different plugins do not cross-fire.
213
- *
214
- * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
215
- * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
216
- * declares a renderer.
217
- *
218
- * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
219
- */
220
- registerGenerator(pluginName: string, gen: Generator): void {
221
- const resolveRenderer = () => {
222
- const plugin = this.plugins.get(pluginName)
223
- return gen.renderer === null ? undefined : (gen.renderer ?? plugin?.renderer ?? this.config.renderer)
224
- }
225
-
226
- if (gen.schema) {
227
- const schemaHandler = async (node: SchemaNode, ctx: GeneratorContext) => {
228
- if (ctx.plugin.name !== pluginName) return
229
- const result = await gen.schema!(node, ctx)
230
- await applyHookResult(result, this, resolveRenderer())
231
- }
232
-
233
- this.hooks.on('kubb:generate:schema', schemaHandler)
234
- this.#trackHookListener('kubb:generate:schema', schemaHandler as (...args: never[]) => void | Promise<void>)
235
- }
236
-
237
- if (gen.operation) {
238
- const operationHandler = async (node: OperationNode, ctx: GeneratorContext) => {
239
- if (ctx.plugin.name !== pluginName) return
240
- const result = await gen.operation!(node, ctx)
241
- await applyHookResult(result, this, resolveRenderer())
242
- }
243
-
244
- this.hooks.on('kubb:generate:operation', operationHandler)
245
- this.#trackHookListener('kubb:generate:operation', operationHandler as (...args: never[]) => void | Promise<void>)
246
- }
247
-
248
- if (gen.operations) {
249
- const operationsHandler = async (nodes: Array<OperationNode>, ctx: GeneratorContext) => {
250
- if (ctx.plugin.name !== pluginName) return
251
- const result = await gen.operations!(nodes, ctx)
252
- await applyHookResult(result, this, resolveRenderer())
253
- }
254
-
255
- this.hooks.on('kubb:generate:operations', operationsHandler)
256
- this.#trackHookListener('kubb:generate:operations', operationsHandler as (...args: never[]) => void | Promise<void>)
257
- }
258
-
259
- this.#pluginsWithEventGenerators.add(pluginName)
260
- }
261
-
262
- /**
263
- * Returns `true` when at least one generator was registered for the given plugin
264
- * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
265
- *
266
- * Used by the build loop to decide whether to walk the AST and emit generator events
267
- * for a plugin that has no static `plugin.generators`.
268
- */
269
- hasRegisteredGenerators(pluginName: string): boolean {
270
- return this.#pluginsWithEventGenerators.has(pluginName)
271
- }
272
-
273
- /**
274
- * Unregisters all plugin lifecycle listeners from the shared event emitter.
275
- * Called at the end of a build to prevent listener leaks across repeated builds.
276
- *
277
- * @internal
278
- */
279
- dispose(): void {
280
- for (const [event, handlers] of this.#hookListeners) {
281
- for (const handler of handlers) {
282
- this.hooks.off(event, handler as never)
283
- }
284
- }
285
- this.#hookListeners.clear()
286
- this.#pluginsWithEventGenerators.clear()
287
- // Release resolver closures — the driver is rebuilt for each build() call
288
- // so there is no value in retaining these maps after disposal.
289
- this.#resolvers.clear()
290
- this.#defaultResolvers.clear()
291
- // Release the parsed adapter graph and the FileNode cache once the build
292
- // has finished; the returned `BuildOutput.files` array still references
293
- // any FileNodes the caller needs to inspect.
294
- this.fileManager.dispose()
295
- this.inputNode = undefined
296
- }
297
-
298
- #trackHookListener(event: keyof KubbHooks, handler: (...args: never[]) => void | Promise<void>): void {
299
- let handlers = this.#hookListeners.get(event)
300
- if (!handlers) {
301
- handlers = new Set()
302
- this.#hookListeners.set(event, handlers)
303
- }
304
- handlers.add(handler)
305
- }
306
-
307
- #createDefaultResolver(pluginName: string): Resolver {
308
- const existingResolver = this.#defaultResolvers.get(pluginName)
309
- if (existingResolver) {
310
- return existingResolver
311
- }
312
-
313
- const resolver = defineResolver<PluginFactoryOptions>(() => ({
314
- name: 'default',
315
- pluginName,
316
- }))
317
- this.#defaultResolvers.set(pluginName, resolver)
318
- return resolver
319
- }
320
-
321
- /**
322
- * Merges `partial` with the plugin's default resolver and stores the result.
323
- * Also mirrors it onto `plugin.resolver` so callers using `getPlugin(name).resolver`
324
- * get the up-to-date resolver without going through `getResolver()`.
325
- */
326
- setPluginResolver(pluginName: string, partial: Partial<Resolver>): void {
327
- const defaultResolver = this.#createDefaultResolver(pluginName)
328
- const merged = { ...defaultResolver, ...partial }
329
- this.#resolvers.set(pluginName, merged)
330
- const plugin = this.plugins.get(pluginName)
331
- if (plugin) {
332
- plugin.resolver = merged
333
- }
334
- }
335
-
336
- /**
337
- * Returns the resolver for the given plugin.
338
- *
339
- * Resolution order: dynamic resolver set via `setPluginResolver` → static resolver on the
340
- * plugin → lazily created default resolver (identity name, no path transforms).
341
- */
342
- getResolver<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Kubb.PluginRegistry[TName]['resolver']
343
- getResolver<TResolver extends Resolver = Resolver>(pluginName: string): TResolver
344
- getResolver(pluginName: string): Resolver {
345
- return this.#resolvers.get(pluginName) ?? this.plugins.get(pluginName)?.resolver ?? this.#createDefaultResolver(pluginName)
346
- }
347
-
348
- getContext<TOptions extends PluginFactoryOptions>(plugin: NormalizedPlugin<TOptions>): GeneratorContext<TOptions> & Record<string, unknown> {
349
- const driver = this
350
-
351
- const baseContext = {
352
- config: driver.config,
353
- get root(): string {
354
- return resolve(driver.config.root, driver.config.output.path)
355
- },
356
- getMode(output: { path: string }): 'single' | 'split' {
357
- return PluginDriver.getMode(resolve(driver.config.root, driver.config.output.path, output.path))
358
- },
359
- hooks: driver.hooks,
360
- plugin,
361
- getPlugin: driver.getPlugin.bind(driver),
362
- requirePlugin: driver.requirePlugin.bind(driver),
363
- getResolver: driver.getResolver.bind(driver),
364
- driver,
365
- addFile: async (...files: Array<FileNode>) => {
366
- driver.fileManager.add(...files)
367
- },
368
- upsertFile: async (...files: Array<FileNode>) => {
369
- driver.fileManager.upsert(...files)
370
- },
371
- get inputNode(): InputNode | undefined {
372
- return driver.inputNode
373
- },
374
- get adapter(): Adapter | undefined {
375
- return driver.adapter
376
- },
377
- get resolver() {
378
- return driver.getResolver(plugin.name)
379
- },
380
- get transformer() {
381
- return plugin.transformer
382
- },
383
- warn(message: string) {
384
- driver.hooks.emit('kubb:warn', { message })
385
- },
386
- error(error: string | Error) {
387
- driver.hooks.emit('kubb:error', { error: typeof error === 'string' ? new Error(error) : error })
388
- },
389
- info(message: string) {
390
- driver.hooks.emit('kubb:info', { message })
391
- },
392
- openInStudio(options?: DevtoolsOptions) {
393
- if (!driver.config.devtools || driver.#studioIsOpen) {
394
- return
395
- }
396
-
397
- if (typeof driver.config.devtools !== 'object') {
398
- throw new Error('Devtools must be an object')
399
- }
400
-
401
- if (!driver.inputNode || !driver.adapter) {
402
- throw new Error('adapter is not defined, make sure you have set the parser in kubb.config.ts')
403
- }
404
-
405
- driver.#studioIsOpen = true
406
-
407
- const studioUrl = driver.config.devtools?.studioUrl ?? DEFAULT_STUDIO_URL
408
-
409
- return openInStudioFn(driver.inputNode, studioUrl, options)
410
- },
411
- } as unknown as GeneratorContext<TOptions>
412
-
413
- return baseContext
414
- }
415
-
416
- getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined
417
- getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined
418
- getPlugin(pluginName: string): Plugin | undefined {
419
- return this.plugins.get(pluginName)
420
- }
421
-
422
- /**
423
- * Like `getPlugin` but throws a descriptive error when the plugin is not found.
424
- */
425
- requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]>
426
- requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions>
427
- requirePlugin(pluginName: string): Plugin {
428
- const plugin = this.plugins.get(pluginName)
429
- if (!plugin) {
430
- throw new Error(`[kubb] Plugin "${pluginName}" is required but not found. Make sure it is included in your Kubb config.`)
431
- }
432
- return plugin
433
- }
434
- }
435
-
436
- /**
437
- * Handles the return value of a plugin AST hook or generator method.
438
- *
439
- * - Renderer output → rendered via the provided `rendererFactory` (e.g. JSX), files stored in `driver.fileManager`
440
- * - `Array<FileNode>` → added directly into `driver.fileManager`
441
- * - `void` / `null` / `undefined` → no-op (plugin handled it via `this.upsertFile`)
442
- *
443
- * Pass a `rendererFactory` (e.g. `jsxRenderer` from `@kubb/renderer-jsx`) when the result
444
- * may be a renderer element. Generators that only return `Array<FileNode>` do not need one.
445
- */
446
- export async function applyHookResult<TElement = unknown>(
447
- result: TElement | Array<FileNode> | void,
448
- driver: PluginDriver,
449
- rendererFactory?: RendererFactory<TElement>,
450
- ): Promise<void> {
451
- if (!result) return
452
-
453
- if (Array.isArray(result)) {
454
- driver.fileManager.upsert(...(result as Array<FileNode>))
455
- return
456
- }
457
-
458
- if (!rendererFactory) {
459
- return
460
- }
461
-
462
- const renderer = rendererFactory()
463
- await renderer.render(result)
464
- driver.fileManager.upsert(...renderer.files)
465
- renderer.unmount()
466
- }