index.d.mts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. import * as _nuxt_schema from '@nuxt/schema';
  2. import { ModuleOptions, ModuleDefinition, NuxtModule, NuxtConfig, Nuxt, ModuleMeta, NuxtOptions, SchemaDefinition, ImportPresetWithDeprecation, NuxtCompatibility, NuxtCompatibilityIssues, Component, ComponentsDir, NuxtTemplate, NuxtMiddleware, NuxtHooks, NuxtPlugin, NuxtPluginTemplate, ResolvedNuxtTemplate, NuxtServerTemplate, NuxtTypeTemplate } from '@nuxt/schema';
  3. import { LoadConfigOptions } from 'c12';
  4. import { Import } from 'unimport';
  5. import { WebpackPluginInstance, Configuration } from 'webpack';
  6. import { RspackPluginInstance } from '@rspack/core';
  7. import { Plugin, UserConfig } from 'vite';
  8. import * as unctx from 'unctx';
  9. import { NitroRouteConfig, NitroEventHandler, NitroDevEventHandler, Nitro } from 'nitropack';
  10. import * as consola from 'consola';
  11. import { ConsolaOptions } from 'consola';
  12. import { genSafeVariableName } from 'knitwork';
  13. /**
  14. * Define a Nuxt module, automatically merging defaults with user provided options, installing
  15. * any hooks that are provided, and calling an optional setup function for full control.
  16. */
  17. declare function defineNuxtModule<TOptions extends ModuleOptions>(definition: ModuleDefinition<TOptions, Partial<TOptions>, false> | NuxtModule<TOptions, Partial<TOptions>, false>): NuxtModule<TOptions, TOptions, false>;
  18. declare function defineNuxtModule<TOptions extends ModuleOptions>(): {
  19. with: <TOptionsDefaults extends Partial<TOptions>>(definition: ModuleDefinition<TOptions, TOptionsDefaults, true> | NuxtModule<TOptions, TOptionsDefaults, true>) => NuxtModule<TOptions, TOptionsDefaults, true>;
  20. };
  21. /** Installs a module on a Nuxt instance. */
  22. declare function installModule<T extends string | NuxtModule, Config extends Extract<NonNullable<NuxtConfig['modules']>[number], [T, any]>>(moduleToInstall: T, inlineOptions?: [Config] extends [never] ? any : Config[1], nuxt?: Nuxt): Promise<void>;
  23. declare function getDirectory(p: string): string;
  24. declare const normalizeModuleTranspilePath: (p: string) => string;
  25. declare function loadNuxtModuleInstance(nuxtModule: string | NuxtModule, nuxt?: Nuxt): Promise<{
  26. nuxtModule: NuxtModule<any>;
  27. buildTimeModuleMeta: ModuleMeta;
  28. resolvedModulePath?: string;
  29. }>;
  30. /**
  31. * Check if a Nuxt module is installed by name.
  32. *
  33. * This will check both the installed modules and the modules to be installed. Note
  34. * that it cannot detect if a module is _going to be_ installed programmatically by another module.
  35. */
  36. declare function hasNuxtModule(moduleName: string, nuxt?: Nuxt): boolean;
  37. /**
  38. * Checks if a Nuxt Module is compatible with a given semver version.
  39. */
  40. declare function hasNuxtModuleCompatibility(module: string | NuxtModule, semverVersion: string, nuxt?: Nuxt): Promise<boolean>;
  41. /**
  42. * Get the version of a Nuxt module.
  43. *
  44. * Scans installed modules for the version, if it's not found it will attempt to load the module instance and get the version from there.
  45. */
  46. declare function getNuxtModuleVersion(module: string | NuxtModule, nuxt?: Nuxt | any): Promise<string | false>;
  47. interface LoadNuxtConfigOptions extends Omit<LoadConfigOptions<NuxtConfig>, 'overrides'> {
  48. overrides?: Exclude<LoadConfigOptions<NuxtConfig>['overrides'], Promise<any> | Function>;
  49. }
  50. declare function loadNuxtConfig(opts: LoadNuxtConfigOptions): Promise<NuxtOptions>;
  51. declare function extendNuxtSchema(def: SchemaDefinition | (() => SchemaDefinition)): void;
  52. interface LoadNuxtOptions extends LoadNuxtConfigOptions {
  53. /** Load nuxt with development mode */
  54. dev?: boolean;
  55. /** Use lazy initialization of nuxt if set to false */
  56. ready?: boolean;
  57. /** @deprecated Use cwd option */
  58. rootDir?: LoadNuxtConfigOptions['cwd'];
  59. /** @deprecated use overrides option */
  60. config?: LoadNuxtConfigOptions['overrides'];
  61. }
  62. declare function loadNuxt(opts: LoadNuxtOptions): Promise<Nuxt>;
  63. declare function buildNuxt(nuxt: Nuxt): Promise<any>;
  64. declare function addImports(imports: Import | Import[]): void;
  65. declare function addImportsDir(dirs: string | string[], opts?: {
  66. prepend?: boolean;
  67. }): void;
  68. declare function addImportsSources(presets: ImportPresetWithDeprecation | ImportPresetWithDeprecation[]): void;
  69. /**
  70. * Access 'resolved' Nuxt runtime configuration, with values updated from environment.
  71. *
  72. * This mirrors the runtime behavior of Nitro.
  73. */
  74. declare function useRuntimeConfig(): Record<string, any>;
  75. /**
  76. * Update Nuxt runtime configuration.
  77. */
  78. declare function updateRuntimeConfig(runtimeConfig: Record<string, unknown>): void | Promise<void>;
  79. interface ExtendConfigOptions {
  80. /**
  81. * Install plugin on dev
  82. * @default true
  83. */
  84. dev?: boolean;
  85. /**
  86. * Install plugin on build
  87. * @default true
  88. */
  89. build?: boolean;
  90. /**
  91. * Install plugin on server side
  92. * @default true
  93. */
  94. server?: boolean;
  95. /**
  96. * Install plugin on client side
  97. * @default true
  98. */
  99. client?: boolean;
  100. /**
  101. * Prepends the plugin to the array with `unshift()` instead of `push()`.
  102. */
  103. prepend?: boolean;
  104. }
  105. interface ExtendWebpackConfigOptions extends ExtendConfigOptions {
  106. }
  107. interface ExtendViteConfigOptions extends ExtendConfigOptions {
  108. }
  109. /**
  110. * Extend webpack config
  111. *
  112. * The fallback function might be called multiple times
  113. * when applying to both client and server builds.
  114. */
  115. declare const extendWebpackConfig: (fn: ((config: Configuration) => void), options?: ExtendWebpackConfigOptions) => void;
  116. /**
  117. * Extend rspack config
  118. *
  119. * The fallback function might be called multiple times
  120. * when applying to both client and server builds.
  121. */
  122. declare const extendRspackConfig: (fn: ((config: Configuration) => void), options?: ExtendWebpackConfigOptions) => void;
  123. /**
  124. * Extend Vite config
  125. */
  126. declare function extendViteConfig(fn: ((config: UserConfig) => void), options?: ExtendViteConfigOptions): (() => void) | undefined;
  127. /**
  128. * Append webpack plugin to the config.
  129. */
  130. declare function addWebpackPlugin(pluginOrGetter: WebpackPluginInstance | WebpackPluginInstance[] | (() => WebpackPluginInstance | WebpackPluginInstance[]), options?: ExtendWebpackConfigOptions): void;
  131. /**
  132. * Append rspack plugin to the config.
  133. */
  134. declare function addRspackPlugin(pluginOrGetter: RspackPluginInstance | RspackPluginInstance[] | (() => RspackPluginInstance | RspackPluginInstance[]), options?: ExtendWebpackConfigOptions): void;
  135. /**
  136. * Append Vite plugin to the config.
  137. */
  138. declare function addVitePlugin(pluginOrGetter: Plugin | Plugin[] | (() => Plugin | Plugin[]), options?: ExtendViteConfigOptions): void;
  139. interface AddBuildPluginFactory {
  140. vite?: () => Plugin | Plugin[];
  141. webpack?: () => WebpackPluginInstance | WebpackPluginInstance[];
  142. rspack?: () => RspackPluginInstance | RspackPluginInstance[];
  143. }
  144. declare function addBuildPlugin(pluginFactory: AddBuildPluginFactory, options?: ExtendConfigOptions): void;
  145. declare function normalizeSemanticVersion(version: string): string;
  146. /**
  147. * Check version constraints and return incompatibility issues as an array
  148. */
  149. declare function checkNuxtCompatibility(constraints: NuxtCompatibility, nuxt?: Nuxt): Promise<NuxtCompatibilityIssues>;
  150. /**
  151. * Check version constraints and throw a detailed error if has any, otherwise returns true
  152. */
  153. declare function assertNuxtCompatibility(constraints: NuxtCompatibility, nuxt?: Nuxt): Promise<true>;
  154. /**
  155. * Check version constraints and return true if passed, otherwise returns false
  156. */
  157. declare function hasNuxtCompatibility(constraints: NuxtCompatibility, nuxt?: Nuxt): Promise<boolean>;
  158. /**
  159. * Check if current Nuxt instance is of specified major version
  160. */
  161. declare function isNuxtMajorVersion(majorVersion: 2 | 3 | 4, nuxt?: Nuxt): boolean;
  162. /**
  163. * @deprecated Use `isNuxtMajorVersion(2, nuxt)` instead. This may be removed in \@nuxt/kit v5 or a future major version.
  164. */
  165. declare function isNuxt2(nuxt?: Nuxt): boolean;
  166. /**
  167. * @deprecated Use `isNuxtMajorVersion(3, nuxt)` instead. This may be removed in \@nuxt/kit v5 or a future major version.
  168. */
  169. declare function isNuxt3(nuxt?: Nuxt): boolean;
  170. /**
  171. * Get nuxt version
  172. */
  173. declare function getNuxtVersion(nuxt?: Nuxt | any): string;
  174. /**
  175. * Register a directory to be scanned for components and imported only when used.
  176. *
  177. * Requires Nuxt 2.13+
  178. */
  179. declare function addComponentsDir(dir: ComponentsDir, opts?: {
  180. prepend?: boolean;
  181. }): void;
  182. type AddComponentOptions = {
  183. name: string;
  184. filePath: string;
  185. } & Partial<Exclude<Component, 'shortPath' | 'async' | 'level' | 'import' | 'asyncImport'>>;
  186. /**
  187. * This utility takes a file path or npm package that is scanned for named exports, which are get added automatically
  188. */
  189. declare function addComponentExports(opts: Omit<AddComponentOptions, 'name'> & {
  190. prefix?: string;
  191. }): void;
  192. /**
  193. * Register a component by its name and filePath.
  194. *
  195. * Requires Nuxt 2.13+
  196. */
  197. declare function addComponent(opts: AddComponentOptions): void;
  198. /**
  199. * Direct access to the Nuxt global context - see https://github.com/unjs/unctx.
  200. * @deprecated Use `getNuxtCtx` instead
  201. */
  202. declare const nuxtCtx: unctx.UseContext<Nuxt>;
  203. /** Direct access to the Nuxt context with asyncLocalStorage - see https://github.com/unjs/unctx. */
  204. declare const getNuxtCtx: () => Nuxt | null;
  205. /**
  206. * Get access to Nuxt instance.
  207. *
  208. * Throws an error if Nuxt instance is unavailable.
  209. * @example
  210. * ```js
  211. * const nuxt = useNuxt()
  212. * ```
  213. */
  214. declare function useNuxt(): Nuxt;
  215. /**
  216. * Get access to Nuxt instance.
  217. *
  218. * Returns null if Nuxt instance is unavailable.
  219. * @example
  220. * ```js
  221. * const nuxt = tryUseNuxt()
  222. * if (nuxt) {
  223. * // Do something
  224. * }
  225. * ```
  226. */
  227. declare function tryUseNuxt(): Nuxt | null;
  228. declare function runWithNuxtContext<T extends (...args: any[]) => any>(nuxt: Nuxt, fn: T): ReturnType<T>;
  229. declare function createIsIgnored(nuxt?: _nuxt_schema.Nuxt | null): (pathname: string, stats?: unknown) => boolean;
  230. /**
  231. * Return a filter function to filter an array of paths
  232. */
  233. declare function isIgnored(pathname: string, _stats?: unknown, nuxt?: _nuxt_schema.Nuxt | null): boolean;
  234. declare function resolveIgnorePatterns(relativePath?: string): string[];
  235. declare function addLayout(this: any, template: NuxtTemplate | string, name?: string): void;
  236. declare function extendPages(cb: NuxtHooks['pages:extend']): void;
  237. interface ExtendRouteRulesOptions {
  238. /**
  239. * Override route rule config
  240. * @default false
  241. */
  242. override?: boolean;
  243. }
  244. declare function extendRouteRules(route: string, rule: NitroRouteConfig, options?: ExtendRouteRulesOptions): void;
  245. interface AddRouteMiddlewareOptions {
  246. /**
  247. * Override existing middleware with the same name, if it exists
  248. * @default false
  249. */
  250. override?: boolean;
  251. /**
  252. * Prepend middleware to the list
  253. * @default false
  254. */
  255. prepend?: boolean;
  256. }
  257. declare function addRouteMiddleware(input: NuxtMiddleware | NuxtMiddleware[], options?: AddRouteMiddlewareOptions): void;
  258. declare function normalizePlugin(plugin: NuxtPlugin | string): NuxtPlugin;
  259. /**
  260. * Registers a nuxt plugin and to the plugins array.
  261. *
  262. * Note: You can use mode or .client and .server modifiers with fileName option
  263. * to use plugin only in client or server side.
  264. *
  265. * Note: By default plugin is prepended to the plugins array. You can use second argument to append (push) instead.
  266. * @example
  267. * ```js
  268. * import { createResolver } from '@nuxt/kit'
  269. * const resolver = createResolver(import.meta.url)
  270. *
  271. * addPlugin({
  272. * src: resolver.resolve('templates/foo.js'),
  273. * filename: 'foo.server.js' // [optional] only include in server bundle
  274. * })
  275. * ```
  276. */
  277. interface AddPluginOptions {
  278. append?: boolean;
  279. }
  280. declare function addPlugin(_plugin: NuxtPlugin | string, opts?: AddPluginOptions): NuxtPlugin;
  281. /**
  282. * Adds a template and registers as a nuxt plugin.
  283. */
  284. declare function addPluginTemplate(plugin: NuxtPluginTemplate | string, opts?: AddPluginOptions): NuxtPlugin;
  285. interface ResolvePathOptions {
  286. /** Base for resolving paths from. Default is Nuxt rootDir. */
  287. cwd?: string;
  288. /** An object of aliases. Default is Nuxt configured aliases. */
  289. alias?: Record<string, string>;
  290. /** The file extensions to try. Default is Nuxt configured extensions. */
  291. extensions?: string[];
  292. /**
  293. * Whether to resolve files that exist in the Nuxt VFS (for example, as a Nuxt template).
  294. * @default false
  295. */
  296. virtual?: boolean;
  297. /**
  298. * Whether to fallback to the original path if the resolved path does not exist instead of returning the normalized input path.
  299. *
  300. * @default false
  301. */
  302. fallbackToOriginal?: boolean;
  303. }
  304. /**
  305. * Resolve full path to a file or directory respecting Nuxt alias and extensions options
  306. *
  307. * If path could not be resolved, normalized input path will be returned
  308. */
  309. declare function resolvePath(path: string, opts?: ResolvePathOptions): Promise<string>;
  310. /**
  311. * Try to resolve first existing file in paths
  312. */
  313. declare function findPath(paths: string | string[], opts?: ResolvePathOptions, pathType?: 'file' | 'dir'): Promise<string | null>;
  314. /**
  315. * Resolve path aliases respecting Nuxt alias options
  316. */
  317. declare function resolveAlias(path: string, alias?: Record<string, string>): string;
  318. interface Resolver {
  319. resolve(...path: string[]): string;
  320. resolvePath(path: string, opts?: ResolvePathOptions): Promise<string>;
  321. }
  322. /**
  323. * Create a relative resolver
  324. */
  325. declare function createResolver(base: string | URL): Resolver;
  326. declare function resolveNuxtModule(base: string, paths: string[]): Promise<string[]>;
  327. declare function resolveFiles(path: string, pattern: string | string[], opts?: {
  328. followSymbolicLinks?: boolean;
  329. }): Promise<string[]>;
  330. /**
  331. * Adds a nitro server handler
  332. *
  333. */
  334. declare function addServerHandler(handler: NitroEventHandler): void;
  335. /**
  336. * Adds a nitro server handler for development-only
  337. *
  338. */
  339. declare function addDevServerHandler(handler: NitroDevEventHandler): void;
  340. /**
  341. * Adds a Nitro plugin
  342. */
  343. declare function addServerPlugin(plugin: string): void;
  344. /**
  345. * Adds routes to be prerendered
  346. */
  347. declare function addPrerenderRoutes(routes: string | string[]): void;
  348. /**
  349. * Access to the Nitro instance
  350. *
  351. * **Note:** You can call `useNitro()` only after `ready` hook.
  352. *
  353. * **Note:** Changes to the Nitro instance configuration are not applied.
  354. * @example
  355. *
  356. * ```ts
  357. * nuxt.hook('ready', () => {
  358. * console.log(useNitro())
  359. * })
  360. * ```
  361. */
  362. declare function useNitro(): Nitro;
  363. /**
  364. * Add server imports to be auto-imported by Nitro
  365. */
  366. declare function addServerImports(imports: Import[]): void;
  367. /**
  368. * Add directories to be scanned for auto-imports by Nitro
  369. */
  370. declare function addServerImportsDir(dirs: string | string[], opts?: {
  371. prepend?: boolean;
  372. }): void;
  373. /**
  374. * Add directories to be scanned by Nitro. It will check for subdirectories,
  375. * which will be registered just like the `~/server` folder is.
  376. */
  377. declare function addServerScanDir(dirs: string | string[], opts?: {
  378. prepend?: boolean;
  379. }): void;
  380. /**
  381. * Renders given template during build into the virtual file system (and optionally to disk in the project `buildDir`)
  382. */
  383. declare function addTemplate<T>(_template: NuxtTemplate<T> | string): ResolvedNuxtTemplate<T>;
  384. /**
  385. * Adds a virtual file that can be used within the Nuxt Nitro server build.
  386. */
  387. declare function addServerTemplate(template: NuxtServerTemplate): NuxtServerTemplate;
  388. /**
  389. * Renders given types during build to disk in the project `buildDir`
  390. * and register them as types.
  391. *
  392. * You can pass a second context object to specify in which context the type should be added.
  393. *
  394. * If no context object is passed, then it will only be added to the nuxt context.
  395. */
  396. declare function addTypeTemplate<T>(_template: NuxtTypeTemplate<T>, context?: {
  397. nitro?: boolean;
  398. nuxt?: boolean;
  399. }): ResolvedNuxtTemplate<T>;
  400. /**
  401. * Normalize a nuxt template object
  402. */
  403. declare function normalizeTemplate<T>(template: NuxtTemplate<T> | string, buildDir?: string): ResolvedNuxtTemplate<T>;
  404. /**
  405. * Trigger rebuilding Nuxt templates
  406. *
  407. * You can pass a filter within the options to selectively regenerate a subset of templates.
  408. */
  409. declare function updateTemplates(options?: {
  410. filter?: (template: ResolvedNuxtTemplate<any>) => boolean;
  411. }): Promise<any>;
  412. declare function writeTypes(nuxt: Nuxt): Promise<void>;
  413. declare const logger: consola.ConsolaInstance;
  414. declare function useLogger(tag?: string, options?: Partial<ConsolaOptions>): consola.ConsolaInstance;
  415. interface ResolveModuleOptions {
  416. /** @deprecated use `url` with URLs pointing at a file - never a directory */
  417. paths?: string | string[];
  418. url?: URL | URL[];
  419. }
  420. declare function directoryToURL(dir: string): URL;
  421. /**
  422. * Resolve a module from a given root path using an algorithm patterned on
  423. * the upcoming `import.meta.resolve`. It returns a file URL
  424. *
  425. * @internal
  426. */
  427. declare function tryResolveModule(id: string, url: URL | URL[]): Promise<string | undefined>;
  428. /** @deprecated pass URLs pointing at files */
  429. declare function tryResolveModule(id: string, url: string | string[]): Promise<string | undefined>;
  430. declare function resolveModule(id: string, options?: ResolveModuleOptions): string;
  431. interface ImportModuleOptions extends ResolveModuleOptions {
  432. /** Automatically de-default the result of requiring the module. */
  433. interopDefault?: boolean;
  434. }
  435. declare function importModule<T = unknown>(id: string, opts?: ImportModuleOptions): Promise<T>;
  436. declare function tryImportModule<T = unknown>(id: string, opts?: ImportModuleOptions): Promise<T | undefined> | undefined;
  437. /**
  438. * @deprecated Please use `importModule` instead.
  439. */
  440. declare function requireModule<T = unknown>(id: string, opts?: ImportModuleOptions): T;
  441. /**
  442. * @deprecated Please use `tryImportModule` instead.
  443. */
  444. declare function tryRequireModule<T = unknown>(id: string, opts?: ImportModuleOptions): T | undefined;
  445. /** @deprecated */
  446. declare function compileTemplate<T>(template: NuxtTemplate<T>, ctx: any): Promise<string>;
  447. /** @deprecated */
  448. declare const templateUtils: {
  449. serialize: (data: any) => string;
  450. importName: typeof genSafeVariableName;
  451. importSources: (sources: string | string[], { lazy }?: {
  452. lazy?: boolean | undefined;
  453. }) => string;
  454. };
  455. export { addBuildPlugin, addComponent, addComponentExports, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addPrerenderRoutes, addRouteMiddleware, addRspackPlugin, addServerHandler, addServerImports, addServerImportsDir, addServerPlugin, addServerScanDir, addServerTemplate, addTemplate, addTypeTemplate, addVitePlugin, addWebpackPlugin, assertNuxtCompatibility, buildNuxt, checkNuxtCompatibility, compileTemplate, createIsIgnored, createResolver, defineNuxtModule, directoryToURL, extendNuxtSchema, extendPages, extendRouteRules, extendRspackConfig, extendViteConfig, extendWebpackConfig, findPath, getDirectory, getNuxtCtx, getNuxtModuleVersion, getNuxtVersion, hasNuxtCompatibility, hasNuxtModule, hasNuxtModuleCompatibility, importModule, installModule, isIgnored, isNuxt2, isNuxt3, isNuxtMajorVersion, loadNuxt, loadNuxtConfig, loadNuxtModuleInstance, logger, normalizeModuleTranspilePath, normalizePlugin, normalizeSemanticVersion, normalizeTemplate, nuxtCtx, requireModule, resolveAlias, resolveFiles, resolveIgnorePatterns, resolveModule, resolveNuxtModule, resolvePath, runWithNuxtContext, templateUtils, tryImportModule, tryRequireModule, tryResolveModule, tryUseNuxt, updateRuntimeConfig, updateTemplates, useLogger, useNitro, useNuxt, useRuntimeConfig, writeTypes };
  456. export type { AddComponentOptions, AddPluginOptions, AddRouteMiddlewareOptions, ExtendConfigOptions, ExtendRouteRulesOptions, ExtendViteConfigOptions, ExtendWebpackConfigOptions, ImportModuleOptions, LoadNuxtConfigOptions, LoadNuxtOptions, ResolveModuleOptions, ResolvePathOptions, Resolver };