import * as types from '@babel/types'; import { Program, ImportDeclaration, Node, CallExpression, File } from '@babel/types'; import traverse, { NodePath } from '@babel/traverse'; import template from '@babel/template'; import { parse, parseExpression, ParserPlugin } from '@babel/parser'; import generate from '@babel/generator'; import { ModuleNode, Plugin, ViteDevServer, ResolvedConfig } from 'vite'; declare type State = { /** * Get the state shared during traversal. */ get(key: K): T; /** * Get the state shared during traversal or set the state if it's missing. */ getOrSet(key: K, or: T): T; /** * Set the state shared during traversal. */ set(key: K, value: T): T; /** * Clear the state shared during traversal. */ clear(): boolean; /** * Delete the state shared during traversal. */ delete(key: K): void; }; /** * ```typescript * import 'moduleName' * { moduleName: string } * * import defaultName from 'moduleName' * { defaultName: string; moduleName: string } * * import { exportName } from 'moduleName' * { exportName: string; moduleName: string } * * import { exportName as localName } from 'moduleName' * { localName: string; exportName: string; moduleName: string } * * import * as namespaceName from 'moduleName' * { namespaceName: string; moduleName: string } * ``` */ declare type ImportOption = { moduleName: string; } | { defaultName: string; moduleName: string; } | { localName: string; exportName: string; moduleName: string; } | { exportName: string; moduleName: string; } | { namespaceName: string; moduleName: string; }; declare type PathPatternNormalizer = { /** * Normalized path or path pattern, */ normalized: string; /** * Base path for the normalized path or path pattern. */ base: string; /** * Get import path from file path got by normalized path and base, * almost the opposite operation of normalization * @param path file path */ resolveImportPath: (path: string) => string; }; declare type NamespacedMacros = { [namespace: string]: Macro[]; }; declare type NamespacedModules = { [namespace: string]: string; }; declare type NamespacedTypes = { [namespace: string]: { moduleScope: string[]; macroScope: string[]; }; }; declare type Exportable = ({ /** * as macros */ macros: Macro[]; } | { /** * as module, code will be used as source code of the module */ code: string; }) & { /** * Type definitions, will be written to d.ts. * * e.g. * ```typescript * { exports: { '@macros': { customTypes: `type A = string` } } } * ``` * will generate * ```typescript * declare module '@macros' { * type A = string * } * ``` */ customTypes?: string; }; declare type NamespacedExportable = { [namespace: string]: Exportable; }; declare type NormalizedExports = { macros: NamespacedMacros; modules: NamespacedModules; types: NamespacedTypes; }; declare type MacroHelper = { /** * Prepend import statements to program. * @param imports an import or an array of imports * @param program node path of the target program for prepending import statements. * use the one currently being handled by default. * @return node path of the last inserted import statement, * or undefined if imports param is array and length === 0 */ prependImports: (imports: ImportOption[] | ImportOption, program?: NodePath) => NodePath | undefined; /** * Append import statements to the last import statement of the program. * @param imports an import or an array of imports * @param program node path of the target program for prepending import statements. * use the one currently being handled by default. * @return node path of the last inserted import statement * or undefined if imports param is array and length === 0 */ appendImports: (imports: ImportOption[] | ImportOption, program?: NodePath) => NodePath | undefined; /** * Find an import statement that has been in the target program already. * Note that findImported() will not resolve extension for moduleName automatically. * @param imports an import * @param loose match loosely, defaults to true, e.g: * `import { a as _a } from 'a'` will match `{ moduleName: 'a' }` and `{ moduleName: 'a', exportName: 'a' }` * @param program node path of the target program. use the one currently being handled by default. */ findImported: (imports: ImportOption, loose?: boolean, program?: NodePath) => NodePath | undefined; /** * Check if an import statement has been in the target program already. * Note that hasImported() will not resolve extension for moduleName automatically. * @param imports an import * @param loose match loosely, defaults to true, e.g: * `import { a as _a } from 'a'` will match `{ moduleName: 'a' }` and `{ moduleName: 'a', exportName: 'a' }` * @param program node path of the target program. use the one currently being handled by default. */ hasImported: (imports: ImportOption, loose?: boolean, program?: NodePath) => boolean; /** * Prepend any node to the target program. * @param nodes any node or an array of nodes * @param program node path of the target program. use the one currently being handled by default. * @return node path of the last inserted node */ prependToBody: (nodes: Nodes, program?: NodePath) => NodePath; /** * Append any node to the target program. * @param nodes any node or an array of nodes * @param program node path of the target program. use the one currently being handled by default. * @return node path of the last inserted node */ appendToBody: (nodes: Nodes, program?: NodePath) => NodePath; /** * Normalize path pattern so can resolve file paths as import paths * @param path relative path or path pattern * @param root absolute file path of the project dir, default to projectDir('leaf') * @param importer absolute file path of the importer, default to current file * * e.g. search files by glob pattern and then import them * * ```typescript * // /src/example/a.ts * // /src/example/b.ts * // in /src/another/index.ts * const pattern = '../example/*.ts' * const { normalized, base, resolveImportPath } = normalizePathPattern(pattern) * const importPaths = glob.sync(normalized, { cwd: base }).map(resolveImportPath) * * // importPaths = ['../example/a.ts', '../example/b.ts'] * ``` */ normalizePathPattern: (pattern: string, root?: string, importer?: string) => PathPatternNormalizer; /** * Get the directory of the root project or the nearest project. * @param which 'root' or 'leaf' */ projectDir: (which: 'root' | 'leaf') => string; /** * Check whether there are unexpanded macros under the path(s). * @param path the node path(s) to be checked, use the arguments of the current * call expression by default */ containsMacros: (...paths: NodePath[]) => boolean[]; }; declare type Babel = { /** * From @babel/template. * Help generate nodes from code string. * * e.g. * ```typescript * template.statement.ast('const a = 1') // generate a statement node * ``` */ template: typeof template; /** * From @babel/traverse. * Help traverse from a node. * * e.g. * ```typescript * traverse(someNode, { * CallExpression(path) { * ... * } * }) * ``` */ traverse: typeof traverse; /** * From @babel/types. * Help check node type and create nodes of specific type. * * e.g. * ```typescript * types.isIdentifier(someNode) // check is identifier * types.identifier('hello') // create identifier node * ``` */ types: typeof types; /** * From @babel/parser. * Help parse code string to ast. * * e.g. * ```typescript * parse('const a = 1') * ``` */ parse: typeof parse; /** * From @babel/parser. * Help parse code string to expression. * * e.g. * ```typescript * parseExpression('1 + 2') * ``` */ parseExpression: typeof parseExpression; /** * From @babel/generator. * Help generate code string from ast. * * e.g. * ```typescript * generate(someNode) * ``` */ generate: typeof generate; }; declare type MacroContext = { /** * The file path of the module currently being handled. */ filepath: string; /** * The original source code of the module currently being handled. */ code: string; /** * The arguments node paths of the call-macro expression currently being handled. */ args: CallExpression['arguments'] extends Array ? NodePath[] : never; /** * The NodePath of the call-macro expression currently being handled. */ path: NodePath; /** * The AST being traversed. */ ast: File; /** * Whether in ssr mode. */ ssr: boolean; /** * Whether in dev mode. */ dev: boolean; /** * Traversal state. */ state: { /** * In order to recursively expand all macros in a file, * the transformer will traverse the AST many times until all macros * are expanded. * * - {@link traversal} is the state shared during one traversal, and * - {@link transform} is the state shared during the whole transformation. */ traversal: State; /** * @see traversal */ transform: State; }; }; declare type YieldContext = NodePath | NodePath[] | undefined; declare type SuspendableTransform = Generator; declare type MacroHandler = ( /** * Context about the macro caller. */ ctx: MacroContext, /** * Babel tools to help operate node paths and nodes. */ babel: Readonly, /** * Wrappers upon babel tools to simplify operations. */ helper: Readonly) => SuspendableTransform | unknown; declare type MacroCall = { ctx: MacroContext; babel: Readonly; helper: Readonly; }; declare type Macro = (call: MacroCall) => SuspendableTransform; declare type MacroBuilder = { /** * Add custom type definition, it will be written to .d.ts before macro signature. */ withCustomType: (typeDefinition: string) => Omit; /** * Add signature of macro. one macro requires at least one signature. * @param signature function signature, like '(s: string): void' * @param comment comment for the signature, will be written to .d.ts * before the corresponding function signature. */ withSignature: (signature: string, comment?: string) => Omit; /** * Set the transform handler and get the macro. * * Async function can not be used as macro handler. * * If the handler is a normal function, the nested macros inside the current * call expression will be expanded automatically before calling the handler. * * If the handler is a generator function, you can: * - yield node paths of import statements to collect macros from them, * note macros must be collected before used, or you can wait for the next round of traversal, * and the runtime(transformer) will collect imported macros again before the traversal * - yield node paths to actively expand macros inside them * * e.g. * ```typescript * .withHandler(function*({ args }) { * // do some thing * yield args // expand macros inside the current call expression * // do some thing * yield someOtherNodePath * // do some thing * }) * ``` */ withHandler: (handler: MacroHandler) => Macro; }; /** * Define a macro. * @param name the name of the macro, should be a valid identifier name. * @return macro builder. */ declare function defineMacro(name: string): Omit; declare type DevServerHelper = { /** * Invalidate caches of modules that import macros from specific namespace, * only available in dev mode. * * This is usually used when, the macro needs to be re-expanded due to * the change of external conditions, while the modules that call * the macro cannot be automatically reloaded because their dependencies * in the module dependency graph have no change so Vite always caches them. */ invalidateCache: (namespace: string) => void; /** * Find modules that import macros from specific namespace, * only available in dev mode. */ findImporters: (namespace: string) => Set; }; declare type TypeRendererOptions = { types: NamespacedTypes; /** * The path of the automatically generated type declaration file. */ typesPath: string; }; declare type TransformerOptions = { /** * The max recursion for applying macros, default to 5. * * After reached the maxRecursions, plugin will throw out an error. * * It's usually caused by forgetting to remove/modify the call expression * in macros. */ maxRecursions?: number; /** * Babel plugins to be applied during parsing. * * 'typescript', 'jsx' and 'importMeta' * are included by default and cannot be removed. * * Some plugins are enabled automatically by the latest babel parser * because they have been regarded as part of the language. * * @see https://babeljs.io/docs/en/babel-parser#plugins * @see https://babeljs.io/docs/en/babel-parser#latest-ecmascript-features */ parserPlugins?: ParserPlugin[]; }; declare type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; declare type FlatOptions = UnionToIntersection; declare type DeepPartial> = { [P in keyof RT]?: RT[P] extends Array ? Array : DeepPartial; }; declare type FilterPattern = RegExp | string | Array; declare type FilterOptions = { /** * Regexp or glob patterns to include matches, applied after * {@link FilterOptions.exclude}. * * The default value is `/\.[jt]sx?$/`. * * Once this option is defined, the default one will be overwritten. */ include?: FilterPattern; /** * Regexp or glob patterns to exclude matches, applied before * {@link FilterOptions.include}. * * The default value is `/node_modules/`. * * Once this option is defined, the default one will be overwritten. */ exclude?: FilterPattern; }; declare type RuntimeOptions = { /** * The options for transformer. */ transformer: TransformerOptions; /** * The options for typeRenderer. */ typeRenderer: Pick; /** * The options that control the filtering of which files * require transformations to be applied. */ filter: FilterOptions; }; declare type Attachable = { exports: NormalizedExports; options?: DeepPartial; }; declare type MacroPluginHooks = Omit & { configureServer?: (server: ViteDevServer, helpers: DevServerHelper) => (() => void) | void | Promise<(() => void) | void>; }; interface MacroPlugin extends Plugin { __consume: () => Attachable; } declare type MacroPluginOptions = FlatOptions & { /** * The name of plugin. */ name: string; /** * Plugin hooks. */ hooks?: MacroPluginHooks; /** * Exports macros or modules in different namespaces. * @see MacroProviderOptions.exports */ exports: NamespacedExportable; }; /** * Define a macro plugin. * @param options plugin options. * @return A vite plugin, can be used as rollup plugin as well. */ declare function defineMacroPlugin(options: MacroPluginOptions): Plugin; declare type ViteStartContext = ({ /** * Is in dev mode. */ dev: true; /** * Vite dev server. */ server: ViteDevServer; /** * Wrappers on vite dev server. */ helper: DevServerHelper; } | { /** * Is in dev mode. */ dev: false; }) & { /** * Vite resolved config. */ config: ResolvedConfig; }; declare type MacroProviderHooks = { /** * A startup hook called only if running in Vite. */ onViteStart?: (ctx: ViteStartContext) => void | Promise; /** * A startup hook called only if running in Rollup. */ onRollupStart?: () => void | Promise; /** * A startup hook, called immediately after {@link onViteStart}/{@link onRollupStart}. */ onStart?: () => void | Promise; }; declare type MacroProvider = { id: string; exports: NormalizedExports; hooks: MacroProviderHooks; options?: Partial>; }; declare type MacroProviderOptions = { /** * The id of provider. */ id: string; /** * Provider hooks. */ hooks?: MacroProviderHooks; /** * Exports macros so macros can be imported and called, * the value of the key will be the name of namespace(or called `module`). * * Also supports exporting modules (source codes), * but a namespace cannot export both module and macros. * * e.g. * ```typescript * const macroA = defineMacro('macroA') * .withSignature('(...args: any[]): void') * .withHandler(()=>...) * * { * exports: { * '@macros': { macros: [macroA] }, * '@helper': { * code: `export const a = 1`, * customTypes: `export const a:number` * } * }, * } * ``` * Then in some .js(x) or .ts(x) file you can * ```typescript * import { macroA } from '@macros' * import { a } from '@helper' * macroA(someArgs) * console.log(a) * ``` */ exports: NamespacedExportable; /** * Provider options. */ options?: { /** * @see TransformerOptions.parserPlugins */ parserPlugins?: ParserPlugin[]; }; }; /** * Define a macro provider. * @param options provider options. */ declare function defineMacroProvider(options: MacroProviderOptions): MacroProvider; /** * A manager/container of macros. */ declare type MacroManager = { /** * Register {@link MacroProvider} or {@link MacroPlugin} to this macro manager so that * all macros in providers and plugins share the same runtime. * * For macro plugins: * > Some options like `maxRecursions` or `typesPath` will be overridden by * > manager's, `parserPlugins` will be merged with the manager's one. * > * > After registered, the original macro plugin will be attached to the manager, * > which means no need to add the plugin to Vite/Rollup 's plugins array again. * @param sources macro providers or plugins. */ use(sources: MacroProvider | Plugin | (MacroProvider | Plugin)[]): MacroManager; /** * Get a shallow copy of the underlying plugins of the macro manager. * In most cases, it can be used as one plugin directly since Vite flats * plugin array automatically. */ toPlugin(): Plugin[]; }; declare type MacroManagerOptions = FlatOptions & { /** * The name of macro manager, also the name of the final plugin. */ name: string; }; /** * Define a macro manager. * @param options manager options. */ declare function createMacroManager(options: MacroManagerOptions): MacroManager; /** * Get a macro manager of the default options. * * @see MacroManager */ declare function vitePluginMacro(options?: Partial): MacroManager; declare type TestTransformerContext = { /** * Source code. */ code: string; /** * Path of the source file. * * Default to 'test.tsx' */ filepath?: string; /** * Is in SSR mode. * * Default to false. */ ssr?: boolean; /** * Is in dev mode. * * Default to false. * * If in dev mode, the import statements that imports macros * will be retained and rewritten by the runtime * to track the module's dependence on the macro. */ dev?: boolean; }; declare type TestTransformer = { (ctx: TestTransformerContext, macros: NamespacedMacros): string; (code: string, macros: NamespacedMacros): string; }; /** * Create a transformer to help test macros. * * e.g. * ```typescript * const aMacro = defineMacro(...) * .withSignature(...) * .withHandler(...) * * const transform = createTestTransformer() * * expect( * transform(`some code...`, { '@ns': [aMacro] }) * ).toBe(`some code...`) * ``` * * @param options the same as the one of transformer */ declare function createTestTransformer(options?: TransformerOptions): TestTransformer; declare type TestTypeRenderer = (exports: NamespacedExportable) => string; /** * Create a type renderer to help test the type of macros/modules. * * e.g. * ```typescript * const aMacro = defineMacro(...) * .withSignature(...) * .withHandler(...) * * const renderType = createTestTypeRenderer() * * expect( * renderType({ * '@ns': { * macros: [aMacro] * customTypes: `some types...` * }, * '@another': { * code: `some code...` * customTypes: `some types...` * } * }) * ).toMatchSnapshot() * ``` */ declare function createTestTypeRenderer(): TestTypeRenderer; export { Babel, DevServerHelper, Exportable, ImportOption, Macro, MacroContext, MacroHandler, MacroHelper, MacroManager, MacroManagerOptions, MacroPlugin, MacroPluginHooks, MacroPluginOptions, MacroProvider, MacroProviderHooks, MacroProviderOptions, NamespacedExportable, TestTransformer, TestTransformerContext, TestTypeRenderer, createMacroManager, createTestTransformer, createTestTypeRenderer, defineMacro, defineMacroPlugin, defineMacroProvider, vitePluginMacro };