Kit

AST and node builders

The ast namespace groups the factory node builders, the transform and collect visitors, the guards, the ref and naming helpers, the macro engine, and the printer helper behind one import.

ast

ast is kubb/kit's namespace for the entire AST surface, the same way TypeScript groups its node constructors under ts.factory. It carries the factory node builders, the transform and collect visitors, the guards, the ref and string helpers, and the macro engine.

ast-namespace.ts
import { ast } from 'kubb/kit'

const root = ast.factory.createInput({
  schemas: [ast.factory.createSchema({ name: 'Pet', type: 'object', properties: [] })],
  operations: [],
})

Node building goes through ast.factory. ast.factory.createFile, ast.factory.createSource, and ast.factory.createText build the FileNode tree a generator returns.

factory.ts
import { ast } from 'kubb/kit'

const file = ast.factory.createFile({
  baseName: 'pet.ts',
  path: './pet.ts',
  sources: [ast.factory.createSource({ nodes: [ast.factory.createText('export type Pet = { id: number }')] })],
})

For why the AST exists and how it fits the pipeline, see AST concepts.

Schema node types

A SchemaNode is discriminated by its type. The values fall into three families.

Structural types

TypeDescriptionTypeScript
objectObject with named properties{ name: string; age: number }
arraySequence of itemsstring[]
tupleFixed-length array with typed positions[string, number, boolean]
unionOne of multiple typesstring | number
intersectionCombination of multiple typesA & B
enumFixed set of literal values'active' | 'inactive'

Scalar types

TypeDescriptionTypeScript
stringText valuestring
numberNumeric valuenumber
integerWhole numbernumber
bigintLarge integerbigint
booleanTrue/falseboolean
nullNull valuenull
anyAny valueany
unknownUnknown valueunknown
voidNo valuevoid
neverNever producednever

Special types

TypeDescriptionExample
refReference to another schemaPet (from $ref)
dateISO date2024-01-15
datetimeISO datetime2024-01-15T10:30:00Z
timeISO time10:30:00
uuidUUID string550e8400-e29b-41d4-a716-446655440000
emailEmail address[email protected]
urlURL stringhttps://example.com
blobBinary dataRaw bytes

Factory functions

Factories return defaulted, fully typed nodes for adapters and generator handlers. Never build AST literals by hand.

factories.ts
import { ast } from 'kubb/kit'

const root = ast.factory.createInput({
  schemas: [ast.factory.createSchema({ name: 'Pet', type: 'object', properties: [] }), ast.factory.createSchema({ name: 'Status', type: 'enum', values: ['active', 'inactive'] })],
  operations: [ast.factory.createOperation({ operationId: 'listPets', method: 'GET', path: '/pets' })],
})

The ast.factory namespace also provides constructors for source files and TypeScript-level artifacts that generators emit:

FactoryPurpose
createFile, createSource, createTextBuild FileNodes emitted by generators.
createImport, createExportEmit import / export statements.
createConst, createFunction, createArrowFunction, createJsxEmit TypeScript declarations and JSX.
createParameterDescribe operation parameters.
createProperty, createTypeCompose object properties and TypeScript types.
createResponse, createRequestBody, createContent, createOutputModel responses, request bodies, content entries, and generator outputs.
createBreakEmit line breaks between nodes.
updateApply an identity-preserving shallow update to any node.

Visitors

Two visitor functions cover the common traversal patterns: transform rewrites the tree and collect gathers nodes. Visitor objects use lowercase, kind-style keys (input, output, operation, schema, property, parameter, response). To rewrite nodes inside a plugin, reach for macros, which add names, ordering, and composition on top of transform. For logging, validation, or statistics, collect the nodes you care about.

transform: synchronous, returns a new tree

transform.ts
import { ast } from 'kubb/kit'

const root = ast.factory.createInput({ schemas: [], operations: [] })

const enhanced = ast.transform(root, {
  schema(node) {
    if (node.type === 'object' && node.additionalProperties === undefined) {
      return { ...node, additionalProperties: false }
    }
    return node
  },
  operation(node) {
    return { ...node, tags: node.tags?.length ? node.tags : ['untagged'] }
  },
})

Use transform to change AST structure, normalize inconsistencies, or annotate nodes.

To apply a change and keep that guarantee, use the update factory instead of spreading by hand. It returns the same node when every field you pass already matches:

update.ts
import { ast } from 'kubb/kit'

const node = ast.factory.createSchema({ name: 'Pet', type: 'object', properties: [] })

ast.factory.update(node, { name: 'Pet' }) // -> same `node` reference (no change)
ast.factory.update(node, { name: 'Animal' }) // -> new node with `name` replaced

collect: gather matching nodes

collect is a generator function, so it yields matches lazily and you consume it with for...of or spread it into an array. When you want the array up front, call collectSync, which is the eager counterpart and returns Array<T>.

collect.ts
import { ast } from 'kubb/kit'

const root = ast.factory.createInput({ schemas: [], operations: [] })

const mutations = ast.collectSync<ast.OperationNode>(root, {
  operation(node) {
    return node.method === 'POST' ? node : undefined
  },
})

const deprecated = ast.collectSync<ast.SchemaNode>(root, {
  schema(node) {
    return 'deprecated' in node && node.deprecated ? node : undefined
  },
})

console.log(`POST operations: ${mutations.length}`)
console.log(`Deprecated schemas: ${deprecated.length}`)

Use collect to stream matches as you find them, and collectSync to find specific nodes, filter by a criterion, or build a list for later processing.

Guards and narrowing

Kubb exports type guards and a narrowSchema helper for safe discrimination:

guards.ts
import { ast } from 'kubb/kit'

const root = ast.factory.createInput({ schemas: [], operations: [] })

for (const node of ast.collect<ast.SchemaNode>(root, { schema: (node) => node })) {
  const obj = ast.narrowSchema(node, 'object')
  if (obj) {
    console.log(`object with ${obj.properties.length} properties`)
  }

  if (node.type === 'ref') {
    console.log(`reference to: ${node.ref}`)
  }
}

for (const node of ast.collect<ast.OperationNode>(root, { operation: (node) => node })) {
  if (ast.isHttpOperationNode(node)) {
    console.log(`${node.method} ${node.path}`)
  }
}

Refs and naming helpers

The ref and naming helpers split across two surfaces. resolveRefName ships on the ast namespace, like the guards and node types. extractRefName, childName, enumPropName, and syncSchemaRef are named exports of kubb/kit itself, not members of the ast namespace (the same split as the built-in macros below).

HelperPurpose
extractRefNameTurn '#/components/schemas/Pet' into 'Pet'.
resolveRefNameResolve the name a ref node emits, preferring its targetName.
childNameDerive a child property name from context.
enumPropNameConvert an enum value into a valid property name.
syncSchemaRefMerge a ref node with its resolved schema, letting usage-site fields (description, nullable) override.
refs.ts
import { extractRefName } from 'kubb/kit'

const name = extractRefName('#/components/schemas/Pet')

Schema graph

Analyze how schemas reference each other, to prune unused schemas or wrap circular ones in a lazy construct. collectUsedSchemaNames and findCircularSchemas ship on the ast namespace. containsCircularRef is a named export of kubb/kit itself, not a member of the ast namespace.

HelperPurpose
collectUsedSchemaNamesCollect the names of every top-level schema transitively used by a set of operations. Pair it with include filters to leave unreferenced schemas ungenerated.
findCircularSchemasFind every schema that takes part in a circular dependency chain, so those positions can be wrapped in a lazy getter or z.lazy(() => …).
containsCircularRefReport whether a schema, or anything nested inside it, references a circular schema. Import it from kubb/kit directly, not through ast.

Constants

ExportPurpose
schemaTypesMap of every schema type discriminant.

Macros

A macro is a named, composable transform built on transform that rewrites nodes before printing, adding ordering, gating, and reuse a bare visitor doesn't give you. See Macros concepts.

ExportPurpose
defineMacroType a macro and read it as one definition.
composeMacrosFold an ordered list of macros into one visitor.
applyMacrosRun a list of macros over a node tree.

Kubb also ships built-in macros for common schema normalizations that any adapter can compose with its own. These are named exports of kubb/kit itself, not members of the ast namespace. See Built-in macros for the full walkthrough.

MacroPurpose
macroSimplifyUnionDrop union members a broader scalar primitive already covers, such as a multi-value string enum next to string.
macroDiscriminatorEnumReplace a discriminator property's schema with a string enum of its allowed values.
macroEnumNameName an inline enum schema from its parent and property name.
macroRenameSchemaRename a schema's declaration and retarget every ref pointing at it in one pass.

Macro options and callbacks

A macro carries the per-kind callbacks of a visitor, plus a name, an optional enforce order, and an optional match predicate.

Type definition
type Macro = {
  name: string
  enforce?: 'pre' | 'post'
  match?: (node: Node) => boolean
  schema?(node: SchemaNode, context): SchemaNode | null | undefined
  operation?(node: OperationNode, context): OperationNode | null | undefined
  // input, output, property, parameter, response
}

Each callback returns a replacement node, or undefined or null to leave the node untouched. A macro that changes nothing returns the original reference, so an unchanged tree is reused, not rebuilt.

Printers

Lower-level helpers for parsers that turn the AST into source code:

ExportPurpose
createPrinterTyped helper for creating a Printer.

createPrinter takes an overrides map to replace the handler for individual schema node types. Inside an override, this.base(node) runs the built-in handler the override replaced, so you can wrap its output instead of re-implementing it. Pass overrides through the overrides field rather than spreading them into nodes, otherwise this.base cannot find the original handler. The printer.nodes option on @kubb/plugin-ts, @kubb/plugin-zod, and @kubb/plugin-faker feeds this map. See Override a printer.

Inside a handler, this.import(ast.factory.createImport(...)) declares an import required by the printed code. After printing, the generator calls printer.drainImports() to retrieve the imports and clear the list. See Import a custom codec for a complete example.

See Parsers concepts for how parsers consume printers.

Printer handlers and context

The map is keyed by the schema type discriminant, such as 'string', 'integer', 'date', 'enum', or 'object'. Supply only the handlers you want to replace and the built-in ones fill in the rest.

Type definition
type PrinterNodes = Partial<{
  [K in SchemaType]: (this: Context, node: SchemaNodeByType[K]) => Output | null
}>

Handlers run with a this context, so write them as regular functions rather than arrow functions. this.transform(node) recurses into a nested schema node through the full handler map, overrides included. this.base(node) runs the built-in handler your override replaced, so you can wrap its output instead of rebuilding it. this.options reads the resolved printer options, such as arrayType on @kubb/plugin-ts or direction on @kubb/plugin-zod.