diff --git a/src/types/config.ts b/src/types/config.ts index e6b31ce531..eef7421bc0 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -34,7 +34,12 @@ import type { NitroRouteConfig, NitroRouteRules } from "./route-rules.ts"; type RollupCommonJSOptions = NonNullable[0]>; /** - * Nitro normalized options (nitro.options) + * Fully resolved Nitro options available on `nitro.options`. + * + * These are the normalized options after preset defaults and user config + * have been merged. For the user-facing input type, see {@link NitroConfig}. + * + * @see https://nitro.build/config */ export interface NitroOptions extends PresetOptions { // Internal @@ -44,46 +49,258 @@ export interface NitroOptions extends PresetOptions { command?: string; }; - // Compatibility + // General + + /** + * Opt-in date for deployment provider features. + * + * Providers introduce new features that Nitro presets can leverage, but + * some need to be explicitly opted into. Set to the latest tested date + * in `YYYY-MM-DD` format. + * + * @default "latest" + * @see https://nitro.build/config#compatibilitydate + */ compatibilityDate: CompatibilityDates; - // General + /** + * Enable debug mode for verbose logging and additional development + * information. + * + * Automatically enabled when the `DEBUG` environment variable is set. + * + * @see https://nitro.build/config#debug + */ debug: boolean; + + /** + * Deployment preset name. + * + * Determines how the production bundle is built and optimized for a + * specific hosting provider or runtime. Auto-detected in known + * environments when not set. Use the `NITRO_PRESET` environment + * variable as an alternative. + * + * @see https://nitro.build/config#preset + */ preset: PresetName; + + /** + * Disable the server build and only output prerendered static assets. + * + * When `true`, the server bundle is skipped entirely and only the public directory is produced. + * Typically used by the `static` preset and its derivatives (e.g., `github-pages`, `vercel-static`). + * + * Note: This does not enable prerendering on its own — configure `prerender` options separately. + * + * @see https://nitro.build/config#static + */ static: boolean; + + /** + * Log verbosity level. + * + * Defaults to `3`, or `1` when a testing environment is detected. + * + * @see https://nitro.build/config#loglevel + * @see https://github.com/unjs/consola + */ logLevel: LogLevel; + + /** + * Server runtime configuration accessible via `useRuntimeConfig()`. + * + * Values can be overridden at runtime using environment variables with + * the `NITRO_` prefix. An alternative prefix can be configured via + * `runtimeConfig.nitro.envPrefix` or `NITRO_ENV_PREFIX`. + * + * **Note:** The `nitro` namespace is reserved for internal use. + * + * @example + * ```ts + * runtimeConfig: { + * apiSecret: "default-secret", // override with NITRO_API_SECRET + * } + * ``` + * + * @see https://nitro.build/config#runtimeconfig + */ runtimeConfig: NitroRuntimeConfig; // Dirs + + /** + * Project workspace root directory. + * + * Auto-detected from the workspace (e.g. pnpm workspace) when not set. + * + * @see https://nitro.build/config#workspacedir + */ workspaceDir: string; + + /** + * Project main root directory. + * + * @see https://nitro.build/config#rootdir + */ rootDir: string; + + /** + * Server directory for scanning `api/`, `routes/`, `plugins/`, `utils/`, + * `middleware/`, `modules/`, and `tasks/` folders. + * + * Set to `false` to disable automatic directory scanning, `"./"` to use + * the root directory, or `"./server"` to use a `server/` subdirectory. + * + * @default false + * @see https://nitro.build/config#serverdir + */ serverDir: string | false; + + /** + * Additional directories to scan and auto-register files such as API + * route handlers. + * + * @see https://nitro.build/config#scandirs + */ scanDirs: string[]; + + /** + * Directory name to scan for API route handlers. + * + * @default "api" + * @see https://nitro.build/config#apidir + */ apiDir: string; + + /** + * Directory name to scan for route handlers. + * + * @default "routes" + * @see https://nitro.build/config#routesdir + */ routesDir: string; + + /** + * Nitro's temporary working directory for build-related files. + * + * @default "node_modules/.nitro" + * @see https://nitro.build/config#builddir + */ buildDir: string; + + /** + * Output directories for the production bundle. + * + * @see https://nitro.build/config#output + */ output: { + /** Production output root directory. */ dir: string; + /** Server bundle output directory. */ serverDir: string; + /** Public/static assets output directory. */ publicDir: string; }; - /** @deprecated migrate to `serverDir` */ + /** @deprecated Migrate to `serverDir`. */ srcDir: string; // Features + + /** + * Storage mount configuration. + * + * Keys are mount-point paths; values specify the unstorage driver and + * its options. + * + * @see https://nitro.build/config#storage + * @see https://nitro.build/docs/storage + */ storage: StorageMounts; + + /** + * Storage mount overrides for development mode. + * + * Useful for swapping production drivers (e.g. Redis) with local + * alternatives (e.g. filesystem) during development. + * + * @see https://nitro.build/config#devstorage + * @see https://nitro.build/docs/storage + */ devStorage: StorageMounts; + + /** + * Database connection configurations. + * + * Requires `experimental.database: true`. + * + * @see https://nitro.build/config#database + * @see https://nitro.build/docs/database + */ database: DatabaseConnectionConfigs; + + /** + * Database connection overrides for development mode. + * + * @see https://nitro.build/config#devdatabase + * @see https://nitro.build/docs/database + */ devDatabase: DatabaseConnectionConfigs; + + /** + * Server-side rendering entry configuration. + * + * Points to the main render handler (the file should export an event + * handler as default). Set to `false` to disable. + * + * @see https://nitro.build/config#renderer + * @see https://nitro.build/docs/renderer + */ renderer?: { handler?: string; static?: boolean; template?: string }; + + /** + * Routes that should be server-side rendered. + */ ssrRoutes: string[]; + + /** + * Include a static asset handler in the server bundle to serve public assets. + * + * - `true` or `"node"` — read assets from the filesystem using Node.js `fs`. + * - `"deno"` — read assets using Deno file APIs. + * - `"inline"` — base64-encode assets directly into the server bundle. + * - `false` — do not serve static assets from the server (rely on a CDN or reverse proxy). + * + * Most self-hosted presets (e.g. `node-server`, `bun`) enable this by default. + * + * @see https://nitro.build/config#servestatic + */ serveStatic: boolean | "node" | "deno" | "inline"; + + /** + * Disable the public output directory entirely. + * + * Skips preparing the `.output/public` directory, copying public + * assets, and prerendering routes. + * + * @see https://nitro.build/config#nopublicdir + */ noPublicDir: boolean; tracingChannel?: undefined | TracingOptions; - manifest?: { + + /** + * Build manifest options. + */ manifest?: { + /** Custom deployment identifier included in the build manifest. */ deploymentId?: string; }; + + /** + * Built-in feature flags. + * + * @see https://nitro.build/config#features + */ features: { /** * Enable runtime hooks for request and response. @@ -93,22 +310,36 @@ export interface NitroOptions extends PresetOptions { runtimeHooks?: boolean; /** - * Enable WebSocket support + * Enable WebSocket support. */ websocket?: boolean; }; /** + * WASM import support configuration. * + * Set to `false` to disable. + * + * @see https://nitro.build/config#wasm * @see https://github.com/unjs/unwasm */ wasm?: false | UnwasmPluginOptions; + /** - * OpenAPI configuration + * OpenAPI specification generation and UI configuration. * + * @see https://nitro.build/config#openapi * @see https://nitro.build/docs/openapi */ openAPI?: NitroOpenAPIConfig; + + /** + * Experimental feature flags. + * + * These features are not yet stable and may change in future releases. + * + * @see https://nitro.build/config#experimental + */ experimental: { /** * Enable experimental OpenAPI support @@ -125,7 +356,9 @@ export interface NitroOptions extends PresetOptions { */ asyncContext?: boolean; /** - * Disable Experimental Sourcemap Minification + * Set to `false` to disable sourcemap minification in production builds. + * + * Sourcemap minification is enabled by default when `sourcemap` is on. */ sourcemapMinify?: false; /** @@ -137,80 +370,325 @@ export interface NitroOptions extends PresetOptions { /** * Enable WebSocket support * - * @see https://nitro.build/guide/websocket - * - * @deprecated use `features.websocket` instead. + * @deprecated Use `features.websocket` instead. */ websocket?: boolean; /** * Enable experimental Database support * - * @see https://nitro.build/guide/database + * @see https://nitro.build/docs/database */ database?: boolean; /** * Enable experimental Tasks support * - * @see https://nitro.build/guide/tasks + * @see https://nitro.build/docs/tasks */ tasks?: boolean; }; + + /** + * Future features pending a major version to avoid breaking changes. + * + * @see https://nitro.build/config#future + */ future: { + /** Opt in to Nitro's native `isr` route rule handling on Vercel and suppress backwards-compatibility warnings for legacy `swr`/`static` route options. */ nativeSWR?: boolean; }; + + /** + * Server-side asset directories bundled at build time. + * + * @see https://nitro.build/config#serverassets + * @see https://nitro.build/docs/assets#server-assets + */ serverAssets: ServerAssetDir[]; + + /** + * Public asset directories served in development and bundled in production. + * + * A `public/` directory is added by default when detected. + * + * @see https://nitro.build/config#publicassets + * @see https://nitro.build/docs/assets + */ publicAssets: PublicAssetDir[]; + /** + * Auto-import configuration. + * + * Set to `false` to disable auto-imports. Pass an object to customize. + * + * @default false + * @see https://nitro.build/config#imports + * @see https://github.com/unjs/unimport + */ imports: Partial | false; + + /** + * Nitro modules to extend behavior during initialization. + * + * Accepts module path strings, {@link NitroModule} objects, or bare setup functions. + * + * @see https://nitro.build/config#modules + */ modules?: NitroModuleInput[]; + + /** + * Paths to Nitro runtime plugins. + * + * Plugins in the `plugins/` directory are auto-registered. + * + * @see https://nitro.build/config#plugins + * @see https://nitro.build/docs/plugins + */ plugins: string[]; + + /** + * Task definitions. + * + * Each key is a task name with a `handler` path and optional `description`. + * + * @example + * ```ts + * tasks: { + * "db:migrate": { + * handler: "./tasks/db-migrate", + * description: "Run database migrations", + * }, + * } + * ``` + * + * @see https://nitro.build/config#tasks + * @see https://nitro.build/docs/tasks + */ tasks: { [name: string]: { handler?: string; description?: string } }; + + /** + * Map of cron expressions to task name(s). + * + * @example + * ```ts + * scheduledTasks: { + * "0 * * * *": "cleanup:temp", + * "*​/5 * * * *": ["health:check", "metrics:collect"], + * } + * ``` + * + * @see https://nitro.build/config#scheduledtasks + * @see https://nitro.build/docs/tasks + */ scheduledTasks: { [cron: string]: string | string[] }; + + /** + * Virtual module definitions. + * + * A map from dynamic virtual import names to their contents or an async + * function that returns them. + * + * @see https://nitro.build/config#virtual + */ virtual: Record string | Promise)>; + + /** + * Pre-compress public assets and prerendered routes. + * + * Generates gzip and brotli (and zstd when available) + * variants of compressible assets larger than 1024 bytes. Pass an + * object to selectively enable/disable each encoding. + * + * @see https://nitro.build/config#compresspublicassets + */ compressPublicAssets: boolean | CompressOptions; + + /** + * Glob patterns to ignore when scanning directories. + * + * @see https://nitro.build/config#ignore + */ ignore: string[]; // Dev + + /** + * Whether the current build targets development mode. + * + * Defaults to `true` during development and `false` for production. + * + * @see https://nitro.build/config#dev + */ dev: boolean; + + /** + * Development server options. + * + * @see https://nitro.build/config#devserver + */ devServer: { + /** Port number for the dev server. */ port?: number; + /** Hostname for the dev server. */ hostname?: string; + /** Additional paths to watch for dev server reloads. */ watch?: string[]; + /** Runtime runner to use for the dev server. */ runner?: RunnerName; }; + + /** + * File watcher options for development mode. + * + * @see https://nitro.build/config#watchoptions + * @see https://github.com/paulmillr/chokidar + */ watchOptions: ChokidarOptions; + + /** + * Proxy configuration for the development server. + * + * A map of path prefixes to proxy target URLs or options. + * + * @example + * ```ts + * devProxy: { + * "/proxy/test": "http://localhost:3001", + * "/proxy/example": { target: "https://example.com", changeOrigin: true }, + * } + * ``` + * + * @see https://nitro.build/config#devproxy + * @see https://github.com/unjs/httpxy + */ devProxy: Record; // Logging + + /** + * Build logging behavior. + * + * @see https://nitro.build/config#logging + */ logging: { + /** Report compressed bundle sizes after build. */ compressedSizes?: boolean; + /** Show the build success message. */ buildSuccess?: boolean; }; // Routing + + /** + * Server's main base URL prefix. + * + * Can also be set via the `NITRO_APP_BASE_URL` environment variable. + * + * @default "/" + * @see https://nitro.build/config#baseurl + */ baseURL: string; + + /** + * Base URL prefix for API routes. + * + * @default "/api" + * @see https://nitro.build/config#apibaseurl + */ apiBaseURL: string; + /** + * Custom server entry point configuration. + * + * Set to `false` to disable the default server entry. + * + * @see https://nitro.build/docs/server-entry + */ serverEntry: false | { handler: string; format?: EventHandlerFormat }; + + /** + * Server handler registrations. + * + * Handlers in `routes/`, `api/`, and `middleware/` directories are + * auto-registered when {@link NitroOptions.serverDir | serverDir} is set. + * + * @see https://nitro.build/config#handlers + * @see https://nitro.build/docs/routing + */ handlers: NitroEventHandler[]; + + /** + * Development-only event handlers with inline handler functions. + * + * Not included in production builds. + * + * @see https://nitro.build/config#devhandlers + */ devHandlers: NitroDevEventHandler[]; + + /** + * Route rules applied to matching request paths. + * + * Supports caching, redirects, proxying, headers, CORS, and more. + * Rules are matched using rou3 patterns and deep-merged when multiple + * patterns match. + * + * @see https://nitro.build/config#routerules + * @see https://nitro.build/docs/routing#route-rules + */ routeRules: { [path: string]: NitroRouteRules }; + + /** + * Inline route definitions. + * + * A map from route pattern to handler path or handler options. + * + * @see https://nitro.build/config#routes + */ routes: Record>; + /** + * Path(s) to custom runtime error handler(s). + * + * Custom handlers run before the built-in error handler, which is + * always added as a fallback. + * + * @see https://nitro.build/config#errorhandler + */ errorHandler: string | string[]; + + /** + * Custom error handler function for development mode. + * + * @see https://nitro.build/config#deverrorhandler + */ devErrorHandler: NitroErrorHandler; + /** + * Prerendering options. + * + * Routes specified here are fetched during the build and copied to + * `.output/public` as static assets. + * + * @see https://nitro.build/config#prerender + */ prerender: { /** - * Prerender HTML routes within subfolders (`/test` would produce `/test/index.html`) + * Prerender HTML routes within subfolders (`/test` produces `/test/index.html`). */ autoSubfolderIndex?: boolean; + /** Maximum number of concurrent prerender requests. */ concurrency?: number; + /** Delay in milliseconds between prerender requests. */ interval?: number; + /** Crawl `` tags in prerendered HTML to discover additional routes. */ crawlLinks?: boolean; + /** Fail the build when a route cannot be prerendered. */ failOnError?: boolean; + /** Patterns (string, RegExp, or function) of routes to skip. */ ignore?: Array undefined | null | boolean)>; + /** Skip prerendering assets without a base URL prefix. */ ignoreUnprefixedPublicAssets?: boolean; + /** Explicit list of routes to prerender. */ routes?: string[]; /** * Amount of retries. Pass Infinity to retry indefinitely. @@ -224,64 +702,237 @@ export interface NitroOptions extends PresetOptions { retryDelay?: number; }; - // Rollup + // Build + + /** + * Bundler to use for production builds. + * + * Auto-detected when not set: `"vite"` if a `vite.config` with the + * `nitro()` plugin is found, otherwise `"rolldown"` (bundled with Nitro). + * Use the `NITRO_BUILDER` environment variable as an alternative. + * + * @see https://nitro.build/config#builder + */ builder?: "rollup" | "rolldown" | "vite"; + + /** + * Additional Rollup configuration. + * + * @see https://nitro.build/config#rollupconfig + */ rollupConfig?: RollupConfig; + + /** + * Additional Rolldown configuration. + * + * @see https://nitro.build/config#rolldownconfig + */ rolldownConfig?: RolldownConfig; + + /** + * Bundler entry point path. + * + * @see https://nitro.build/config#entry + */ entry: string; + + /** + * unenv preset(s) for environment compatibility polyfills. + * + * @see https://nitro.build/config#unenv + * @see https://github.com/unjs/unenv + */ unenv: UnenvPreset[]; + + /** + * Path aliases for module resolution. + * + * @example + * ```ts + * alias: { + * "~utils": "./src/utils", + * "#shared": "./shared", + * } + * ``` + * + * @see https://nitro.build/config#alias + */ alias: Record; + + /** + * Minify the production bundle. + * + * @see https://nitro.build/config#minify + */ minify: boolean; + + /** + * Bundle all code into a single file instead of separate chunks. + * + * When `false`, each route handler becomes a separate chunk loaded + * on-demand. Some presets enable this by default. + * + * @see https://nitro.build/config#inlinedynamicimports + */ inlineDynamicImports: boolean; + + /** + * Enable source map generation. + * + * @see https://nitro.build/config#sourcemap + */ sourcemap: boolean; + + /** + * Target a Node.js-compatible runtime. + * + * When `true` (default), the bundler targets the `node` platform, prefers + * Node.js built-in modules, and enables dependency externalization. + * + * When `false`, Nitro prepends the `nodeless` unenv preset to polyfill + * Node.js globals and built-ins for non-Node runtimes (workers, edge, Deno). + * + * @see https://nitro.build/config#node + */ node: boolean; + + /** + * OXC options for Rolldown builds (minification and transforms). + * + * @see https://nitro.build/config#oxc + */ oxc?: OXCOptions; + + /** + * Build-time string replacements. + * + * @see https://nitro.build/config#replace + */ replace: Record string)>; + + /** + * Additional configuration for the Rollup CommonJS plugin. + * + * @see https://nitro.build/config#commonjs + */ commonJS?: RollupCommonJSOptions; + + /** + * Custom export conditions for module resolution. + * + * @see https://nitro.build/config#exportconditions + */ exportConditions?: string[]; + + /** + * Prevent packages from being externalized. + * + * Set to `true` to bundle all dependencies, or pass an array of + * package names or patterns. + * + * @see https://nitro.build/config#noexternals + */ noExternals?: boolean | (string | RegExp)[]; + + /** + * Additional dependencies to trace and include in the build output. + * + * Supports `!pkg` to exclude and `pkg*` for full package trace. + * + * @see https://nitro.build/config#tracedeps + */ traceDeps?: (string | RegExp)[]; + + /** + * Advanced options for dependency tracing via nf3. + * + * @see https://nitro.build/config#traceopts + * @see https://github.com/nicolo-ribaudo/nf3 + */ traceOpts?: Pick; // Advanced + + /** + * TypeScript configuration options. + * + * @see https://nitro.build/config#typescript + */ typescript: { + /** Enable strict TypeScript checks. */ strict?: boolean; + /** Generate types for runtime config. */ generateRuntimeConfigTypes?: boolean; + /** Generate a `tsconfig.json` in the build directory. */ generateTsConfig?: boolean; + /** Custom tsconfig overrides. */ tsConfig?: Partial; /** * Path of the generated types directory. * - * Default is `node_modules/.nitro/types` + * @default "node_modules/.nitro/types" */ generatedTypesDir?: string; /** - * Path of the generated `tsconfig.json` relative to `typescript.generatedTypesDir` + * Path of the generated `tsconfig.json` relative to `typescript.generatedTypesDir`. * - * Default is `tsconfig.json` (`node_modules/.nitro/types/tsconfig.json`) + * @default "tsconfig.json" */ tsconfigPath?: string; }; + + /** + * Nitro lifecycle hooks. + * + * @see https://nitro.build/config#hooks + * @see https://nitro.build/docs/lifecycle + * @see https://github.com/unjs/hookable + */ hooks: NestedHooks; + + /** + * Preview and deploy command hints (usually filled by deployment presets). + * + * @see https://nitro.build/config#commands + */ commands: { + /** Command to preview the production build locally. */ preview?: string; + /** Command to deploy the production build. */ deploy?: string; }; - // Framework + /** + * Metadata about the higher-level framework using Nitro (e.g. Nuxt). + * + * Used by presets and included in build info output. + * + * @see https://nitro.build/config#framework + */ framework: NitroFrameworkInfo; - // IIS + /** + * IIS-specific deployment options. + */ iis?: { + /** Merge with existing IIS `web.config` instead of replacing. */ mergeConfig?: boolean; + /** Override existing IIS `web.config` entirely. */ overrideConfig?: boolean; }; } /** - * Nitro input config (nitro.config) + * User-facing Nitro configuration used in `nitro.config.ts` or + * `defineNitroConfig()`. + * + * All properties are optional and will be merged with defaults and preset + * values to produce the fully resolved {@link NitroOptions}. + * + * @see https://nitro.build/config + * @see https://nitro.build/docs/configuration */ export interface NitroConfig extends @@ -320,6 +971,7 @@ export interface NitroConfig // Config Loader // ------------------------------------------------------------ +/** Options for loading Nitro configuration via c12. */ export interface LoadConfigOptions { watch?: boolean; c12?: WatchConfigOptions; @@ -331,32 +983,58 @@ export interface LoadConfigOptions { // Partial types // ------------------------------------------------------------ -// Public assets +/** + * Configuration for a public asset directory served in development and + * bundled in production. + * + * @see https://nitro.build/config#publicassets + * @see https://nitro.build/docs/assets + */ export interface PublicAssetDir { + /** URL prefix under which these assets are served. */ baseURL?: string; + /** Fall through to the next handler when the asset is not found. */ fallthrough?: boolean; + /** `Cache-Control` max-age value in seconds. */ maxAge: number; + /** Filesystem path to the asset directory. */ dir: string; /** - * Pass false to disable ignore patterns when scanning the directory, or - * pass an array of glob patterns to ignore (which will override global - * nitro.ignore patterns). + * Pass `false` to disable ignore patterns when scanning the directory, + * or pass an array of glob patterns to ignore (overrides global + * `nitro.ignore` patterns). */ ignore?: false | string[]; } -// Public assets compression +/** + * Pre-compression options for public assets and prerendered routes. + * + * @see https://nitro.build/config#compresspublicassets + */ export interface CompressOptions { + /** Enable gzip pre-compression. */ gzip?: boolean; + /** Enable brotli pre-compression. */ brotli?: boolean; + /** Enable zstd pre-compression. */ zstd?: boolean; } -// Server assets +/** + * Configuration for a server-side asset directory bundled at build time. + * + * @see https://nitro.build/config#serverassets + * @see https://nitro.build/docs/assets#server-assets + */ export interface ServerAssetDir { + /** Logical name used to access the asset group at runtime. */ baseName: string; + /** Glob pattern to filter files within the directory. */ pattern?: string; + /** Filesystem path to the asset directory. */ dir: string; + /** Glob patterns to ignore when scanning the directory. */ ignore?: string[]; } @@ -365,7 +1043,15 @@ export interface TracingOptions { h3?: boolean; } -// Storage mounts +/** + * Storage mount configuration mapping mount points to driver options. + * + * Keys are storage mount-point paths; values specify the unstorage driver + * and its options. + * + * @see https://nitro.build/config#storage + * @see https://nitro.build/docs/storage + */ type CustomDriverName = string & { _custom?: any }; export interface StorageMounts { [path: string]: { @@ -375,21 +1061,42 @@ export interface StorageMounts { } // Database + +/** Logical database connection name. Defaults to `"default"`. */ export type DatabaseConnectionName = "default" | (string & {}); + +/** + * Database connection configuration specifying a db0 connector and options. + * + * @see https://nitro.build/config#database + * @see https://nitro.build/docs/database + */ export type DatabaseConnectionConfig = { connector: ConnectorName; options?: { [key: string]: any; }; }; + +/** Map of {@link DatabaseConnectionName} to {@link DatabaseConnectionConfig}. */ export type DatabaseConnectionConfigs = Record; // Runtime config +/** Application-specific runtime configuration. */ export interface NitroRuntimeConfigApp { [key: string]: any; } +/** + * Server runtime configuration accessible via `useRuntimeConfig()`. + * + * Values can be overridden at runtime using environment variables with + * the `NITRO_` prefix. An alternative prefix can be configured via + * `nitro.envPrefix` or `NITRO_ENV_PREFIX`. + * + * @see https://nitro.build/config#runtimeconfig + */ export interface NitroRuntimeConfig { nitro?: { envPrefix?: string; diff --git a/src/types/handler.ts b/src/types/handler.ts index 42d9b78dfb..ea7b06e98a 100644 --- a/src/types/handler.ts +++ b/src/types/handler.ts @@ -4,7 +4,12 @@ import type { OperationObject, OpenAPI3, Extensable } from "../types/openapi-ts. type MaybeArray = T | T[]; -/** @experimental */ +/** + * Route-level metadata attached to event handlers. + * + * @experimental + * @see https://nitro.build/docs/routing + */ export interface NitroRouteMeta { openAPI?: OperationObject & { $global?: Pick & Extensable; @@ -13,38 +18,53 @@ export interface NitroRouteMeta { interface NitroHandlerCommon { /** - * HTTP pathname pattern to match + * HTTP pathname pattern to match. * - * Examples: `/test`, `/api/:id`, `/blog/**` + * @example "/test", "/api/:id", "/blog/**" */ route: string; /** - * HTTP method to match + * HTTP method to match. */ method?: HTTPMethod; /** - * Run handler as a middleware before other route handlings + * Run handler as a middleware before other route handlers. */ middleware?: boolean; /** - * Extra Meta + * Route metadata (e.g. OpenAPI operation info). */ meta?: NitroRouteMeta; } +/** + * Handler module format. + * + * - `"web"` — standard Web API handler (default). + * - `"node"` — Node.js-style handler, automatically converted to web-compatible. + */ export type EventHandlerFormat = "web" | "node"; +/** + * Event handler registration for build-time bundling. + * + * Handlers are file references that the bundler imports and transforms. + * For runtime-only handlers in development, use {@link NitroDevEventHandler}. + * + * @see https://nitro.build/config#handlers + * @see https://nitro.build/docs/routing + */ export interface NitroEventHandler extends NitroHandlerCommon { /** - * Use lazy loading to import handler + * Use lazy loading to import handler. */ lazy?: boolean; /** - * Path to event handler + * Path to event handler. */ handler: string; @@ -55,21 +75,43 @@ export interface NitroEventHandler extends NitroHandlerCommon { */ format?: EventHandlerFormat; - /* - * Environments to include and bundle this handler + /** + * Environments to include and bundle this handler. + * + * @example + * ```ts + * env: ["dev", "prod"] + * env: "prerender" + * ``` */ env?: MaybeArray<"dev" | "prod" | "prerender" | PresetName | (string & {})>; } +/** + * Development-only event handler with an inline handler function. + * + * These handlers are available only during `nitro dev` and are not + * included in production builds. + * + * @see https://nitro.build/config#devhandlers + */ export interface NitroDevEventHandler extends NitroHandlerCommon { /** - * Event handler function + * Event handler function. */ handler: HTTPHandler; } type MaybePromise = T | Promise; +/** + * Custom error handler function signature. + * + * Receives the error, the H3 event, and a helper object containing the + * `defaultHandler` for fallback rendering. + * + * @see https://nitro.build/config#errorhandler + */ export type NitroErrorHandler = ( error: HTTPError, event: HTTPEvent, diff --git a/src/types/module.ts b/src/types/module.ts index 265ab43fef..839df6e99a 100644 --- a/src/types/module.ts +++ b/src/types/module.ts @@ -1,7 +1,35 @@ import type { Nitro } from "./nitro.ts"; +/** + * Accepted input formats for Nitro modules. + * + * Can be a module path string, a {@link NitroModule} object, a bare setup + * function, or an object with a `nitro` key containing a {@link NitroModule}. + * + * @see https://nitro.build/config#modules + */ export type NitroModuleInput = string | NitroModule | NitroModule["setup"] | { nitro: NitroModule }; +/** + * A Nitro module that extends behavior during initialization. + * + * Modules receive the {@link Nitro} instance and can register hooks, + * add handlers, modify options, or perform other setup tasks. + * + * @example + * ```ts + * const myModule: NitroModule = { + * name: "my-module", + * setup(nitro) { + * nitro.hooks.hook("compiled", () => { + * console.log("Build complete!"); + * }); + * }, + * }; + * ``` + * + * @see https://nitro.build/config#modules + */ export interface NitroModule { name?: string; setup: (this: void, nitro: Nitro) => void | Promise; diff --git a/src/types/nitro.ts b/src/types/nitro.ts index 98203a46ef..02ebc3d4be 100644 --- a/src/types/nitro.ts +++ b/src/types/nitro.ts @@ -14,12 +14,20 @@ import type { WorkerAddress } from "./runner.ts"; type MaybeArray = T | T[]; +/** Nitro package metadata including version information. */ export interface NitroMeta { version: string; majorVersion: number; - [key: string]: unknown; } +/** + * The core Nitro instance available throughout the build lifecycle. + * + * Provides access to resolved options, hooks, the virtual file system, + * scanned handlers, and utility methods. + * + * @see https://nitro.build/docs/lifecycle + */ export interface Nitro { meta: NitroMeta; options: NitroOptions; @@ -44,6 +52,10 @@ export interface Nitro { _prerenderMeta?: Record; } +/** + * Subset of {@link NitroConfig} that can be updated at runtime via + * `nitro.updateConfig()`. + */ export type NitroDynamicConfig = Pick; export type NitroTypes = { @@ -51,12 +63,24 @@ export type NitroTypes = { tsConfig?: TSConfig; }; +/** + * Metadata about the higher-level framework using Nitro (e.g. Nuxt). + * + * Used by presets and included in build info output. + * + * @see https://nitro.build/config#framework + */ export interface NitroFrameworkInfo { name?: "nitro" | (string & {}); version?: string; } -/** Build info written to `.output/nitro.json` or `.nitro/dev/nitro.json` */ +/** + * Build info written to `.output/nitro.json` (production) or + * `node_modules/.nitro/nitro.dev.json` (development). + * + * Contains preset, framework, version, and command information. + */ export interface NitroBuildInfo { date: string; preset: PresetName; diff --git a/src/types/openapi.ts b/src/types/openapi.ts index b858c24c7b..af868541bb 100644 --- a/src/types/openapi.ts +++ b/src/types/openapi.ts @@ -1,7 +1,7 @@ // import type { ApiReferenceConfiguration as ScalarConfig } from "@scalar/api-reference"; /** - * Swagger UI configuration options + * Swagger UI configuration options. * * @see https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/ */ @@ -32,13 +32,14 @@ export interface SwaggerUIConfig { } /** - * Nitro OpenAPI configuration + * Nitro OpenAPI configuration. * + * @see https://nitro.build/config#openapi * @see https://nitro.build/docs/openapi */ export interface NitroOpenAPIConfig { /** - * OpenAPI meta information + * OpenAPI document metadata. */ meta?: { title?: string; @@ -47,36 +48,46 @@ export interface NitroOpenAPIConfig { }; /** - * OpenAPI json route + * Route for the OpenAPI JSON endpoint. * - * Default is `/_openapi.json` + * @default "/_openapi.json" */ route?: string; /** - * Enable OpenAPI generation for production builds + * Enable OpenAPI generation for production builds. + * + * - `"runtime"` — generate at runtime (allows middleware usage). + * - `"prerender"` — prerender the JSON response at build time (most efficient). + * - `false` — disable in production. + * + * @see https://nitro.build/config#openapi */ production?: false | "runtime" | "prerender"; /** - * UI configurations + * UI configurations for interactive API documentation. */ ui?: { /** - * Scalar UI configuration + * Scalar UI configuration. + * + * Set to `false` to disable. */ scalar?: | false | (Partial & { /** - * Scalar UI route + * Route for Scalar UI. * - * Default is `/_scalar` + * @default "/_scalar" */ route?: string; }); /** - * Swagger UI configuration + * Swagger UI configuration. + * + * Set to `false` to disable. * * @see https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/ */ @@ -84,9 +95,9 @@ export interface NitroOpenAPIConfig { | false | (SwaggerUIConfig & { /** - * Swagger UI route + * Route for Swagger UI. * - * Default is `/_swagger` + * @default "/_swagger" */ route?: string; }); diff --git a/src/types/route-rules.ts b/src/types/route-rules.ts index 0ff0c4edf9..85c7507bc5 100644 --- a/src/types/route-rules.ts +++ b/src/types/route-rules.ts @@ -2,23 +2,145 @@ import type { Middleware, ProxyOptions, BasicAuthOptions } from "h3"; import type { ExcludeFunctions, IntRange } from "./_utils.ts"; import type { CachedEventHandlerOptions } from "./runtime/index.ts"; +/** Valid HTTP status code range (100–599). */ export type HTTPstatus = IntRange<100, 600>; +/** + * Route rule options that can be applied to matching route patterns. + * + * Rules are matched against the request path (without query string or + * `app.baseURL`) using rou3 pattern matching. When multiple patterns match, + * their options are deep-merged with more-specific patterns taking precedence. + * + * Shortcut fields (`cors`, `swr`, `static`) are normalized into their + * canonical forms in {@link NitroRouteRules} at runtime. + * + * @see https://nitro.build/docs/routing#route-rules + */ export interface NitroRouteConfig { + /** + * Server-side response caching options. + * + * When set to an options object, matching handlers are wrapped with + * `defineCachedHandler`. Set to `false` to disable caching. + * + * @see https://nitro.build/docs/cache + */ cache?: ExcludeFunctions | false; + + /** + * Response headers to set for matching routes. + * + * @example + * ```ts + * headers: { 'cache-control': 's-maxage=60' } + * ``` + * + * @see https://nitro.build/docs/routing#headers + */ headers?: Record; + + /** + * Server-side redirect for matching routes. + * + * A plain string defaults to status `307`. Use an object to specify a + * custom status code. When the rule key ends with `/**` and `to` also + * ends with `/**`, the matched path tail is appended to the destination. + * + * @example + * ```ts + * redirect: '/new-page' + * redirect: { to: '/new-page', status: 301 } + * ``` + * + * @see https://nitro.build/docs/routing#redirect + */ redirect?: string | { to: string; status?: HTTPstatus }; + + /** + * Add this route to the prerender queue at build time. + * + * Only exact paths are collected; wildcard rules apply at runtime but are + * not auto-added to the queue. Set to `false` to explicitly exclude a + * route from prerendering. + * + * @see https://nitro.build/docs/routing#prerender + */ prerender?: boolean; + + /** + * Proxy matching requests to another origin or internal path. + * + * A plain string specifies the destination. Use an object for additional + * H3 {@link ProxyOptions}. Wildcard `/**` tail behavior works the same + * as {@link NitroRouteConfig.redirect | redirect}. + * + * @see https://nitro.build/docs/routing#proxy + */ proxy?: string | ({ to: string } & ProxyOptions); + + /** + * Incremental Static Regeneration on supported platforms. + * + * - `number` — revalidation time in seconds. + * - `true` — never expires until the next deployment. + * - `false` — disable ISR for this route. + * + * Only handled by presets with native support (e.g. Vercel, Netlify). + * Ignored on platforms without ISR support. + * + * @see https://nitro.build/docs/routing#isr-vercel + */ isr?: number /* expiration */ | boolean | VercelISRConfig; + + /** + * Protect matching routes with HTTP Basic Authentication. + * + * Set to `false` to disable auth inherited from a less-specific pattern. + * + * @see https://nitro.build/docs/routing#basic-auth + */ basicAuth?: Pick | false; // Shortcuts + + /** + * Shortcut to add permissive CORS headers (`access-control-allow-origin: *`, + * `access-control-allow-methods: *`, `access-control-allow-headers: *`, + * `access-control-max-age: 0`). Override individual headers via + * {@link NitroRouteConfig.headers | headers}. + * + * @see https://nitro.build/docs/routing#cors + */ cors?: boolean; + + /** + * Shortcut for `cache: { swr: true, maxAge?: number }`. + * + * - `true` — enable SWR with no explicit `maxAge`. + * - `number` — enable SWR with the given `maxAge` in seconds. + * + * Prefer {@link NitroRouteConfig.isr | isr} on platforms with native support. + * + * @see https://nitro.build/docs/routing#caching-swr-static + */ swr?: boolean | number; + + /** + * Legacy caching shortcut. Prefer {@link NitroRouteConfig.isr | isr}. + * + * @see https://nitro.build/docs/routing#caching-swr-static + */ static?: boolean | number; } +/** + * Normalized route rules used at runtime after shortcut resolution. + * + * - `redirect` is always an object with a required `status`. + * - `proxy` is always an object with `to` plus any {@link ProxyOptions}. + * - Shortcut fields (`cors`, `swr`, `static`) are omitted after normalization. + */ export interface NitroRouteRules extends Omit< NitroRouteConfig, "redirect" | "cors" | "swr" | "static" diff --git a/src/types/runtime/cache.ts b/src/types/runtime/cache.ts index ee6459c007..4383995445 100644 --- a/src/types/runtime/cache.ts +++ b/src/types/runtime/cache.ts @@ -2,6 +2,11 @@ import type { HTTPEvent } from "h3"; export type { CacheEntry, CacheOptions, ResponseCacheEntry } from "ocache"; +/** + * Options for `defineCachedHandler`. + * + * @see https://nitro.build/docs/cache + */ export interface CachedEventHandlerOptions extends Omit< import("ocache").CachedEventHandlerOptions, "toResponse" | "createResponse" | "handleCacheHeaders" diff --git a/src/types/runtime/nitro.ts b/src/types/runtime/nitro.ts index 963f13d11c..c891816eaa 100644 --- a/src/types/runtime/nitro.ts +++ b/src/types/runtime/nitro.ts @@ -2,6 +2,11 @@ import type { H3Core, HTTPEvent } from "h3"; import type { HookableCore } from "hookable"; import type { ServerRequest } from "srvx"; +/** + * The runtime Nitro application instance accessible via `useNitroApp()`. + * + * @see https://nitro.build/docs/plugins + */ export interface NitroApp { fetch: (req: Request) => Response | Promise; h3?: H3Core; @@ -9,6 +14,14 @@ export interface NitroApp { captureError?: CaptureError; } +/** + * A Nitro runtime plugin function. + * + * Receives the {@link NitroApp} instance (with `hooks` guaranteed to exist) + * and can register runtime hooks or modify the app. + * + * @see https://nitro.build/docs/plugins + */ export interface NitroAppPlugin { ( nitro: NitroApp & { @@ -38,13 +51,21 @@ export interface RenderContext { response?: Partial; } +/** Context provided when an error is captured at runtime. */ export interface CapturedErrorContext { event?: HTTPEvent; tags?: string[]; } +/** Error capture callback used by `nitroApp.captureError`. */ export type CaptureError = (error: Error, context: CapturedErrorContext) => void; +/** + * Runtime hooks available in Nitro plugins. + * + * @see https://nitro.build/docs/plugins + * @see https://nitro.build/docs/lifecycle + */ export interface NitroRuntimeHooks { close: () => void; error: CaptureError;