UNPKG

@kubb/react

Version:

React integration for Kubb, providing JSX runtime support and React component generation capabilities for code generation plugins.

885 lines (884 loc) 25.4 kB
import { BaseName, Export, Extname, File as File$1, Import, Mode, OptionalPath, Path, ResolvedFile, Source } from "./globals-CwlRa4y3.js"; import { FunctionParams, JSDoc, Key, KubbNode, createFunctionParams } from "./types-Caq5b3m8.js"; import * as react1 from "react"; import React, { ReactNode } from "react"; import * as react_jsx_runtime0 from "react/jsx-runtime"; import { ConsolaInstance, LogLevel } from "consola"; //#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; type ArrayWithLength<T extends number, U extends any[] = []> = U['length'] extends T ? U : ArrayWithLength<T, [true, ...U]>; type GreaterThan<T extends number, U extends number> = ArrayWithLength<U> extends [...ArrayWithLength<T>, ...infer _] ? false : true; //#endregion //#region ../core/src/types.d.ts 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<Extname, 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 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']; } & (TOptions['context'] extends never ? { context?: never; } : { context: 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 */ buildStart?: (this: PluginContext<TOptions>, Config: Config) => 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: BaseName, mode?: Mode, options?: TOptions['resolvePathOptions']) => OptionalPath; /** * 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; /** * End of the plugin lifecycle. * @type hookParallel */ buildEnd?: (this: PluginContext<TOptions>) => PossiblePromise<void>; }; type PluginLifecycleHooks = keyof PluginLifecycle; type PluginParameter<H extends PluginLifecycleHooks> = Parameters<Required<PluginLifecycle>[H]>; type ResolvePathParams<TOptions = object> = { pluginKey?: Plugin['key']; baseName: BaseName; mode?: 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> = { config: Config; fileManager: FileManager; pluginManager: PluginManager; addFile: (...file: Array<File$1>) => Promise<Array<ResolvedFile>>; resolvePath: (params: ResolvePathParams<TOptions['resolvePathOptions']>) => OptionalPath; resolveName: (params: ResolveNameParams) => string; logger: Logger; /** * All plugins */ plugins: Plugin[]; /** * Current plugin */ plugin: Plugin<TOptions>; }; /** * Specify the export location for the files and define the behavior of the output */ //#endregion //#region ../core/src/FileManager.d.ts type FileMetaBase = { pluginKey?: Plugin['key']; }; type AddResult<T extends Array<File$1>> = Promise<Awaited<GreaterThan<T['length'], 1> extends true ? Promise<ResolvedFile[]> : Promise<ResolvedFile>>>; type AddIndexesProps = { type: BarrelType | false | undefined; /** * Root based on root and output.path specified in the config */ root: string; /** * Output for plugin */ output: { path: string; }; group?: { output: string; exportAs: string; }; logger?: Logger; meta?: FileMetaBase; }; type WriteFilesProps = { root: Config['root']; extension?: Record<Extname, Extname | ''>; logger?: Logger; dryRun?: boolean; }; declare class FileManager { #private; constructor(); add<T extends Array<File$1> = Array<File$1>>(...files: T): AddResult<T>; getByPath(path: Path): Promise<ResolvedFile | null>; deleteByPath(path: Path): Promise<void>; clear(): Promise<void>; getFiles(): Promise<Array<ResolvedFile>>; processFiles({ dryRun, root, extension, logger }: WriteFilesProps): Promise<Array<ResolvedFile>>; getBarrelFiles({ type, meta, root, output, logger }: AddIndexesProps): Promise<File$1[]>; static getMode(path: string | undefined | null): Mode; } //#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 = { 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?: Mode; extname: Extname; pluginKey: Plugin['key']; options?: TOptions; }; declare class PluginManager { #private; readonly plugins: Set<Plugin<PluginFactoryOptions<string, object, object, any, object>>>; readonly fileManager: FileManager; readonly events: EventEmitter<Events>; readonly config: Config; readonly executed: Array<Executer>; readonly logger: Logger; readonly options: Options; constructor(config: Config, options: Options); getFile<TOptions = object>({ name, mode, extname, pluginKey, options }: GetFileProps<TOptions>): File$1<{ pluginKey: Plugin['key']; }>; resolvePath: <TOptions = object>(params: ResolvePathParams<TOptions>) => OptionalPath; 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[]; static getDependedPlugins<T1 extends PluginFactoryOptions, T2 extends PluginFactoryOptions = never, T3 extends PluginFactoryOptions = never, TOutput = (T3 extends never ? (T2 extends never ? [T1: Plugin<T1>] : [T1: Plugin<T1>, T2: Plugin<T2>]) : [T1: Plugin<T1>, T2: Plugin<T2>, T3: Plugin<T3>])>(plugins: Array<Plugin>, dependedPluginNames: string | string[]): TOutput; static get hooks(): readonly ["buildStart", "resolvePath", "resolveName", "buildEnd"]; } //#endregion //#region src/components/App.d.ts type AppContextProps = { /** * Exit (unmount) */ readonly exit: (error?: Error) => void; readonly mode: Mode; readonly pluginManager: PluginManager; readonly plugin: Plugin; }; type Props$5 = { readonly mode: Mode; readonly pluginManager: PluginManager; readonly plugin: Plugin; readonly children?: KubbNode; }; declare function App({ plugin, pluginManager, mode, children }: Props$5): react_jsx_runtime0.JSX.Element; declare namespace App { var Context: react1.Context<AppContextProps | undefined>; var displayName: string; } //#endregion //#region src/components/Const.d.ts type Props$4 = { key?: Key; /** * Name of the const */ name: string; /** * Does this type need to be exported. */ export?: boolean; /** * Type to make the const being typed */ type?: string; /** * Options for JSdocs. */ JSDoc?: JSDoc; /** * Use of `const` assertions */ asConst?: boolean; children?: KubbNode; }; declare function Const({ name, export: canExport, type, JSDoc, asConst, children }: Props$4): react_jsx_runtime0.JSX.Element; declare namespace Const { var displayName: string; } //#endregion //#region src/components/File.d.ts type FileContextProps<TMeta extends FileMetaBase = FileMetaBase> = { /** * Name to be used to dynamicly create the baseName(based on input.path). * Based on UNIX basename * @link https://nodejs.org/api/path.html#pathbasenamepath-suffix */ baseName: BaseName; /** * Path will be full qualified path to a specified file. */ path: Path; meta?: TMeta; }; type BasePropsWithBaseName = { /** * Name to be used to dynamicly create the baseName(based on input.path). * Based on UNIX basename * @link https://nodejs.org/api/path.html#pathbasenamepath-suffix */ baseName: BaseName; /** * Path will be full qualified path to a specified file. */ path: Path; }; type BasePropsWithoutBaseName = { baseName?: never; /** * Path will be full qualified path to a specified file. */ path?: Path; }; type BaseProps = BasePropsWithBaseName | BasePropsWithoutBaseName; type Props$3<TMeta extends FileMetaBase = FileMetaBase> = BaseProps & { key?: Key; meta?: TMeta; banner?: string; footer?: string; children?: KubbNode; }; declare function File<TMeta extends FileMetaBase = FileMetaBase>({ children, ...rest }: Props$3<TMeta>): react_jsx_runtime0.JSX.Element; declare namespace File { var displayName: string; var Export: typeof FileExport; var Import: typeof FileImport; var Source: typeof FileSource; var Context: react1.Context<FileContextProps<FileMetaBase>>; } type FileSourceProps = Omit<Source, 'value'> & { key?: Key; children?: KubbNode; }; declare function FileSource({ isTypeOnly, name, isExportable, isIndexable, children }: FileSourceProps): react_jsx_runtime0.JSX.Element; declare namespace FileSource { var displayName: string; } type FileExportProps = Export & { key?: Key; }; declare function FileExport({ name, path, isTypeOnly, asAlias }: FileExportProps): react_jsx_runtime0.JSX.Element; declare namespace FileExport { var displayName: string; } type FileImportProps = Import & { key?: Key; }; declare function FileImport({ name, root, path, isTypeOnly, isNameSpace }: FileImportProps): react_jsx_runtime0.JSX.Element; declare namespace FileImport { var displayName: string; } //#endregion //#region src/components/Function.d.ts type Props$2 = { key?: Key; /** * Name of the function. */ name: string; /** * Add default when export is being used */ default?: boolean; /** * Parameters/options/props that need to be used. */ params?: string; /** * Does this function need to be exported. */ export?: boolean; /** * Does the function has async/promise behaviour. * This will also add `Promise<returnType>` as the returnType. */ async?: boolean; /** * Generics that needs to be added for TypeScript. */ generics?: string | string[]; /** * ReturnType(see async for adding Promise type). */ returnType?: string; /** * Options for JSdocs. */ JSDoc?: JSDoc; children?: KubbNode; }; declare function Function({ name, default: isDefault, export: canExport, async, generics, params, returnType, JSDoc, children }: Props$2): react_jsx_runtime0.JSX.Element; declare namespace Function { var displayName: string; var Arrow: typeof ArrowFunction; } type ArrowFunctionProps = Props$2 & { /** * Create Arrow function in one line */ singleLine?: boolean; }; declare function ArrowFunction({ name, default: isDefault, export: canExport, async, generics, params, returnType, JSDoc, singleLine, children }: ArrowFunctionProps): react_jsx_runtime0.JSX.Element; declare namespace ArrowFunction { var displayName: string; } //#endregion //#region src/components/Indent.d.ts type IndentProps = { size?: number; children?: React.ReactNode; }; /** * Indents all children by `size` spaces. * Collapses consecutive <br /> tags to at most 2. */ declare function Indent({ size, children }: IndentProps): react_jsx_runtime0.JSX.Element | null; //#endregion //#region src/components/Text.d.ts type Props$1 = { key?: Key; /** * Change the indent. * @default 0 * @deprecated */ indentSize?: number; children?: KubbNode; }; /** * @deprecated */ declare function Text({ children }: Props$1): react_jsx_runtime0.JSX.Element; declare namespace Text { var displayName: string; var Space: typeof Space; } type SpaceProps = {}; declare function Space({}: SpaceProps): react_jsx_runtime0.JSX.Element; declare namespace Space { var displayName: string; } //#endregion //#region src/components/Type.d.ts type Props = { key?: Key; /** * Name of the type, this needs to start with a capital letter. */ name: string; /** * Does this type need to be exported. */ export?: boolean; /** * Options for JSdocs. */ JSDoc?: JSDoc; children?: KubbNode; }; declare function Type({ name, export: canExport, JSDoc, children }: Props): react_jsx_runtime0.JSX.Element; declare namespace Type { var displayName: string; } //#endregion //#region src/components/Root.d.ts type RootContextProps<Meta extends Record<string, unknown> = Record<string, unknown>> = { /** * Exit (unmount) the whole Ink app. */ readonly exit: (error?: Error) => void; readonly meta: Meta; }; //#endregion //#region src/renderer.d.ts type RendererResult = { output: string; imports: Array<Import>; exports: Array<Export>; files: Array<File$1>; }; //#endregion //#region src/ReactTemplate.d.ts type ReactTemplateOptions = { stdout?: NodeJS.WriteStream; stdin?: NodeJS.ReadStream; stderr?: NodeJS.WriteStream; logger?: Logger; /** * Set this to true to always see the result of the render in the console(line per render) */ debug?: boolean; }; type Context = Omit<RootContextProps, 'exit'>; declare class ReactTemplate { #private; constructor(options: ReactTemplateOptions); get output(): string; get files(): Array<File$1>; resolveExitPromise: (result: RendererResult) => void; rejectExitPromise: (reason?: Error) => void; unsubscribeExit: () => void; onRender: () => void; onError(error: Error): void; onExit(error?: Error): void; render(node: ReactNode, context?: Context): RendererResult; renderToString(node: ReactNode, context?: Context): Promise<string>; unmount(error?: Error | number | null): void; waitUntilExit(): Promise<RendererResult>; } //#endregion //#region src/createRoot.d.ts declare function createRoot(options?: ReactTemplateOptions): ReactTemplate; //#endregion //#region src/hooks/useApp.d.ts type AppResult<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = { /** * Exit (unmount) */ readonly exit: (error?: Error) => void; readonly plugin: Plugin<TOptions>; readonly mode: Mode; readonly pluginManager: PluginManager; readonly fileManager: FileManager; readonly getFile: PluginManager['getFile']; }; /** * `useApp` will return the current App with plugin, pluginManager, fileManager and mode. */ declare function useApp<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(): AppResult<TOptions>; //#endregion //#region src/hooks/useFile.d.ts /** * `useFile` will return the current file when <File/> is used. */ declare function useFile<TMeta extends FileMetaBase = FileMetaBase>(): FileContextProps<TMeta>; //#endregion //#region src/hooks/useLifecycle.d.ts /** * `useLifecycle` will return some helpers to exit/restart the generation. */ declare function useLifecycle(): { exit: (error?: Error) => void; }; //#endregion //#region src/index.d.ts declare const createContext: typeof react1.createContext; declare const createElement: typeof react1.createElement; declare const useContext: typeof react1.useContext; declare const useEffect: typeof react1.useEffect; declare const useState: typeof react1.useState; declare const useRef: typeof react1.useRef; declare const use: typeof react1.use; declare const useReducer: typeof react1.useReducer; //#endregion export { App, Const, File, Function, FunctionParams, Indent, Text, Type, createContext, createElement, createFunctionParams, createRoot, use, useApp, useContext, useEffect, useFile, useLifecycle, useReducer, useRef, useState }; //# sourceMappingURL=index.d.ts.map