@kubb/plugin-oas
Version:
OpenAPI Specification (OAS) plugin for Kubb, providing core functionality for parsing and processing OpenAPI/Swagger schemas for code generation.
849 lines (847 loc) • 24.1 kB
text/typescript
import { KubbFile } from "@kubb/fabric-core/types";
import { Fabric } from "@kubb/react-fabric";
import { ConsolaInstance, LogLevel } from "consola";
import * as OasTypes from "oas/types";
import { HttpMethods as HttpMethod, OASDocument, SchemaObject, User } from "oas/types";
import { Operation, Operation as Operation$1 } from "oas/operation";
import { OpenAPIV3, OpenAPIV3 as OpenAPIV3$1, OpenAPIV3_1 } from "openapi-types";
import * as oas_normalize_lib_types0 from "oas-normalize/lib/types";
import BaseOas from "oas";
//#region ../core/src/BaseGenerator.d.ts
/**
* Abstract class that contains the building blocks for plugins to create their own Generator
* @link idea based on https://github.com/colinhacks/zod/blob/master/src/types.ts#L137
*/
declare abstract class BaseGenerator<TOptions = unknown, TContext = unknown> {
#private;
constructor(options?: TOptions, context?: TContext);
get options(): TOptions;
get context(): TContext;
set options(options: TOptions);
abstract build(...params: unknown[]): unknown;
}
//#endregion
//#region ../core/src/utils/EventEmitter.d.ts
declare class EventEmitter<TEvents extends Record<string, any>> {
#private;
constructor();
emit<TEventName extends keyof TEvents & string>(eventName: TEventName, ...eventArg: TEvents[TEventName]): void;
on<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: (...eventArg: TEvents[TEventName]) => void): void;
off<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: (...eventArg: TEvents[TEventName]) => void): void;
removeAll(): void;
}
//#endregion
//#region ../core/src/logger.d.ts
type DebugEvent = {
date: Date;
logs: string[];
fileName?: string;
};
type Events$1 = {
start: [message: string];
success: [message: string];
error: [message: string, cause: Error];
warning: [message: string];
debug: [DebugEvent];
info: [message: string];
progress_start: [{
id: string;
size: number;
message?: string;
}];
progressed: [{
id: string;
message?: string;
}];
progress_stop: [{
id: string;
}];
};
type Logger = {
/**
* Optional config name to show in CLI output
*/
name?: string;
logLevel: LogLevel;
consola?: ConsolaInstance;
on: EventEmitter<Events$1>['on'];
emit: EventEmitter<Events$1>['emit'];
writeLogs: () => Promise<string[]>;
};
//#endregion
//#region ../core/src/utils/types.d.ts
type PossiblePromise<T> = Promise<T> | T;
//#endregion
//#region ../core/src/types.d.ts
declare global {
namespace Kubb {
interface PluginContext {}
}
}
/**
* Config used in `kubb.config.ts`
*
* @example
* import { defineConfig } from '@kubb/core'
* export default defineConfig({
* ...
* })
*/
type InputPath = {
/**
* Specify your Swagger/OpenAPI file, either as an absolute path or a path relative to the root.
*/
path: string;
};
type InputData = {
/**
* A `string` or `object` that contains your Swagger/OpenAPI data.
*/
data: string | unknown;
};
type Input = InputPath | InputData | Array<InputPath>;
type BarrelType = 'all' | 'named' | 'propagate';
/**
* @private
*/
type Config<TInput = Input> = {
/**
* The name to display in the CLI output.
*/
name?: string;
/**
* The project root directory, which can be either an absolute path or a path relative to the location of your `kubb.config.ts` file.
* @default process.cwd()
*/
root: string;
/**
* You can use either `input.path` or `input.data`, depending on your specific needs.
*/
input: TInput;
output: {
/**
* The path where all generated files will be exported.
* This can be an absolute path or a path relative to the specified root option.
*/
path: string;
/**
* Clean the output directory before each build.
*/
clean?: boolean;
/**
* Save files to the file system.
* @default true
*/
write?: boolean;
/**
* Specifies the formatting tool to be used.
* @default prettier
*
* Possible values:
* - 'prettier': Uses Prettier for code formatting.
* - 'biome': Uses Biome for code formatting.
*
*/
format?: 'prettier' | 'biome' | false;
/**
* Specifies the linter that should be used to analyze the code.
* The accepted values indicate different linting tools.
*
* Possible values:
* - 'eslint': Represents the use of ESLint, a widely used JavaScript linter.
* - 'biome': Represents the Biome linter, a modern tool for code scanning.
* - 'oxlint': Represents the Oxlint tool for linting purposes.
*
*/
lint?: 'eslint' | 'biome' | 'oxlint' | false;
/**
* Override the extension to the generated imports and exports, by default each plugin will add an extension
* @default { '.ts': '.ts'}
*/
extension?: Record<KubbFile.Extname, KubbFile.Extname | ''>;
/**
* Specify how `index.ts` files should be created. You can also disable the generation of barrel files here. While each plugin has its own `barrelType` option, this setting controls the creation of the root barrel file, such as` src/gen/index.ts`.
* @default 'named'
*/
barrelType?: Exclude<BarrelType, 'propagate'> | false;
/**
* Add a default banner to the beginning of every generated file. This makes it clear that the file was generated by Kubb.
* - 'simple': will only add banner with link to Kubb
* - 'full': will add source, title, description and the OpenAPI version used
* @default 'simple'
*/
defaultBanner?: 'simple' | 'full' | false;
};
/**
* An array of Kubb plugins that will be used in the generation.
* Each plugin may include additional configurable options(defined in the plugin itself).
* If a plugin depends on another plugin, an error will be returned if the required dependency is missing. See pre for more details.
*/
plugins?: Array<Plugin>;
/**
* Hooks that will be called when a specific action is triggered in Kubb.
*/
hooks?: {
/**
* Hook that will be triggered at the end of all executions.
* Useful for running Prettier or ESLint to format/lint your code.
*/
done?: string | Array<string>;
};
};
type PluginFactoryOptions<
/**
* Name to be used for the plugin, this will also be used for they key.
*/
TName extends string = string,
/**
* Options of the plugin.
*/
TOptions extends object = object,
/**
* Options of the plugin that can be used later on, see `options` inside your plugin config.
*/
TResolvedOptions extends object = TOptions,
/**
* Context that you want to expose to other plugins.
*/
TContext = any,
/**
* When calling `resolvePath` you can specify better types.
*/
TResolvePathOptions extends object = object> = {
name: TName;
/**
* Same behaviour like what has been done with `QueryKey` in `@tanstack/react-query`
*/
key: PluginKey<TName | string>;
options: TOptions;
resolvedOptions: TResolvedOptions;
context: TContext;
resolvePathOptions: TResolvePathOptions;
};
type PluginKey<TName> = [name: TName, identifier?: string | number];
type UserPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
/**
* Unique name used for the plugin
* The name of the plugin follows the format scope:foo-bar or foo-bar, adding scope: can avoid naming conflicts with other plugins.
* @example @kubb/typescript
*/
name: TOptions['name'];
/**
* Options set for a specific plugin(see kubb.config.js), passthrough of options.
*/
options: TOptions['resolvedOptions'];
/**
* Specifies the preceding plugins for the current plugin. You can pass an array of preceding plugin names, and the current plugin will be executed after these plugins.
* Can be used to validate dependent plugins.
*/
pre?: Array<string>;
/**
* Specifies the succeeding plugins for the current plugin. You can pass an array of succeeding plugin names, and the current plugin will be executed before these plugins.
*/
post?: Array<string>;
inject?: (this: PluginContext<TOptions>, context: PluginContext<TOptions>) => TOptions['context'];
};
type UserPluginWithLifeCycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = UserPlugin<TOptions> & PluginLifecycle<TOptions>;
type Plugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
/**
* Unique name used for the plugin
* @example @kubb/typescript
*/
name: TOptions['name'];
/**
* Internal key used when a developer uses more than one of the same plugin
* @private
*/
key: TOptions['key'];
/**
* Specifies the preceding plugins for the current plugin. You can pass an array of preceding plugin names, and the current plugin will be executed after these plugins.
* Can be used to validate dependent plugins.
*/
pre?: Array<string>;
/**
* Specifies the succeeding plugins for the current plugin. You can pass an array of succeeding plugin names, and the current plugin will be executed before these plugins.
*/
post?: Array<string>;
/**
* Options set for a specific plugin(see kubb.config.js), passthrough of options.
*/
options: TOptions['resolvedOptions'];
install: (this: PluginContext<TOptions>, context: PluginContext<TOptions>) => PossiblePromise<void>;
/**
* Define a context that can be used by other plugins, see `PluginManager' where we convert from `UserPlugin` to `Plugin`(used when calling `definePlugin`).
*/
inject: (this: PluginContext<TOptions>, context: PluginContext<TOptions>) => TOptions['context'];
};
type PluginWithLifeCycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & PluginLifecycle<TOptions>;
type PluginLifecycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
/**
* Start of the lifecycle of a plugin.
* @type hookParallel
*/
install?: (this: PluginContext<TOptions>, context: PluginContext<TOptions>) => PossiblePromise<void>;
/**
* Resolve to a Path based on a baseName(example: `./Pet.ts`) and directory(example: `./models`).
* Options can als be included.
* @type hookFirst
* @example ('./Pet.ts', './src/gen/') => '/src/gen/Pet.ts'
*/
resolvePath?: (this: PluginContext<TOptions>, baseName: KubbFile.BaseName, mode?: KubbFile.Mode, options?: TOptions['resolvePathOptions']) => KubbFile.Path;
/**
* Resolve to a name based on a string.
* Useful when converting to PascalCase or camelCase.
* @type hookFirst
* @example ('pet') => 'Pet'
*/
resolveName?: (this: PluginContext<TOptions>, name: ResolveNameParams['name'], type?: ResolveNameParams['type']) => string;
};
type PluginLifecycleHooks = keyof PluginLifecycle;
type PluginParameter<H extends PluginLifecycleHooks> = Parameters<Required<PluginLifecycle>[H]>;
type ResolvePathParams<TOptions = object> = {
pluginKey?: Plugin['key'];
baseName: KubbFile.BaseName;
mode?: KubbFile.Mode;
/**
* Options to be passed to 'resolvePath' 3th parameter
*/
options?: TOptions;
};
type ResolveNameParams = {
name: string;
pluginKey?: Plugin['key'];
/**
* `file` will be used to customize the name of the created file(use of camelCase)
* `function` can be used to customize the exported functions(use of camelCase)
* `type` is a special type for TypeScript(use of PascalCase)
* `const` can be used for variables(use of camelCase)
*/
type?: 'file' | 'function' | 'type' | 'const';
};
type PluginContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
fabric: Fabric;
config: Config;
pluginManager: PluginManager;
/**
* Only add when the file does not exist yet
*/
addFile: (...file: Array<KubbFile.File>) => Promise<void>;
/**
* merging multiple sources into the same output file
*/
upsertFile: (...file: Array<KubbFile.File>) => Promise<void>;
logger: Logger;
mode: KubbFile.Mode;
/**
* Current plugin
*/
plugin: Plugin<TOptions>;
} & Kubb.PluginContext;
/**
* Specify the export location for the files and define the behavior of the output
*/
type Output<TOptions> = {
/**
* Path to the output folder or file that will contain the generated code
*/
path: string;
/**
* Define what needs to be exported, here you can also disable the export of barrel files
* @default 'named'
*/
barrelType?: BarrelType | false;
/**
* Add a banner text in the beginning of every file
*/
banner?: string | ((options: TOptions) => string);
/**
* Add a footer text in the beginning of every file
*/
footer?: string | ((options: TOptions) => string);
};
type GroupContext = {
group: string;
};
type Group = {
/**
* Define a type where to group the files on
*/
type: 'tag' | 'path';
/**
* Return the name of a group based on the group name, this will be used for the file and name generation
*/
name?: (context: GroupContext) => string;
};
//#endregion
//#region ../core/src/PluginManager.d.ts
type RequiredPluginLifecycle = Required<PluginLifecycle>;
type Strategy = 'hookFirst' | 'hookForPlugin' | 'hookParallel' | 'hookSeq';
type Executer<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
message: string;
strategy: Strategy;
hookName: H;
plugin: Plugin;
parameters?: unknown[] | undefined;
output?: unknown;
};
type ParseResult<H extends PluginLifecycleHooks> = RequiredPluginLifecycle[H];
type SafeParseResult<H extends PluginLifecycleHooks, Result = ReturnType<ParseResult<H>>> = {
result: Result;
plugin: Plugin;
};
type Options$1 = {
fabric: Fabric;
logger: Logger;
/**
* @default Number.POSITIVE_INFINITY
*/
concurrency?: number;
};
type Events = {
executing: [executer: Executer];
executed: [executer: Executer];
error: [error: Error];
};
type GetFileProps<TOptions = object> = {
name: string;
mode?: KubbFile.Mode;
extname: KubbFile.Extname;
pluginKey: Plugin['key'];
options?: TOptions;
};
declare class PluginManager {
#private;
readonly events: EventEmitter<Events>;
readonly config: Config;
readonly executed: Array<Executer>;
readonly logger: Logger;
readonly options: Options$1;
constructor(config: Config, options: Options$1);
getContext<TOptions extends PluginFactoryOptions>(plugin: Plugin<TOptions>): PluginContext<TOptions> & Record<string, any>;
get plugins(): Array<Plugin>;
getFile<TOptions = object>({
name,
mode,
extname,
pluginKey,
options
}: GetFileProps<TOptions>): KubbFile.File<{
pluginKey: Plugin['key'];
}>;
resolvePath: <TOptions = object>(params: ResolvePathParams<TOptions>) => KubbFile.Path;
resolveName: (params: ResolveNameParams) => string;
/**
* Instead of calling `pluginManager.events.on` you can use `pluginManager.on`. This one also has better types.
*/
on<TEventName extends keyof Events & string>(eventName: TEventName, handler: (...eventArg: Events[TEventName]) => void): void;
/**
* Run a specific hookName for plugin x.
*/
hookForPlugin<H extends PluginLifecycleHooks>({
pluginKey,
hookName,
parameters,
message
}: {
pluginKey: Plugin['key'];
hookName: H;
parameters: PluginParameter<H>;
message: string;
}): Promise<Array<ReturnType<ParseResult<H>> | null>>;
/**
* Run a specific hookName for plugin x.
*/
hookForPluginSync<H extends PluginLifecycleHooks>({
pluginKey,
hookName,
parameters,
message
}: {
pluginKey: Plugin['key'];
hookName: H;
parameters: PluginParameter<H>;
message: string;
}): Array<ReturnType<ParseResult<H>>> | null;
/**
* First non-null result stops and will return it's value.
*/
hookFirst<H extends PluginLifecycleHooks>({
hookName,
parameters,
skipped,
message
}: {
hookName: H;
parameters: PluginParameter<H>;
skipped?: ReadonlySet<Plugin> | null;
message: string;
}): Promise<SafeParseResult<H>>;
/**
* First non-null result stops and will return it's value.
*/
hookFirstSync<H extends PluginLifecycleHooks>({
hookName,
parameters,
skipped,
message
}: {
hookName: H;
parameters: PluginParameter<H>;
skipped?: ReadonlySet<Plugin> | null;
message: string;
}): SafeParseResult<H>;
/**
* Run all plugins in parallel(order will be based on `this.plugin` and if `pre` or `post` is set).
*/
hookParallel<H extends PluginLifecycleHooks, TOuput = void>({
hookName,
parameters,
message
}: {
hookName: H;
parameters?: Parameters<RequiredPluginLifecycle[H]> | undefined;
message: string;
}): Promise<Awaited<TOuput>[]>;
/**
* Chains plugins
*/
hookSeq<H extends PluginLifecycleHooks>({
hookName,
parameters,
message
}: {
hookName: H;
parameters?: PluginParameter<H>;
message: string;
}): Promise<void>;
getPluginByKey(pluginKey: Plugin['key']): Plugin | undefined;
getPluginsByKey(hookName: keyof PluginWithLifeCycle, pluginKey: Plugin['key']): Plugin[];
}
//#endregion
//#region ../core/src/utils/getBarrelFiles.d.ts
type FileMetaBase = {
pluginKey?: Plugin['key'];
};
//#endregion
//#region ../oas/src/types.d.ts
type contentType = 'application/json' | (string & {});
type SchemaObject$1 = OasTypes.SchemaObject & {
'x-nullable'?: boolean;
$ref?: string;
};
//#endregion
//#region ../oas/src/Oas.d.ts
type Options = {
contentType?: contentType;
discriminator?: 'strict' | 'inherit';
};
declare class Oas<const TOAS = unknown> extends BaseOas {
#private;
document: TOAS;
constructor({
oas,
user
}: {
oas: TOAS | OASDocument | string;
user?: User;
});
setOptions(options: Options): void;
get options(): Options;
get($ref: string): any;
getKey($ref: string): string | undefined;
set($ref: string, value: unknown): false | undefined;
getDiscriminator(schema: OasTypes.SchemaObject): OpenAPIV3.DiscriminatorObject | undefined;
dereferenceWithRef(schema?: unknown): any;
getResponseSchema(operation: Operation, statusCode: string | number): SchemaObject;
getRequestSchema(operation: Operation): SchemaObject | undefined;
getParametersSchema(operation: Operation, inKey: 'path' | 'query' | 'header'): SchemaObject | null;
valdiate(): Promise<oas_normalize_lib_types0.ValidationResult>;
}
//#endregion
//#region ../oas/src/utils.d.ts
declare function isOptional(schema?: SchemaObject): boolean;
//#endregion
//#region src/SchemaMapper.d.ts
type SchemaKeywordMapper = {
object: {
keyword: 'object';
args: {
properties: {
[x: string]: Schema[];
};
additionalProperties: Schema[];
strict?: boolean;
};
};
url: {
keyword: 'url';
};
readOnly: {
keyword: 'readOnly';
};
writeOnly: {
keyword: 'writeOnly';
};
uuid: {
keyword: 'uuid';
};
email: {
keyword: 'email';
};
firstName: {
keyword: 'firstName';
};
lastName: {
keyword: 'lastName';
};
phone: {
keyword: 'phone';
};
password: {
keyword: 'password';
};
date: {
keyword: 'date';
args: {
type?: 'date' | 'string';
};
};
time: {
keyword: 'time';
args: {
type?: 'date' | 'string';
};
};
datetime: {
keyword: 'datetime';
args: {
offset?: boolean;
local?: boolean;
};
};
tuple: {
keyword: 'tuple';
args: {
items: Schema[];
min?: number;
max?: number;
rest?: Schema;
};
};
array: {
keyword: 'array';
args: {
items: Schema[];
min?: number;
max?: number;
unique?: boolean;
};
};
enum: {
keyword: 'enum';
args: {
name: string;
typeName: string;
asConst: boolean;
items: Array<{
name: string | number;
format: 'string' | 'number' | 'boolean';
value?: string | number | boolean;
}>;
};
};
and: {
keyword: 'and';
args: Schema[];
};
const: {
keyword: 'const';
args: {
name: string | number;
format: 'string' | 'number' | 'boolean';
value?: string | number | boolean;
};
};
union: {
keyword: 'union';
args: Schema[];
};
ref: {
keyword: 'ref';
args: {
name: string;
$ref: string;
/**
* Full qualified path.
*/
path: KubbFile.Path;
/**
* When true `File.Import` will be used.
* When false a reference will be used inside the current file.
*/
isImportable: boolean;
};
};
matches: {
keyword: 'matches';
args?: string;
};
boolean: {
keyword: 'boolean';
};
default: {
keyword: 'default';
args: string | number | boolean;
};
string: {
keyword: 'string';
};
integer: {
keyword: 'integer';
};
number: {
keyword: 'number';
};
max: {
keyword: 'max';
args: number;
};
min: {
keyword: 'min';
args: number;
};
exclusiveMaximum: {
keyword: 'exclusiveMaximum';
args: number;
};
exclusiveMinimum: {
keyword: 'exclusiveMinimum';
args: number;
};
describe: {
keyword: 'describe';
args: string;
};
example: {
keyword: 'example';
args: string;
};
deprecated: {
keyword: 'deprecated';
};
optional: {
keyword: 'optional';
};
undefined: {
keyword: 'undefined';
};
nullish: {
keyword: 'nullish';
};
nullable: {
keyword: 'nullable';
};
null: {
keyword: 'null';
};
any: {
keyword: 'any';
};
unknown: {
keyword: 'unknown';
};
void: {
keyword: 'void';
};
blob: {
keyword: 'blob';
};
schema: {
keyword: 'schema';
args: {
type: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object';
format?: string;
};
};
name: {
keyword: 'name';
args: string;
};
catchall: {
keyword: 'catchall';
};
interface: {
keyword: 'interface';
};
};
declare const schemaKeywords: {
any: "any";
unknown: "unknown";
number: "number";
integer: "integer";
string: "string";
boolean: "boolean";
undefined: "undefined";
nullable: "nullable";
null: "null";
nullish: "nullish";
array: "array";
tuple: "tuple";
enum: "enum";
union: "union";
datetime: "datetime";
date: "date";
email: "email";
uuid: "uuid";
url: "url";
void: "void";
default: "default";
const: "const";
and: "and";
describe: "describe";
min: "min";
max: "max";
exclusiveMinimum: "exclusiveMinimum";
exclusiveMaximum: "exclusiveMaximum";
optional: "optional";
readOnly: "readOnly";
writeOnly: "writeOnly";
object: "object";
ref: "ref";
matches: "matches";
firstName: "firstName";
lastName: "lastName";
password: "password";
phone: "phone";
blob: "blob";
deprecated: "deprecated";
example: "example";
schema: "schema";
catchall: "catchall";
time: "time";
name: "name";
interface: "interface";
};
type SchemaKeyword = keyof SchemaKeywordMapper;
type SchemaMapper<T = string | null | undefined> = { [K in keyof SchemaKeywordMapper]: (() => T | undefined) | undefined };
type SchemaKeywordBase<T> = {
keyword: SchemaKeyword;
args: T;
};
type Schema = {
keyword: string;
} | SchemaKeywordMapper[keyof SchemaKeywordMapper];
type SchemaTree = {
schema: SchemaObject$1;
parent: Schema | undefined;
current: Schema;
siblings: Schema[];
/**
* this will be equal to the key of a property(object)
*/
name?: string;
};
declare function isKeyword<T extends Schema, K extends keyof SchemaKeywordMapper>(meta: T, keyword: K): meta is Extract<T, SchemaKeywordMapper[K]>;
//#endregion
export { Plugin as C, BaseGenerator as D, UserPluginWithLifeCycle as E, Output as S, ResolveNameParams as T, contentType as _, SchemaMapper as a, Config as b, schemaKeywords as c, HttpMethod as d, OasTypes as f, SchemaObject$1 as g, Operation$1 as h, SchemaKeywordMapper as i, isOptional as l, OpenAPIV3_1 as m, SchemaKeyword as n, SchemaTree as o, OpenAPIV3$1 as p, SchemaKeywordBase as r, isKeyword as s, Schema as t, Oas as u, FileMetaBase as v, PluginFactoryOptions as w, Group as x, PluginManager as y };
//# sourceMappingURL=SchemaMapper-DOSP3wgJ.d.cts.map