Resolvers
createResolver
A resolver names every symbol and file your plugin generates, and decides where imports point. Build one with createResolver, which requires pluginName. Other plugins read it through ctx.getResolver(name) in a template, or getResolver(name) from kubb/kit in any plugin hook. getResolver reads the memo of the running hook; pass the memo as a second argument to read it outside a hook. Without a stored resolver, getResolver stores and returns the default one for that plugin.
import { createResolver } from 'kubb/kit'
import type { PluginType, Resolver } from 'kubb/kit'
// Extend the base Resolver with plugin-specific naming namespaces.
type MyResolver = Resolver & {
schema: {
name(node: { name: string }): string
}
}
type MyPlugin = PluginType<'plugin-example', object, object, MyResolver>
export const resolver = createResolver<MyPlugin>({
pluginName: 'plugin-example',
name(name) {
return `${name.charAt(0).toUpperCase()}${name.slice(1)}`
},
schema: {
name(node) {
return this.name(node.name)
},
},
})Built-in members
Every resolver has these members. name and file follow your overrides, and default always holds Kubb's built-ins.
| Member | Does |
|---|---|
name(name) | The identifier casing. Falls back to default.name. |
file(options) | Builds a FileNode from file.baseName and file.path, or default.path. |
imports(options) | One import per $ref. See resolver.imports. |
memo(key, compute) | Caches a value for the rest of the build. |
resolveName(), reserveNames() | Allocate names that do not collide. See Name reservations. |
groupDir(group, value) | The folder a group puts a file in. |
default.name | Kubb's camelCase. |
default.options | Applies the exclude, include, and override filters. |
default.path | Resolves to output.path. With mode: 'directory' it adds the base name, inside a tag or path folder when group is set. |
default.file | Builds a FileNode. The built-in base name camelCases each dotted segment, so pet.petId becomes pet/petId. |
default.banner | Returns output.banner, or the "Generated by Kubb" header. null when output.defaultBanner is false. |
default.footer | Returns output.footer, or null. |
resolver.imports
resolver.imports returns one import per $ref in a schema tree. It names each import from the ref's targetName, or else the last segment of its pointer. Names and paths go through name and file, and extname defaults to .ts.
const imports = resolver.imports({ node, root, output })
// → [{ kind: 'Import', name: ['pet'], path: '/src/types/pet.ts' }]| Option | Effect |
|---|---|
name | Turns a referenced schema name into the imported identifier, for example (schemaName) => \${resolver.name(schemaName)}Type``. |
checks | true also imports refs inside conditionals, contains, and a string's content. See Ref imports in checks. |
Name reservations
resolver.resolveName({ key, name }) keeps the preferred name when it is free and adds 2, 3, and so on when it is taken. Use the same key for a declaration and its references.
Kubb reserves component names itself, and resolver.name only applies casing. Reserve other identifiers, such as enum type aliases, with resolver.reserveNames first.
resolver.reserveNames(['CreateContainerBody', 'CreateContainerBody2'])
const name = resolver.resolveName({
key: ['operation', 'POST', '/containers', 'body'],
name: 'CreateContainerBody',
})
// 'CreateContainerBody3'Resolver.merge
Resolver.merge(base, ...patches) layers the patches over base in order and returns a new resolver. A top-level name replaces. file and each namespace merge per member, so overriding query.name keeps the base query.keyName.
const patched = Resolver.merge(resolver, {
name(name) {
return `Custom${this.default.name(name)}`
},
})ResolverPatch<T> to check this and the namespace shapes against the target resolver.Reusable resolver parts
A resolver part is a partial resolver, such as one namespace or a file rule, that any plugin can merge in. Define one with defineResolver. It types this as the full resolver plus the part and adds no runtime behavior, like defineMacro. Name exports resolver<Name>.
import { defineResolver } from 'kubb/kit'
export const resolverHook = defineResolver({
hook: {
optionsName(): string {
return this.resolveName({ key: ['hook', 'options'], name: 'HookOptions' })
},
},
})Spread parts into createResolver, or pass a list to setResolver. The list merges left to right, so a later part wins per method:
setResolver([resolverReactQuery, resolverHook])kubb/kit ships the parts the official plugins share:
| Part | Adds |
|---|---|
resolverOperationParams | param.name, param.path, param.query, param.headers, param.cookies |
resolverOperationResponse | response.status, response.headers, response.body, response.responses, response.response |
resolverCasedFile(caseLast) | file.baseName that nests dotted names and cases the file name with caseLast |
import { casing, createResolver, resolverCasedFile, resolverOperationParams, resolverOperationResponse } from 'kubb/kit'
export const resolverTs = createResolver<PluginTs>({
pluginName: 'plugin-ts',
name: (name) => casing.pascal(name),
...resolverOperationParams,
...resolverOperationResponse,
...resolverCasedFile(casing.pascal),
})Every name a part builds goes through the plugin's top-level name, so the part follows that plugin's casing. Build your own keys with operationKey(node, ...scope) so two declarations of one operation never share a name.
Resolver overrides
name changes identifier casing, file.name, file.baseName and file.path control files, and plugin namespaces control specific symbols. Users pass the same shape to a plugin's resolver option.
type ResolverPatch = {
name?: (name: string) => string
file?: {
name?: (node: SchemaNode | OperationNode, exportName?: string) => string | undefined
baseName?: (params: { name: string; extname: string }) => string
path?: (params: { baseName: string; output: Output }) => string
}
imports?: Resolver['imports']
// plugin-specific namespaces, such as query.keyName or schema.typeName
}- Write methods as regular functions, not arrow functions, so
thisis the merged resolver. file.namenames a node's file before casing. Returnundefinedto keep the default: theoperationIdor the schemaname.exportNameis the name another plugin imports withfrom. A plugin that writes several files per node uses it to say which file holds that name.file()andfrom()both readfile.name, so the files a plugin writes match the imports other plugins point at.- Kit adds
Operationto an operation file that would land on a schema file, but only for a plugin with aSchematemplate. - Kubb resolves the path
file.pathreturns against the rootoutput.path, and the result must stay inside it. Theoutputargument is the plugin's ownoutput. file.baseNameandfile.pathmust return the same result for the same arguments, becauseresolver.importskeeps each import path for the rest of the build.this.default.name(name)always appliescamelCase. For other casing, callcasingfromkubb/kit.- From a namespaced method,
this.name(name)calls the active top-levelname, including a user override. Inside the top-levelnameit recurses, so wrap an exported preset, such asresolverTs.name, instead. this.memo(key, compute)computes each value once per build. See Memo caches.
Less common cases
Ref imports in checks
When your plugin prints checks such as conditionals, contains, or a string's content, pass checks: true to resolver.imports. It then also imports the refs inside them.
Checks that cannot fail stay out: a contains with min: 0 and no max, and content that is not JSON or is encoded.
