@kubb/core 5.0.0-beta.22 → 5.0.0-beta.24

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/src/createKubb.ts CHANGED
@@ -90,22 +90,25 @@ export type Config<TInput = Input> = {
90
90
  */
91
91
  name?: string
92
92
  /**
93
- * Project root directory, absolute or relative to the config file.
94
- * @default process.cwd()
93
+ * Project root directory, absolute or relative to the config file. Already
94
+ * resolved on the `Config` instance — see `UserConfig` for the optional
95
+ * form that defaults to `process.cwd()`.
95
96
  */
96
97
  root: string
97
98
  /**
98
- * Parsers that convert generated files to strings.
99
- * Each parser handles specific extensions (e.g. `.ts`, `.tsx`).
100
- * A fallback parser is appended for unhandled extensions.
101
- * When omitted, defaults to `parserTs` from `@kubb/parser-ts`.
99
+ * Parsers that convert generated files into strings. Each parser handles a
100
+ * set of file extensions; a fallback parser handles anything else.
101
+ *
102
+ * Already resolved on the `Config` instance — see `UserConfig` for the
103
+ * optional form that defaults to `[parserTs, parserTsx]`.
102
104
  *
103
- * @default [parserTs] from `@kubb/parser-ts`
104
105
  * @example
105
106
  * ```ts
106
- * import { parserTs, tsxParser } from '@kubb/parser-ts'
107
+ * import { defineConfig } from 'kubb'
108
+ * import { parserTs, parserTsx } from '@kubb/parser-ts'
109
+ *
107
110
  * export default defineConfig({
108
- * parsers: [parserTs, tsxParser],
111
+ * parsers: [parserTs, parserTsx],
109
112
  * })
110
113
  * ```
111
114
  */
@@ -821,6 +824,11 @@ export type CLIOptions = {
821
824
  * Path to the Kubb config file.
822
825
  */
823
826
  config?: string
827
+ /**
828
+ * OpenAPI input path passed as the positional argument to `kubb generate`.
829
+ * Overrides `config.input.path` when set.
830
+ */
831
+ input?: string
824
832
  /**
825
833
  * Re-run generation whenever input files change.
826
834
  */
@@ -828,9 +836,9 @@ export type CLIOptions = {
828
836
  /**
829
837
  * Controls how much output the CLI prints.
830
838
  *
831
- * @default 'silent'
839
+ * @default 'info'
832
840
  */
833
- logLevel?: 'silent' | 'info' | 'debug'
841
+ logLevel?: 'silent' | 'info' | 'verbose' | 'debug'
834
842
  }
835
843
 
836
844
  /**
@@ -1103,8 +1111,24 @@ export class Kubb {
1103
1111
  }
1104
1112
 
1105
1113
  /**
1106
- * Factory for {@link Kubb}. Equivalent to `new Kubb(userConfig, options)` and kept
1107
- * as the canonical public entry point.
1114
+ * Constructs a {@link Kubb} build orchestrator from a user config. Equivalent
1115
+ * to `new Kubb(userConfig, options)` and the canonical public entry point.
1116
+ *
1117
+ * @example
1118
+ * ```ts
1119
+ * import { createKubb } from '@kubb/core'
1120
+ * import { adapterOas } from '@kubb/adapter-oas'
1121
+ * import { pluginTs } from '@kubb/plugin-ts'
1122
+ *
1123
+ * const kubb = createKubb({
1124
+ * input: { path: './petStore.yaml' },
1125
+ * output: { path: './src/gen' },
1126
+ * adapter: adapterOas(),
1127
+ * plugins: [pluginTs()],
1128
+ * })
1129
+ *
1130
+ * await kubb.build()
1131
+ * ```
1108
1132
  */
1109
1133
  export function createKubb(userConfig: UserConfig, options: CreateKubbOptions = {}): Kubb {
1110
1134
  return new Kubb(userConfig, options)
@@ -48,17 +48,37 @@ export type Renderer<TElement = unknown> = {
48
48
  export type RendererFactory<TElement = unknown> = () => Renderer<TElement>
49
49
 
50
50
  /**
51
- * Wraps a renderer factory for use in generator definitions.
51
+ * Defines a renderer factory. Renderers turn the generator's return value
52
+ * (JSX, a template string, a tree of any shape) into `FileNode`s that get
53
+ * written to disk.
52
54
  *
53
- * @example
55
+ * Use this to support output formats beyond JSX — for instance, a Handlebars
56
+ * renderer, a string-template renderer, or a renderer that writes binary
57
+ * files. Plugins and generators pick the renderer to use via the `renderer`
58
+ * field on `defineGenerator`.
59
+ *
60
+ * @example A minimal renderer that wraps a custom runtime
54
61
  * ```ts
55
- * export const jsxRenderer = createRenderer(() => {
56
- * const runtime = new Runtime()
62
+ * import { createRenderer } from '@kubb/core'
63
+ *
64
+ * export const myRenderer = createRenderer(() => {
65
+ * const runtime = new MyRuntime()
57
66
  * return {
58
- * async render(element) { await runtime.render(element) },
59
- * get files() { return runtime.nodes },
60
- * dispose() { runtime.unmount() },
61
- * unmount(error) { runtime.unmount(error) },
67
+ * async render(element) {
68
+ * await runtime.render(element)
69
+ * },
70
+ * get files() {
71
+ * return runtime.files
72
+ * },
73
+ * dispose() {
74
+ * runtime.dispose()
75
+ * },
76
+ * unmount(error) {
77
+ * runtime.dispose(error)
78
+ * },
79
+ * [Symbol.dispose]() {
80
+ * this.dispose()
81
+ * },
62
82
  * }
63
83
  * })
64
84
  * ```
@@ -1,68 +1,81 @@
1
+ /**
2
+ * Backend that persists generated files. Kubb ships with `fsStorage` (writes
3
+ * to disk) and `memoryStorage` (keeps everything in RAM). Implement this
4
+ * interface to write to S3, a database, or any other target.
5
+ */
1
6
  export type Storage = {
2
7
  /**
3
- * Identifier used for logging and debugging (e.g. `'fs'`, `'s3'`).
8
+ * Identifier used in logs and diagnostics (`'fs'`, `'memory'`, `'s3'`).
4
9
  */
5
10
  readonly name: string
6
11
  /**
7
- * Returns `true` when an entry for `key` exists in storage.
12
+ * Returns `true` when an entry for `key` exists.
8
13
  */
9
14
  hasItem(key: string): Promise<boolean>
10
15
  /**
11
- * Returns the stored string value, or `null` when `key` does not exist.
16
+ * Reads the stored string. Returns `null` when the key is missing.
12
17
  */
13
18
  getItem(key: string): Promise<string | null>
14
19
  /**
15
- * Persists `value` under `key`, creating any required structure.
20
+ * Stores `value` under `key`, creating any required structure (directories,
21
+ * buckets, ...).
16
22
  */
17
23
  setItem(key: string, value: string): Promise<void>
18
24
  /**
19
- * Removes the entry for `key`. No-ops when the key does not exist.
25
+ * Deletes the entry for `key`. No-op when the key does not exist.
20
26
  */
21
27
  removeItem(key: string): Promise<void>
22
28
  /**
23
- * Returns all keys, optionally filtered to those starting with `base`.
29
+ * Returns every key. Pass `base` to filter to keys starting with that prefix.
24
30
  */
25
31
  getKeys(base?: string): Promise<Array<string>>
26
32
  /**
27
- * Removes all entries, optionally scoped to those starting with `base`.
33
+ * Removes every entry. Pass `base` to scope the wipe to a key prefix.
28
34
  */
29
35
  clear(base?: string): Promise<void>
30
36
  /**
31
- * Optional teardown hook called after the build completes.
37
+ * Optional teardown hook called after the build completes. Use to flush
38
+ * buffers, close connections, or release file locks.
32
39
  */
33
40
  dispose?(): Promise<void>
34
41
  }
35
42
 
36
43
  /**
37
- * Factory for implementing custom storage backends that control where generated files are written.
38
- *
39
- * Takes a builder function `(options: TOptions) => Storage` and returns a factory `(options?: TOptions) => Storage`.
40
- * Kubb provides filesystem and in-memory implementations out of the box.
44
+ * Defines a custom storage backend. The builder receives user options and
45
+ * returns a `Storage` implementation. Kubb ships with filesystem and
46
+ * in-memory storages reach for this when you need to write generated files
47
+ * elsewhere (cloud storage, a database, a remote API).
41
48
  *
42
- * @note Call the returned factory with optional options to instantiate the storage adapter.
43
- *
44
- * @example
49
+ * @example In-memory storage (the built-in implementation)
45
50
  * ```ts
46
51
  * import { createStorage } from '@kubb/core'
47
52
  *
48
53
  * export const memoryStorage = createStorage(() => {
49
54
  * const store = new Map<string, string>()
55
+ *
50
56
  * return {
51
57
  * name: 'memory',
52
- * async hasItem(key) { return store.has(key) },
53
- * async getItem(key) { return store.get(key) ?? null },
54
- * async setItem(key, value) { store.set(key, value) },
55
- * async removeItem(key) { store.delete(key) },
58
+ * async hasItem(key) {
59
+ * return store.has(key)
60
+ * },
61
+ * async getItem(key) {
62
+ * return store.get(key) ?? null
63
+ * },
64
+ * async setItem(key, value) {
65
+ * store.set(key, value)
66
+ * },
67
+ * async removeItem(key) {
68
+ * store.delete(key)
69
+ * },
56
70
  * async getKeys(base) {
57
71
  * const keys = [...store.keys()]
58
72
  * return base ? keys.filter((k) => k.startsWith(base)) : keys
59
73
  * },
60
- * async clear(base) { if (!base) store.clear() },
74
+ * async clear(base) {
75
+ * if (!base) store.clear()
76
+ * },
61
77
  * }
62
78
  * })
63
- *
64
- * // Instantiate:
65
- * const storage = memoryStorage()
66
79
  * ```
67
80
  */
68
81
  export function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage {
@@ -98,8 +98,8 @@ export type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFacto
98
98
  * Declares a named generator unit that walks the AST and emits files.
99
99
  *
100
100
  * Each method (`schema`, `operation`, `operations`) is called for the matching node type.
101
- * Each method returns `TElement | Array<FileNode> | void`. JSX-based generators require a `renderer` factory.
102
- * Return `Array<FileNode>` directly or call `ctx.upsertFile()` manually and return `void` to bypass rendering.
101
+ * Each method returns `TElement | Array<FileNode> | undefined | null`. JSX-based generators require a `renderer` factory.
102
+ * Return `Array<FileNode>` directly or call `ctx.upsertFile()` manually and return `undefined` or `null` to bypass rendering.
103
103
  *
104
104
  * @note Generators are consumed by plugins and registered via `ctx.addGenerator()` in `kubb:plugin:setup`.
105
105
  *
@@ -149,25 +149,48 @@ export type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptio
149
149
  * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
150
150
  * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
151
151
  */
152
- schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>
152
+ schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>
153
153
  /**
154
154
  * Called for each operation node in the AST walk.
155
155
  * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
156
156
  * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
157
157
  */
158
- operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>
158
+ operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>
159
159
  /**
160
160
  * Called once after all operations have been walked.
161
161
  * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
162
162
  * plus `ctx.options` with the plugin-level options for the batch call.
163
163
  */
164
- operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>
164
+ operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>
165
165
  }
166
166
 
167
167
  /**
168
- * Defines a generator. Returns the object as-is with correct `this` typings.
169
- * `applyHookResult` handles renderer elements and `File[]` uniformly using
170
- * the generator's declared `renderer` factory.
168
+ * Defines a generator: a unit of work that runs during the plugin's AST walk
169
+ * and produces files. Plugins register generators via `ctx.addGenerator()`
170
+ * inside `kubb:plugin:setup`.
171
+ *
172
+ * The returned object is the input as-is, but with `this` types preserved so
173
+ * `schema`/`operation`/`operations` methods are correctly typed against the
174
+ * plugin's `PluginFactoryOptions`. Renderer elements and `FileNode[]` returns
175
+ * are both handled by the runtime — pick whichever style fits.
176
+ *
177
+ * @example JSX-based schema generator
178
+ * ```tsx
179
+ * import { defineGenerator } from '@kubb/core'
180
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
181
+ *
182
+ * export const typeGenerator = defineGenerator({
183
+ * name: 'typescript',
184
+ * renderer: jsxRenderer,
185
+ * schema(node, ctx) {
186
+ * return (
187
+ * <File path={`${ctx.root}/${node.name}.ts`}>
188
+ * <Type node={node} resolver={ctx.resolver} />
189
+ * </File>
190
+ * )
191
+ * },
192
+ * })
193
+ * ```
171
194
  */
172
195
  export function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(
173
196
  generator: Generator<TOptions, TElement>,
@@ -2,51 +2,71 @@ import type { AsyncEventEmitter } from '@internals/utils'
2
2
  import type { logLevel } from './constants.ts'
3
3
  import type { KubbHooks } from './types.ts'
4
4
 
5
+ /**
6
+ * Options accepted by a logger's `install` callback.
7
+ */
5
8
  export type LoggerOptions = {
6
9
  /**
7
- * Log level for output verbosity.
8
- * @default 3
10
+ * Output verbosity. Use the `logLevel` constants exported from `@kubb/core`
11
+ * (`silent`, `error`, `warn`, `info`, `verbose`, `debug`).
9
12
  */
10
13
  logLevel: (typeof logLevel)[keyof typeof logLevel]
11
14
  }
12
15
 
13
16
  /**
14
- * Shared context passed to plugins, parsers, and other internals.
17
+ * Event emitter handed to `Logger.install`. Use `.on('kubb:info', ...)` and
18
+ * friends to subscribe to build events.
15
19
  */
16
20
  export type LoggerContext = AsyncEventEmitter<KubbHooks>
17
21
 
22
+ /**
23
+ * Logger contract. A logger receives the build's event emitter and subscribes
24
+ * to whichever lifecycle events it wants to forward to its destination
25
+ * (console, file, remote sink).
26
+ */
18
27
  export type Logger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = {
28
+ /**
29
+ * Display name used in diagnostics.
30
+ */
19
31
  name: string
32
+ /**
33
+ * Called once per build with the shared event emitter. Subscribe to events
34
+ * here. The return value (if any) is forwarded to whoever installed the
35
+ * logger, which is handy for sink factories.
36
+ */
20
37
  install: (context: LoggerContext, options?: TOptions) => TInstallReturn | Promise<TInstallReturn>
21
38
  }
22
39
 
23
40
  export type UserLogger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = Logger<TOptions, TInstallReturn>
24
41
 
25
42
  /**
26
- * Wraps a logger definition into a typed {@link Logger}.
27
- *
28
- * The optional second type parameter `TInstallReturn` allows loggers to return
29
- * a value from `install` — for example, a sink factory that the caller can
30
- * forward to hook execution.
43
+ * Defines a typed logger. Use the second type parameter to declare a return
44
+ * value from `install`, which is handy when the logger exposes a sink factory
45
+ * or cleanup callback to the caller.
31
46
  *
32
47
  * @example Basic logger
33
48
  * ```ts
49
+ * import { defineLogger } from '@kubb/core'
50
+ *
34
51
  * export const myLogger = defineLogger({
35
52
  * name: 'my-logger',
36
- * install(context, options) {
37
- * context.on('kubb:info', (message) => console.log('ℹ', message))
38
- * context.on('kubb:error', (error) => console.error('✗', error.message))
53
+ * install(context) {
54
+ * context.on('kubb:info', ({ message }) => console.log('ℹ', message))
55
+ * context.on('kubb:error', ({ error }) => console.error('✗', error.message))
39
56
  * },
40
57
  * })
41
58
  * ```
42
59
  *
43
60
  * @example Logger that returns a hook sink factory
44
61
  * ```ts
62
+ * import { defineLogger, type LoggerOptions } from '@kubb/core'
63
+ * import type { HookSinkFactory } from './sinks'
64
+ *
45
65
  * export const myLogger = defineLogger<LoggerOptions, HookSinkFactory>({
46
66
  * name: 'my-logger',
47
- * install(context, options) {
67
+ * install(context) {
48
68
  * // … register event handlers …
49
- * return (commandWithArgs) => ({ onStdout: console.log })
69
+ * return () => ({ onStdout: console.log })
50
70
  * },
51
71
  * })
52
72
  * ```
@@ -1,20 +1,19 @@
1
1
  import type { KubbHooks } from './types.ts'
2
2
 
3
3
  /**
4
- * A middleware instance produced by calling a factory created with `defineMiddleware`.
5
- * It declares event handlers under a `hooks` object which are registered on the
6
- * shared emitter after all plugin hooks, so middleware handlers for any event
7
- * always fire last.
4
+ * A middleware instance. Subscribes to lifecycle events via `hooks`. Middleware
5
+ * handlers always fire after every plugin handler for the same event, so they
6
+ * see the full set of generated files.
8
7
  */
9
8
  export type Middleware = {
10
9
  /**
11
- * Unique identifier for this middleware.
10
+ * Unique name. Use a `middleware-<feature>` convention (e.g.
11
+ * `middleware-barrel`).
12
12
  */
13
13
  name: string
14
14
  /**
15
- * Lifecycle event handlers for this middleware.
16
- * Any event from the global `KubbHooks` map can be subscribed to here.
17
- * Handlers are registered after all plugin handlers, so they always fire last.
15
+ * Lifecycle event handlers. Any event from the global `KubbHooks` map can be
16
+ * subscribed to here. Handlers run after all plugin handlers for that event.
18
17
  */
19
18
  hooks: {
20
19
  [K in keyof KubbHooks]?: (...args: KubbHooks[K]) => void | Promise<void>
@@ -22,18 +21,17 @@ export type Middleware = {
22
21
  }
23
22
 
24
23
  /**
25
- * Creates a middleware factory using the hook-style `hooks` API.
24
+ * Creates a middleware factory. Middleware fires after every plugin handler
25
+ * for the same event, which makes it the natural place for post-processing
26
+ * (barrel files, lint runs, audit logs).
26
27
  *
27
- * Middleware handlers fire after all plugin handlers for any given event, making them ideal for post-processing, logging, and auditing.
28
- * Per-build state (such as accumulators) belongs inside the factory closure so each `createKubb` invocation gets its own isolated instance.
28
+ * Per-build state belongs inside the factory closure so each `createKubb`
29
+ * invocation gets its own isolated instance.
29
30
  *
30
- * @note The factory can accept typed options. See examples for using options and per-build state patterns.
31
- *
32
- * @example
31
+ * @example Stateless middleware
33
32
  * ```ts
34
33
  * import { defineMiddleware } from '@kubb/core'
35
34
  *
36
- * // Stateless middleware
37
35
  * export const logMiddleware = defineMiddleware(() => ({
38
36
  * name: 'log-middleware',
39
37
  * hooks: {
@@ -42,8 +40,12 @@ export type Middleware = {
42
40
  * },
43
41
  * },
44
42
  * }))
43
+ * ```
44
+ *
45
+ * @example Middleware with options and per-build state
46
+ * ```ts
47
+ * import { defineMiddleware } from '@kubb/core'
45
48
  *
46
- * // Middleware with options and per-build state
47
49
  * export const prefixMiddleware = defineMiddleware((options: { prefix: string } = { prefix: '' }) => {
48
50
  * const seen = new Set<string>()
49
51
  * return {
@@ -4,41 +4,58 @@ type PrintOptions = {
4
4
  extname?: FileNode['extname']
5
5
  }
6
6
 
7
- export type Parser<TMeta extends object = any> = {
7
+ /**
8
+ * Converts a resolved {@link FileNode} into the final source string that gets
9
+ * written to disk. Kubb ships with TypeScript and TSX parsers; add your own
10
+ * for new file types (JSON, Markdown, ...).
11
+ */
12
+ export type Parser<TMeta extends object = any, TNode = unknown> = {
13
+ /**
14
+ * Display name used in diagnostics and the parser registry.
15
+ */
8
16
  name: string
9
17
  /**
10
- * File extensions this parser handles.
11
- * Use `undefined` to create a catch-all fallback parser.
18
+ * File extensions this parser handles. Set to `undefined` to define a
19
+ * catch-all fallback used when no other parser claims the extension.
12
20
  *
13
- * @example Handled extensions
21
+ * @example
14
22
  * `['.ts', '.js']`
15
23
  */
16
24
  extNames: Array<FileNode['extname']> | undefined
17
25
  /**
18
- * Convert a resolved file to a string.
26
+ * Serialise the file's AST into source code.
19
27
  */
20
28
  parse(file: FileNode<TMeta>, options?: PrintOptions): string
29
+ /**
30
+ * Render compiler AST nodes for this parser's language into source text.
31
+ * Plugins call this to format the nodes they assemble before handing them
32
+ * back to the parser as `FileNode.sources`.
33
+ */
34
+ print(...nodes: TNode[]): string
21
35
  }
22
36
 
23
37
  /**
24
- * Defines a parser with type safety. Creates parsers that transform generated files to strings based on their extension.
25
- *
26
- * @note Call the returned factory with optional options to instantiate the parser.
38
+ * Defines a parser with type-safe `this`. Used to register handlers for new
39
+ * file extensions or to plug a non-TypeScript output into the build.
27
40
  *
28
41
  * @example
29
42
  * ```ts
30
- * import { defineParser } from '@kubb/core'
43
+ * import { defineParser, ast } from '@kubb/core'
31
44
  *
32
45
  * export const jsonParser = defineParser({
33
46
  * name: 'json',
34
47
  * extNames: ['.json'],
35
48
  * parse(file) {
36
- * const { extractStringsFromNodes } = await import('@kubb/ast')
37
- * return file.sources.map((s) => extractStringsFromNodes(s.nodes ?? [])).join('\n')
49
+ * return file.sources
50
+ * .map((source) => ast.extractStringsFromNodes(source.nodes ?? []))
51
+ * .join('\n')
52
+ * },
53
+ * print(...nodes) {
54
+ * return nodes.map(String).join('\n')
38
55
  * },
39
56
  * })
40
57
  * ```
41
58
  */
42
- export function defineParser<TMeta extends object = any>(parser: Parser<TMeta>): Parser<TMeta> {
59
+ export function defineParser<T extends Parser>(parser: T): T {
43
60
  return parser
44
61
  }