import { NestedHooks } from "../_libs/hookable.mjs"; import { C12InputConfig, ConfigWatcher, DotenvOptions, ResolvedConfig, WatchConfigOptions } from "../_libs/c12+jiti+giget.mjs"; import { ChokidarOptions } from "../_libs/readdirp+chokidar.mjs"; import { CompatibilityDateSpec, CompatibilityDates, DateString } from "../_libs/compatx.mjs"; import { ProxyServerOptions } from "../_libs/httpxy.mjs"; import { RawConfig } from "../_libs/undici+jsonc-parser.mjs"; import { OutputBundleConfig } from "../_libs/common.mjs"; import { DeployOptions } from "../_chunks/nitro.mjs"; import { TSConfig } from "../_libs/pkg-types.mjs"; import { ExternalsTraceOptions } from "../_libs/nf3.mjs"; import { UnwasmPluginOptions } from "../_libs/unwasm.mjs"; import { OpenAPIV3_1 } from "../_libs/openapi-types.mjs"; import { TransformOptions } from "../_libs/oxbox.mjs"; import { ProviderName } from "../_libs/std-env.mjs"; import { version } from "#nitro/meta"; import { MatchedRouteRule, MatchedRouteRules, NormalizedRouteRules, NormalizedRouteRules as NormalizedRouteRules$1, ProxyRuleOptions, RedirectRuleOptions, ResolvedRouteRules, RouteRuleConfig, RouteRuleConfig as RouteRuleConfig$1, RouteRules } from "h3/rules"; import { H3Core, HTTPError, HTTPEvent, HTTPHandler, HTTPMethod } from "h3"; import { RouterContext } from "rou3"; import { CompileRouterToStringOptions } from "rou3/compiler"; import { EnvRunner, EnvRunnerData, EnvRunnerPluginOption, FetchHandler, RunnerMessageListener, RunnerName, RunnerRPCHooks, RunnerReloadOptions, UpgradeHandler, WorkerAddress, WorkerHooks } from "env-runner"; import { ServerOptions, ServerRequest, ServerRequest as ServerRequest$1, ServerRequestContext, ServerRuntimeContext } from "srvx"; import { Nitro as Nitro$1 } from "nitro/types"; // @ts-ignore optional dependency import { InputOptions, MinifyOptions, OutputOptions, RolldownPluginOption } from "rolldown"; // @ts-ignore optional dependency import { InputOptions as InputOptions$1, InputPluginOption, OutputOptions as OutputOptions$1 } from "rollup"; import { CacheEntry, CacheOptions as CacheOptions$1, CachedEventHandlerOptions as CachedEventHandlerOptions$1, CachedFunction, HTTPEvent as HTTPEvent$1, MemoryStorageOptions, ResponseCacheEntry } from "ocache"; // @ts-ignore optional dependency import { ConnectorName, ConnectorOptions } from "db0"; // @ts-ignore optional dependency import { ExecutionContext, ForwardableEmailMessage, MessageBatch, ScheduledController, TraceItem } from "@cloudflare/workers-types"; // @ts-ignore optional dependency import { DurableObject } from "cloudflare:workers"; // @ts-ignore optional dependency import { MessageMetadata, send } from "@vercel/queue"; // @ts-ignore optional dependency import { BuiltinDriverName, BuiltinDriverOptions } from "unstorage"; // @ts-ignore optional dependency import { Configuration } from "@rspack/core"; export interface PublicAsset { type: string; etag: string; mtime: string; path: string; size: number; encoding?: string; data?: string; } export interface AssetMeta { type?: string; etag?: string; mtime?: string; } /** * Options for `defineCachedFunction`. * * @see https://nitro.build/docs/cache */ export type CachedFunctionOptions = CacheOptions$1; /** @deprecated Use {@link CachedFunctionOptions}. */ export type CacheOptions = CachedFunctionOptions; /** * Options for `defineCachedHandler`. * * @see https://nitro.build/docs/cache */ export interface CachedHandlerOptions extends Omit, "toResponse" | "createResponse" | "handleCacheHeaders"> {} /** @deprecated Use {@link CachedHandlerOptions}. */ export type CachedEventHandlerOptions = CachedHandlerOptions; type HookCallback = (...args: any) => Promise | void; type HookKeys = keyof T & string; type InferCallback = HooksT[NameT] extends HookCallback ? HooksT[NameT] : never; type DeprecatedHook = { message?: string; to: HookKeys; }; type HookEvent = { [NameT in keyof HooksT]: { name: NameT; args: Parameters>; context: Record; }; }[keyof HooksT]; /** * Minimal hook system (`HookableCore` from `hookable`). * * @see https://github.com/unjs/hookable */ interface HookableCore> { hook>(name: NameT, fn: InferCallback): () => void; removeHook>(name: NameT, fn: InferCallback): void; callHook>(name: NameT, ...args: Parameters>): Promise | void; } /** * Hook system (`Hookable` from `hookable`). * * @see https://github.com/unjs/hookable */ interface Hookable> extends HookableCore { hook>(name: NameT, fn: InferCallback, options?: { allowDeprecated?: boolean; }): () => void; hookOnce>(name: NameT, fn: InferCallback): () => void; clearHook>(name: NameT): void; deprecateHook>(name: NameT, deprecated: HookKeys | DeprecatedHook): void; deprecateHooks(deprecatedHooks: Partial, DeprecatedHook>>): void; addHooks(configHooks: NestedHooks): () => void; removeHooks(configHooks: NestedHooks): void; removeAllHooks(): void; callHookParallel>(name: NameT, ...args: Parameters>): Promise | void; callHookWith, CallFunction extends (hooks: HookCallback[], args: Parameters>, name: NameT) => any>(caller: CallFunction, name: NameT, args: Parameters>): ReturnType; beforeEach(fn: (event: HookEvent) => void): () => void; afterEach(fn: (event: HookEvent) => void): () => void; } /** * The runtime Nitro application instance accessible via `useNitroApp()`. * * @see https://nitro.build/docs/plugins */ export interface NitroApp { fetch: (req: Request) => Response | Promise; h3?: H3Core; hooks?: HookableCore; captureError?: CaptureError; /** * Set while async plugins are still initializing and resolves once all * plugins have finished. `undefined` when the app is ready. * * Requests to `fetch` are held until then automatically. */ ready?: Promise; } /** * A Nitro runtime plugin function. * * Receives the {@link NitroApp} instance (with `hooks` guaranteed to exist) * and can register runtime hooks or modify the app. * * A plugin can be async: the plugins after it run once it resolves, and * requests are held until all plugins have finished. * * @see https://nitro.build/docs/plugins */ export interface NitroAppPlugin { (nitro: NitroApp & { hooks: NonNullable; }): void | Promise; } export interface NitroAsyncContext { request: ServerRequest$1; } /** 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; request: (event: HTTPEvent) => void | Promise; response: (res: Response, event: HTTPEvent) => void | Promise; } type MaybePromise$3 = T | Promise; /** @experimental */ export interface TaskContext {} /** @experimental */ export interface TaskPayload { [key: string]: unknown; } /** @experimental */ export interface TaskMeta { name?: string; description?: string; } /** @experimental */ export interface TaskEvent { name: string; payload: TaskPayload; context: TaskContext; } /** @experimental */ export interface TaskResult { result?: RT; } /** @experimental */ export interface Task { meta?: TaskMeta; run(event: TaskEvent): MaybePromise$3>; } /** @experimental */ export interface TaskRunnerOptions { cwd?: string; buildDir?: string; /** * Socket inactivity timeout in milliseconds for requests to the dev server. * * `listTasks()` defaults to 30 seconds, since the dev server answers it * immediately. `runTask()` has no default: the socket stays idle for as long * as the task runs, so a default would cap the task's own duration. */ timeout?: number; } /** * Log level (`LogLevel` from `consola`). * * @see https://github.com/unjs/consola#log-level */ type LogLevel = 0 | 1 | 2 | 3 | 4 | 5 | (number & {}); type LogType = "silent" | "fatal" | "error" | "warn" | "log" | "info" | "success" | "fail" | "ready" | "start" | "box" | "debug" | "trace" | "verbose"; type LogFn = { (message: any, ...args: any[]): void; raw: (...args: any[]) => void; }; /** * Logger (`ConsolaInstance` from `consola`). * * @see https://github.com/unjs/consola */ type ConsolaInstance = Record & { level: LogLevel; withTag(tag: string): ConsolaInstance; }; type AmplifyImageSettings = { /** Array of supported image widths */ sizes: number[]; /** * Array of allowed external domains that can use Image Optimization. * Leave empty for only allowing the deployment domain to use Image Optimization. */ domains: string[]; /** * Array of allowed external patterns that can use Image Optimization. * Similar to `domains` but provides more control with RegExp. */ remotePatterns: { /** The protocol of the allowed remote pattern. Can be `http` or `https`. */ protocol?: "http" | "https"; /** * The hostname of the allowed remote pattern. * Can be literal or wildcard. Single `*` matches a single subdomain. * Double `**` matches any number of subdomains. * We will disallow blanket wildcards of `**` with nothing else. */ hostname: string; /** The port of the allowed remote pattern. */ port?: string; /** The pathname of the allowed remote pattern. */ pathname?: string; }[]; /** Array of allowed output image formats. */ formats: ("image/avif" | "image/webp" | "image/gif" | "image/png" | "image/jpeg")[]; /** Cache duration (in seconds) for the optimized images. */ minimumCacheTTL: number; /** Allow SVG input image URLs. This is disabled by default for security purposes. */ dangerouslyAllowSVG: boolean; }; interface AwsAmplifyOptions { catchAllStaticFallback?: boolean; imageOptimization?: { path?: string; cacheControl?: string; }; imageSettings?: AmplifyImageSettings; /** * The Node.js runtime of the compute resource. * * @default "nodejs22.x" */ runtime?: "nodejs20.x" | "nodejs22.x" | "nodejs24.x"; } interface AwsLambdaOptions { streaming?: boolean; } interface AzureOptions { /** * Azure Functions Node.js programming model of the generated server function. * * - `4` (default): Registers the function with `app.http()` from `@azure/functions` (must be installed in your project). * - `3`: Legacy model using a `function.json` file. * * @see https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node */ functionsVersion?: 3 | 4; config?: { platform?: { apiRuntime?: string; [key: string]: unknown; }; navigationFallback?: { rewrite?: string; [key: string]: unknown; }; [key: string]: unknown; }; } declare const invalidValue: unique symbol; /** Uninhabited, so a rejected value reports `Message` in its type error. */ type Invalid = Message & { readonly [invalidValue]: never; }; type LibOptionName = "lib" | `${string}Lib`; type LibOption = null | Invalid<"Library imports are not JSON-serializable; nitro injects them for installed driver dependencies (set `null` to opt out)">; type JsonPrimitive = string | number | boolean | null | undefined; type NonSerializable = Function | symbol | bigint | RegExp | Date | Error | Promise | Map | Set | WeakMap | WeakSet | ArrayBufferLike | ArrayBufferView; type Prev = [never, 0, 1, 2, 3, 4, 5, 6]; type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue; }; /** * The subset of `T` that survives `JSON.stringify`, with anything else mapped to {@link Invalid}. * * `Depth` bounds instantiation for large and self-referential option types; deeper values are * passed through unchecked. */ type Serializable = [Depth] extends [never] ? T : T extends JsonPrimitive ? T : T extends NonSerializable ? Invalid<"nitro serializes options with JSON.stringify; this value would not survive"> : T extends readonly (infer U)[] ? Array> : T extends object ? { [K in keyof T]: Serializable; } : T; /** Driver or connector options, as serialized into the build output. */ type SerializableOptions = { [K in keyof T]: K extends LibOptionName ? LibOption : Serializable; }; /** * `T` from an optional dependency, or `Fallback` when it is not installed. * * Built types import optional dependencies with `@ts-ignore` (see `build.config.ts`), so a missing * one resolves to an error type (`any`), which the tuple check detects without collapsing to `any`. */ type OptionalDepType = [0] extends [1 & T] ? Fallback : T; type WranglerConfig = Partial; /** * https://developers.cloudflare.com/pages/platform/functions/routing/#functions-invocation-routes */ interface CloudflarePagesRoutes { /** Defines the version of the schema. Currently there is only one version of the schema (version 1), however, we may add more in the future and aim to be backwards compatible. */ version?: 1; /** Defines routes that will be invoked by Functions. Accepts wildcard behavior. */ include?: string[]; /** Defines routes that will not be invoked by Functions. Accepts wildcard behavior. `exclude` always take priority over `include`. */ exclude?: string[]; } interface CloudflareOptions { /** * Configuration for the Cloudflare deployments and local dev. * */ wrangler?: WranglerConfig; /** * Wrangler environment to select when loading the config. */ wranglerEnv?: string; /** * Automatically generate `.wrangler/deploy/config.json`. * * Enabled by default. * * More info: https://developers.cloudflare.com/workers/wrangler/configuration#generated-wrangler-configuration */ deployConfig?: boolean; /** * Native Node.js compatibility support. * * Enabled by default. * * If this option disabled, pure unenv polyfills will be used instead. * */ nodeCompat?: boolean; pages?: { /** * Nitro will automatically generate a `_routes.json` that controls which files get served statically and * which get served by the Worker. Using this config will override the automatic `_routes.json`. Or, if the * `merge` options is set, it will merge the user-set routes with the auto-generated ones, giving priority * to the user routes. * * @see https://developers.cloudflare.com/pages/platform/functions/routing/#functions-invocation-routes * * There are a maximum of 100 rules, and you must have at least one include rule. Wildcards are accepted. * * If any fields are unset, they default to: * * ```json * { * "version": 1, * "include": ["/*"], * "exclude": [] * } * ``` */ routes?: CloudflarePagesRoutes; /** * If set to `false`, nitro will disable the automatically generated `_routes.json` and instead use the user-set only ones. * * @default true */ defaultRoutes?: boolean; }; } declare module "nitro/types" { interface NitroRuntimeHooks { "cloudflare:scheduled": (_: { controller: ScheduledController$1; env: unknown; context: ExecutionContext$1; }) => void; "cloudflare:email": (_: { message: ForwardableEmailMessage$1; env: unknown; context: ExecutionContext$1; }) => void; "cloudflare:queue": (_: { batch: MessageBatch$1; env: unknown; context: ExecutionContext$1; }) => void; "cloudflare:tail": (_: { traces: TraceItem$1[]; env: unknown; context: ExecutionContext$1; }) => void; "cloudflare:trace": (_: { traces: TraceItem$1[]; env: unknown; context: ExecutionContext$1; }) => void; "cloudflare:durable:init": (durable: DurableObject$1, _: { state: DurableObjectState; env: unknown; }) => void; "cloudflare:durable:alarm": (durable: DurableObject$1) => void; } } type ExecutionContext$1 = OptionalDepType; type ScheduledController$1 = OptionalDepType; type ForwardableEmailMessage$1 = OptionalDepType; type MessageBatch$1 = OptionalDepType; type TraceItem$1 = OptionalDepType; type DurableObject$1 = OptionalDepType; type DurableObjectState = OptionalDepType[0], DurableObjectStateFallback>; interface ExecutionContextFallback { waitUntil(promise: Promise): void; passThroughOnException(): void; readonly props: unknown; } interface ScheduledControllerFallback { readonly scheduledTime: number; readonly cron: string; noRetry(): void; } interface ForwardableEmailMessageFallback { readonly from: string; readonly to: string; readonly raw: ReadableStream; readonly headers: Headers; readonly rawSize: number; setReject(reason: string): void; forward(rcptTo: string, headers?: Headers): Promise; reply(message: unknown): Promise; } interface MessageBatchFallback { readonly queue: string; readonly messages: readonly { readonly id: string; readonly timestamp: Date; readonly body: Body; readonly attempts: number; retry(options?: { delaySeconds?: number; }): void; ack(): void; }[]; retryAll(options?: { delaySeconds?: number; }): void; ackAll(): void; } interface TraceItemFallback { readonly event: unknown; readonly eventTimestamp: number | null; readonly logs: { readonly timestamp: number; readonly level: string; readonly message: any; }[]; readonly exceptions: { readonly timestamp: number; readonly message: string; readonly name: string; readonly stack?: string; }[]; readonly scriptName: string | null; readonly entrypoint?: string; readonly outcome: string; readonly truncated: boolean; readonly cpuTime: number; readonly wallTime: number; } type DurableObjectFallback = object & { alarm?(alarmInfo?: { retryCount: number; isRetry: boolean; }): void | Promise; }; interface DurableObjectStateFallback { readonly id: { toString(): string; equals(other: any): boolean; readonly name?: string; }; readonly storage: any; waitUntil(promise: Promise): void; blockConcurrencyWhile(callback: () => Promise): Promise; acceptWebSocket(ws: WebSocket, tags?: string[]): void; getWebSockets(tag?: string): WebSocket[]; } type AppHostingOutputBundleConfig = OutputBundleConfig; interface FirebaseOptions { appHosting?: Partial; } interface IisOptions { /** Merge with existing IIS `web.config` instead of replacing. */ mergeConfig?: boolean; /** Override existing IIS `web.config` entirely. */ overrideConfig?: boolean; } interface NetlifyOptions { config?: NetlifyConfigJson; } interface NetlifyConfigJson { edge_functions?: NetlifyEdgeFunctionDeclaration[]; functions?: NetlifyFunctionsConfig | NetlifyFunctionsConfigByPattern; headers?: NetlifyHeaderRule[]; images?: NetlifyImagesConfig; redirects?: NetlifyRedirectRule[]; "redirects!"?: NetlifyRedirectRule[]; } interface NetlifyEdgeFunctionDeclaration { function: string; path?: string; pattern?: string; excludedPath?: string; excludedPattern?: string; cache?: string; [key: string]: unknown; } interface NetlifyFunctionsConfig extends NetlifyFunctionInlineConfig { directory?: string; } type NetlifyFunctionsConfigByPattern = Record; interface NetlifyFunctionInlineConfig { included_files?: string[]; [key: string]: unknown; } interface NetlifyHeaderRule { for: string; values: Record; [key: string]: unknown; } interface NetlifyImagesConfig { remote_images?: string[]; [key: string]: unknown; } interface NetlifyRedirectRule { from: string; to: string; status?: number; force?: boolean; conditions?: Record; query?: Record; [key: string]: unknown; } /** * Vercel Build Output Configuration * @see https://vercel.com/docs/build-output-api/v3 */ interface VercelBuildConfigV3 { version: 3; routes?: ({ src: string; dest?: string; headers?: Record; continue?: boolean; status?: number; } | { handle: string; })[]; images?: { sizes: number[]; domains: string[]; remotePatterns?: { protocol?: "http" | "https"; hostname: string; port?: string; pathname?: string; }[]; minimumCacheTTL?: number; formats?: ("image/avif" | "image/webp")[]; dangerouslyAllowSVG?: boolean; contentSecurityPolicy?: string; }; wildcard?: Array<{ domain: string; value: string; }>; overrides?: Record; cache?: string[]; bypassToken?: string; framework?: { version: string; }; crons?: { path: string; schedule: string; }[]; /** Vercel Schedules, keyed by schedule name. */ schedules?: Record; } /** * Vercel Schedules definition in the Build Output API, keyed by its name in `schedules` * @see https://vercel.com/docs/schedules */ type VercelSchedule = { /** Cron expression. */ schedule: string; /** IANA timezone the cron expression is evaluated in. Defaults to UTC. */ timezone?: string; /** Maximum random delay in minutes, from 1 to 15. */ jitter?: number; } & ({ function: string; } | { path: string; requestMethod?: "GET" | "POST"; } | { topic: string; }); /** * https://vercel.com/docs/build-output-api/primitives#serverless-function-configuration * https://vercel.com/docs/build-output-api/primitives#node.js-config */ interface VercelServerlessFunctionConfig { /** * Amount of memory (RAM in MB) that will be allocated to the Serverless Function. */ memory?: number; /** * Specifies the instruction set "architecture" the Vercel Function supports. * * Either `x86_64` or `arm64`. The default value is `x86_64` */ architecture?: "x86_64" | "arm64"; /** * Maximum execution duration (in seconds) that will be allowed for the Serverless Function. `max` automatically sets the duration to the maximum allowed value. */ maxDuration?: number | "max"; /** * Map of additional environment variables that will be available to the Vercel Function, * in addition to the env vars specified in the Project Settings. */ environment?: Record; /** * List of Vercel Regions where the Vercel Function will be deployed to. */ regions?: string[]; /** * True if a custom runtime has support for Lambda runtime wrappers. */ supportsWrapper?: boolean; /** * When true, the Serverless Function will stream the response to the client. */ supportsResponseStreaming?: boolean; /** * Enables source map generation. */ shouldAddSourcemapSupport?: boolean; /** * The runtime to use. Defaults to `engines` in `package.json`, then `bunVersion` in `vercel.json`, then the runtime used to build. */ runtime?: "nodejs22.x" | "nodejs24.x" | "nodejs26.x" | "bun1.x" | "bun1.4.x" | (string & {}); /** * Experimental trigger configuration (e.g., Vercel Queues). */ experimentalTriggers?: VercelFunctionTrigger[]; [key: string]: unknown; } type VercelFunctionTrigger = { type: "queue/v2beta"; topic: string; retryAfterSeconds?: number; initialDelaySeconds?: number; consumer?: string; } | { type: "schedule/v1beta"; }; interface VercelOptions { config?: VercelBuildConfigV3; /** * If you have enabled skew protection in the Vercel dashboard, it will * be enabled by default. * * You can disable the Nitro integration by setting this option to `false`. */ skewProtection?: boolean; /** * Emit content-addressed build assets as [immutable static files](https://vercel.com/docs/skew-protection). * * Immutable assets are served from the reserved `/_vercel/immutable/` base * (without the deployment-scoped `?dpl` query), so they can be shared across * deployments to improve cross-deployment caching. Nitro also writes an * `immutable.json` manifest listing each emitted immutable file. * * Opt in by setting this to `true` or the `NITRO_VERCEL_IMMUTABLE_STATIC_FILES_ENABLED` * environment variable. When building on Vercel, immutable output is only * produced if the deployment supports it (`VERCEL_IMMUTABLE_STATIC_FILES_ENABLED`); * otherwise it is skipped with a warning. * * @default false */ immutableStaticFiles?: boolean; functions?: VercelServerlessFunctionConfig; /** * Handler format to use for Vercel Serverless Functions. * * Using `node` format enables compatibility with Node.js specific APIs in your Nitro application (e.g., `req.runtime.node`). * * Possible values are: `web` (default) and `node`. */ entryFormat?: "web" | "node"; /** * The route path for the Vercel cron handler endpoint. * * When `experimental.tasks` and `scheduledTasks` are configured, * Nitro registers a cron handler at this path that Vercel invokes * on each scheduled cron trigger. * * @default "/_vercel/cron" * @see https://vercel.com/docs/cron-jobs */ cronHandlerRoute?: string; /** * Run [`scheduledTasks`](https://nitro.build/docs/tasks#scheduled-tasks) with Vercel Schedules * instead of Vercel Cron Jobs. Nitro emits one schedule per task in the Build Output API. * * - `"private"`: every schedule targets a private function that runs the task. Only Vercel * Schedules can invoke it, so there is no public cron endpoint and no `CRON_SECRET` is needed. * - `"public"`: every schedule targets the public cron handler route * ({@link VercelOptions.cronHandlerRoute}), which keeps working for direct requests * exactly like with Cron Jobs. * * Under `vercel dev`, the local Schedules broker runs scheduled tasks instead of the * in-process scheduler. * * Defaults to the `NITRO_VERCEL_SCHEDULES` environment variable (`private` or `public`). * * @experimental Vercel Schedules is in beta. * @default false */ schedules?: "private" | "public" | false; /** * Vercel Queues configuration. * * Messages are delivered via the `vercel:queue` runtime hook. * * @example * ```ts * // nitro.config.ts * import { defineConfig } from "nitro"; * * export default defineConfig({ * vercel: { * queues: { * triggers: [{ topic: "orders" }], * }, * }, * }); * ``` * * ```ts * // server/plugins/queues.ts * import { definePlugin } from "nitro"; * * export default definePlugin((nitro) => { * nitro.hooks.hook("vercel:queue", ({ message, metadata }) => { * console.log(`Received message on ${metadata.topicName}:`, message); * }); * }); * ``` * * @see https://vercel.com/docs/queues */ queues?: { /** * Route path for the queue consumer handler. * @default "/_vercel/queues/consumer" */ handlerRoute?: string; /** Queue topic triggers to subscribe to. */ triggers: Array<{ topic: string; retryAfterSeconds?: number; initialDelaySeconds?: number; }>; }; /** * Per-route function configuration overrides. * * Keys are route patterns (e.g., `/api/queues/*`, `/api/slow-routes/**`). * Values are partial {@link VercelServerlessFunctionConfig} objects. * * @example * ```ts * functionRules: { * '/api/my-slow-routes/**': { maxDuration: 3600 }, * '/api/queues/fulfill-order': { * experimentalTriggers: [{ type: 'queue/v2beta', topic: 'orders' }], * }, * } * ``` */ functionRules?: Record; } declare module "nitro/types" { interface NitroRuntimeHooks { "vercel:queue": (_: { message: unknown; metadata: OptionalDepType; send: OptionalDepType; }) => void; } } interface VercelQueueMessageMetadata { messageId: string; deliveryCount: number; createdAt: Date; expiresAt: Date; topicName: string; consumerGroup: string; region: string; } type VercelQueueSend = (topicName: string, payload: T, options?: { idempotencyKey?: string; retentionSeconds?: number; delaySeconds?: number; headers?: Record; region?: string; [key: string]: unknown; }) => Promise<{ messageId: string | null; }>; interface ZephyrOptions { /** * Deploy to Zephyr during `nitro build` when using the `zephyr` preset. * * @default false */ deployOnBuild?: boolean; } interface PresetOptions { awsAmplify?: AwsAmplifyOptions; awsLambda?: AwsLambdaOptions; azure?: AzureOptions; cloudflare?: CloudflareOptions; firebase?: FirebaseOptions; iis?: IisOptions; netlify?: NetlifyOptions; vercel?: VercelOptions; zephyr?: ZephyrOptions; } type PresetName = "alwaysdata" | "aws-amplify" | "aws-lambda" | "azure-swa" | "base-worker" | "bun" | "cleavr" | "cloudflare-dev" | "cloudflare-durable" | "cloudflare-module" | "cloudflare-pages" | "cloudflare-pages-static" | "deno" | "deno-server" | "digital-ocean" | "edgeone" | "edgeone-pages" | "firebase-app-hosting" | "flight-control" | "genezio" | "github-pages" | "gitlab-pages" | "heroku" | "iis-handler" | "iis-node" | "koyeb" | "netlify" | "netlify-edge" | "netlify-static" | "nitro-dev" | "nitro-prerender" | "nitro-serve" | "node" | "node-cluster" | "node-middleware" | "node-server" | "platform-sh" | "render-com" | "standard" | "static" | "stormkit" | "upsun" | "vercel" | "vercel-dev" | "vercel-static" | "zeabur" | "zeabur-static" | "zephyr" | "zerops" | "zerops-static"; type PresetNameInput = "alwaysdata" | "aws-amplify" | "awsAmplify" | "aws_amplify" | "aws-lambda" | "awsLambda" | "aws_lambda" | "azure-swa" | "azureSwa" | "azure_swa" | "base-worker" | "baseWorker" | "base_worker" | "bun" | "cleavr" | "cloudflare-dev" | "cloudflareDev" | "cloudflare_dev" | "cloudflare-durable" | "cloudflareDurable" | "cloudflare_durable" | "cloudflare-module" | "cloudflareModule" | "cloudflare_module" | "cloudflare-pages" | "cloudflarePages" | "cloudflare_pages" | "cloudflare-pages-static" | "cloudflarePagesStatic" | "cloudflare_pages_static" | "deno" | "deno-server" | "denoServer" | "deno_server" | "digital-ocean" | "digitalOcean" | "digital_ocean" | "edgeone" | "edgeone-pages" | "edgeonePages" | "edgeone_pages" | "firebase-app-hosting" | "firebaseAppHosting" | "firebase_app_hosting" | "flight-control" | "flightControl" | "flight_control" | "genezio" | "github-pages" | "githubPages" | "github_pages" | "gitlab-pages" | "gitlabPages" | "gitlab_pages" | "heroku" | "iis-handler" | "iisHandler" | "iis_handler" | "iis-node" | "iisNode" | "iis_node" | "koyeb" | "netlify" | "netlify-edge" | "netlifyEdge" | "netlify_edge" | "netlify-static" | "netlifyStatic" | "netlify_static" | "nitro-dev" | "nitroDev" | "nitro_dev" | "nitro-prerender" | "nitroPrerender" | "nitro_prerender" | "nitro-serve" | "nitroServe" | "nitro_serve" | "node" | "node-cluster" | "nodeCluster" | "node_cluster" | "node-middleware" | "nodeMiddleware" | "node_middleware" | "node-server" | "nodeServer" | "node_server" | "platform-sh" | "platformSh" | "platform_sh" | "render-com" | "renderCom" | "render_com" | "standard" | "static" | "stormkit" | "upsun" | "vercel" | "vercel-dev" | "vercelDev" | "vercel_dev" | "vercel-static" | "vercelStatic" | "vercel_static" | "zeabur" | "zeabur-static" | "zeaburStatic" | "zeabur_static" | "zephyr" | "zerops" | "zerops-static" | "zeropsStatic" | "zerops_static" | (string & {}); interface Extensable { [key: `x-${string}`]: any; } type OpenAPI3 = OpenAPIV3_1.Document & Extensable; type OperationObject = OpenAPIV3_1.OperationObject; type MaybeArray$3 = T | T[]; /** * Route-level metadata attached to event handlers. * * @experimental * @see https://nitro.build/docs/routing */ export interface NitroRouteMeta { openAPI?: OperationObject & { $global?: Pick & Extensable; }; } interface NitroHandlerCommon { /** * HTTP pathname pattern to match. * * @example "/test", "/api/:id", "/blog/**" */ route: string; /** * HTTP method to match. */ method?: HTTPMethod; /** * Run handler as a middleware before other route handlers. */ middleware?: boolean; /** * 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/routing#handlers * @see https://nitro.build/docs/routing */ export interface NitroEventHandler extends NitroHandlerCommon { /** * Use lazy loading to import handler. */ lazy?: boolean; /** * Path to event handler. */ handler: string; /** * Event handler type. * * Default is `"web"`. If set to `"node"`, the handler will be converted into a web compatible handler. */ format?: EventHandlerFormat; /** * Environments to include and bundle this handler. * * @example * ```ts * env: ["dev", "prod"] * env: "prerender" * ``` */ env?: MaybeArray$3<"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/routing#devhandlers */ export interface NitroDevEventHandler extends NitroHandlerCommon { /** * Event handler function. */ handler: HTTPHandler; } type MaybePromise$2 = 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/routing#errorhandler */ export type NitroErrorHandler = (error: HTTPError, event: HTTPEvent, _: { defaultHandler: (error: HTTPError, event: HTTPEvent, opts?: { silent?: boolean; json?: boolean; }) => MaybePromise$2<{ status?: number; statusText?: string; headers?: HeadersInit; body?: string | Record; }>; }) => MaybePromise$2; export interface PrerenderRoute { route: string; contents?: string; data?: ArrayBuffer; fileName?: string; error?: Partial; generateTimeMS?: number; skip?: boolean; contentType?: string; } interface Route { route: string; method: string; data: T; } interface RouterOptions { /** * Normalize each pattern into the shape of the `event.url.pathname` it will be * matched against (percent-encoding, needless-escape decoding, dot segments), * mirroring what h3 does in its own `on()`. * * Turn this off for a router that is matched with another *pattern* rather * than with a request path — the two sides would otherwise normalize * differently and stop matching. * * @default true */ normalize?: boolean; } declare class Router { _routes?: Route[]; _router?: RouterContext; /** * Cached output of {@link compileToString}, invalidated by {@link _update}. * * Only one result is cached: each Router instance must always be compiled with * the same `opts`. Compiling one instance with differing `opts` would silently * return the first result, since `opts` holds a `serialize` closure and is * therefore not hashable into a cache key. */ _compiled?: string; _baseURL: string; _normalize: boolean; constructor(baseURL?: string, opts?: RouterOptions); get routes(): Route[]; _update(routes: Route[], opts?: { merge?: boolean; }): void; hasRoutes(): boolean; compileToString(opts?: CompileRouterToStringOptions): string; match(method: string, path: string): undefined | T; matchAll(method: string, path: string): T[]; _lookupPath(path: string): string; } /** * @deprecated Use `RouteRuleConfig` from `h3/rules` (re-exported by `nitro/types`). */ export type NitroRouteConfig = RouteRuleConfig$1; /** * @deprecated Use `NormalizedRouteRules` from `h3/rules` (re-exported by `nitro/types`). */ export type NitroRouteRules = NormalizedRouteRules$1; declare module "h3/rules" { interface RouteRuleConfig { /** * 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; /** * 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. * * Do not combine with `prerender` on the same route — prerendered pages are * generated at build time and ISR will not apply. * * @see https://nitro.build/docs/routing#isr-vercel */ isr?: number | boolean | VercelISRConfig; static?: boolean | number; } interface RouteRules { prerender?: boolean; isr?: number | boolean | VercelISRConfig; static?: boolean | number; } } export interface VercelISRConfig { /** * (vercel) * Expiration time (in seconds) before the cached asset will be re-generated by invoking the Serverless Function. * Setting the value to `false` (or `isr: true` route rule) means it will never expire. */ expiration?: number | false; /** * (vercel) * Group number of the asset. * Prerender assets with the same group number will all be re-validated at the same time. */ group?: number; /** * (vercel) * List of query string parameter names that will be cached independently. * - If an empty array, query values are not considered for caching. * - If undefined each unique query value is cached independently * - For wildcard `/**` route rules, `url` is always added. */ allowQuery?: string[]; /** * (vercel) * When `true`, the query string will be present on the `request` argument passed to the invoked function. The `allowQuery` filter still applies. * * Defaults to `true` when `allowQuery` is a non-empty list, so the listed params reach the handler. Set to `false` to opt out. */ passQuery?: boolean; /** * (vercel) * * When `true`, expose the response body regardless of status code including error status codes. (default `false`) */ exposeErrBody?: boolean; } type MaybeArray$2 = T | T[]; /** Nitro package metadata including version information. */ export interface NitroMeta { version: string; majorVersion: number; } /** * The core Nitro instance available throughout the build lifecycle. * * Provides access to resolved options, hooks, the virtual file system, * scanned handlers, and utility methods. */ export interface Nitro { meta: NitroMeta; options: NitroOptions; scannedHandlers: NitroEventHandler[]; vfs: Map string | Promise; }>; hooks: Hookable; logger: ConsolaInstance; fetch: (input: Request) => Response | Promise; close: () => Promise; updateConfig: (config: NitroDynamicConfig) => void | Promise; routing: Readonly<{ sync: () => void; routeRules: Router; routes: Router>; globalMiddleware: (NitroEventHandler & { _importHash: string; })[]; routedMiddleware: Router; }>; /** Routes generated by the last `prerender()` run. */ _prerenderedRoutes?: PrerenderRoute[]; /** * Page template provided by a builder integration (e.g. `nitro/vite`), compiled into the * renderer template at build time (in development too). * * @internal */ _pageTemplate?: { /** * Returns the page HTML (e.g. the client HTML transformed by the builder). * * Defaults to the contents of `renderer.template`. */ html?: () => string | undefined | Promise; /** Imports added to the template context (e.g. `fetchViteEnv`). */ context?: { from: string; name: string; }[]; }; /** * Set by the builder integration that builds the `services` (e.g. `nitro/vite`): how the * server loads the output of each service. * * @internal */ _serviceLoader?: (name: string) => NitroServiceLoader; } /** * How the server loads the output of a service. * * - `import`: module (path or id) imported on the first fetch, bundled by Nitro in production. * With `bundle: false`, the module (e.g. a file URL of the service output in development) is * imported at runtime, not bundled. A failed import is retried by the next fetch. * - `expression`: JavaScript expression evaluated on each fetch, returning the `{ fetch }` * service (e.g. registered by a dev worker on `globalThis`). */ export type NitroServiceLoader = { import: string; bundle?: false; } | { expression: string; }; /** * Subset of {@link NitroConfig} that can be updated at runtime via * `nitro.updateConfig()`. */ export type NitroDynamicConfig = Pick; /** * Metadata about the framework using Nitro. * * @see https://nitro.build/config/advanced#framework */ export interface NitroFrameworkInfo { name?: "nitro" | (string & {}); version?: string; /** * Command shown in build output as the suggested preview command. * * Display-only: Nitro never executes this. Use this when the framework * wraps `nitro preview` with its own CLI (e.g. `npx nuxt preview`). * Defaults to `npx nitro preview`. */ previewCommand?: string; /** * Command shown in build output as the suggested deploy command. * * Display-only: Nitro never executes this. Use this when the framework * wraps `nitro deploy` with its own CLI (e.g. `npx nuxt deploy`). * Defaults to `npx nitro deploy --prebuilt`. */ deployCommand?: string; } /** * Build info written to `/nitro.json` (production, default * `.output/nitro.json`) or `/node_modules/.nitro/nitro.dev.json` * (development). * * Contains preset, framework, version, and command information. */ export interface NitroBuildInfo { date: string; preset: PresetName; envName?: string; framework: NitroFrameworkInfo; versions: { nitro: string; [key: string]: string; }; commands?: { preview?: string; deploy?: string; }; serverEntry?: string; publicDir?: string; dev?: { pid: number; workerAddress?: WorkerAddress; /** Public URL of the dev server (its first listener). */ url?: string; }; config?: Partial; } type MaybeArray$1 = T | T[]; type MaybePromise$1 = T | Promise; interface BundlerInputOptions { input?: string | string[] | Record; external?: MaybeArray$1 | ((source: string, importer: string | undefined, isResolved: boolean) => boolean | void); treeshake?: boolean | Record; onwarn?: (warning: any, defaultHandler: (warning: any) => void) => void; onLog?: (level: "info" | "debug" | "warn", log: any, defaultHandler: (...args: any[]) => void) => void; logLevel?: "info" | "debug" | "warn" | "silent"; preserveEntrySignatures?: false | "strict" | "allow-extension" | "exports-only"; context?: string; moduleContext?: Record | ((id: string) => string | null | undefined); /** Rolldown only. */ platform?: "node" | "browser" | "neutral"; /** Rolldown only. */ resolve?: Record; /** Rolldown only. */ transform?: Record; /** Rolldown only. */ checks?: Record; /** Builder-specific options. */ [key: string]: any; } interface BundlerOutputOptions { dir?: string; file?: string; format?: "es" | "esm" | "module" | "cjs" | "commonjs" | "iife" | "umd" | "amd" | "system"; entryFileNames?: string | ((chunkInfo: any) => string); chunkFileNames?: string | ((chunkInfo: any) => string); assetFileNames?: string | ((assetInfo: any) => string); sourcemap?: boolean | "inline" | "hidden"; sourcemapExcludeSources?: boolean; sourcemapIgnoreList?: boolean | ((source: string, sourcemapPath: string) => boolean); sourcemapPathTransform?: (source: string, sourcemapPath: string) => string; banner?: string | ((chunk: any) => MaybePromise$1); footer?: string | ((chunk: any) => MaybePromise$1); intro?: string | ((chunk: any) => MaybePromise$1); outro?: string | ((chunk: any) => MaybePromise$1); exports?: "auto" | "default" | "named" | "none"; inlineDynamicImports?: boolean; /** Rollup only. */ manualChunks?: Record | ((id: string, meta: any) => string | null | undefined); /** Rolldown only. */ codeSplitting?: boolean | Record; /** Rolldown only. */ minify?: boolean | "dce-only" | Record; /** Builder-specific options. */ [key: string]: any; } /** Rolldown (oxc) minifier options. */ interface BundlerMinifyOptions { module?: boolean; compress?: boolean | Record; mangle?: boolean | Record; mangleProps?: Record; codegen?: boolean | Record; sourcemap?: boolean; } type FilterPattern = ReadonlyArray | string | RegExp | null; type RequireReturnsDefaultOption = boolean | "auto" | "preferred" | "namespace"; type DefaultIsModuleExportsOption = boolean | "auto"; /** `@rollup/plugin-commonjs` options. */ interface CommonJSOptions { include?: FilterPattern; exclude?: FilterPattern; extensions?: ReadonlyArray; ignoreGlobal?: boolean; sourceMap?: boolean; ignoreDynamicRequires?: boolean; transformMixedEsModules?: boolean; strictRequires?: boolean | FilterPattern; ignore?: ReadonlyArray | ((id: string) => boolean); ignoreTryCatch?: boolean | "remove" | ReadonlyArray | ((id: string) => boolean | "remove"); esmExternals?: boolean | ReadonlyArray | ((id: string) => boolean); requireReturnsDefault?: RequireReturnsDefaultOption | ((id: string) => RequireReturnsDefaultOption); defaultIsModuleExports?: DefaultIsModuleExportsOption | ((id: string) => DefaultIsModuleExportsOption); dynamicRequireTargets?: string | ReadonlyArray; dynamicRequireRoot?: string; requireNodeBuiltins?: boolean; } /** * A build plugin (Rollup plugin interface), applied with every builder. * * Rollup, Rolldown and Vite plugins are accepted. Only `resolveId`, `load` and `transform` are * supported by all builders (`builder: false` runs plugins in env-runner, which supports only * these). */ export interface NitroBuildPlugin { name: string; /** Run before (`"pre"`) or after (`"post"`) the other plugins. */ enforce?: "pre" | "post"; resolveId?: NitroBuildPluginHook<(this: any, source: string, importer: string | undefined, options: any) => any>; load?: NitroBuildPluginHook<(this: any, id: string, options?: any) => any>; transform?: NitroBuildPluginHook<(this: any, code: string, id: string, options?: any) => any>; /** Builder-specific hooks and options. */ [key: string]: any; } export type NitroBuildPluginHook = Handler | { order?: "pre" | "post" | null; filter?: NitroBuildPluginHookFilter | readonly unknown[]; handler: Handler; }; export interface NitroBuildPluginHookFilter { id?: NitroBuildPluginStringFilter; code?: NitroBuildPluginStringFilter; moduleType?: NitroBuildPluginStringFilter; } export type NitroBuildPluginStringFilter = MaybeArray | { include?: MaybeArray; exclude?: MaybeArray; }; /** `buildPlugins` entries: nested arrays and promises are resolved, falsy ones skipped. */ export type NitroBuildPluginOption = MaybePromise; export type RollupConfig = OptionalDepType, BundlerInputOptions> & { output?: OptionalDepType; plugins?: (OptionalDepType | OptionalDepType)[]; }; export type RolldownConfig = OptionalDepType & { output?: OptionalDepType; }; /** Rspack configuration (experimental `rspack` builder). */ export type RspackConfig = OptionalDepType>; /** * [`Bun.build`](https://bun.com/docs/bundler) options used by the `bun` builder. * * Nitro's build plugins run in a single Bun plugin (`nitro:plugins`) of `plugins`. */ export interface BunConfig { entrypoints?: string[]; root?: string; target?: "bun" | "node" | "browser"; format?: "esm" | "cjs" | "iife"; splitting?: boolean; external?: string[]; packages?: "bundle" | "external"; conditions?: string | string[]; naming?: string | { entry?: string; chunk?: string; asset?: string; }; minify?: boolean | { whitespace?: boolean; syntax?: boolean; identifiers?: boolean; }; sourcemap?: boolean | "none" | "linked" | "inline" | "external"; define?: Record; loader?: Record; banner?: string; footer?: string; drop?: string[]; jsx?: { runtime?: "automatic" | "classic"; importSource?: string; factory?: string; fragment?: string; development?: boolean; }; env?: "inline" | "disable" | `${string}*`; metafile?: boolean; plugins?: { name: string; setup: (build: any) => void | Promise; }[]; /** Other `Bun.build` options. */ [key: string]: any; } /** * Bundler config passed to the `build:config` hook, keyed by the bundler in use. * * The `vite` builder passes a Rollup or Rolldown config, depending on the Vite version. */ export type NitroBuildConfig = { builder: "rollup" | "vite"; rollup: RollupConfig; rolldown?: never; rspack?: never; bun?: never; } | { builder: "rolldown" | "vite"; rolldown: RolldownConfig; rollup?: never; rspack?: never; bun?: never; } | { builder: "rspack"; rspack: RspackConfig; rollup?: never; rolldown?: never; bun?: never; } | { builder: "bun"; bun: BunConfig; rollup?: never; rolldown?: never; rspack?: never; }; export interface OXCOptions { minify?: OptionalDepType; transform?: Omit & { jsx?: Exclude; }; } type MaybePromise = T | Promise; type MaybeArray = T | readonly T[]; type HookResult = void | Promise; export interface NitroHooks { "build:before": (nitro: Nitro) => HookResult; /** * Called after the bundler config is resolved, right before bundling. Last chance to modify it. * * The config is passed as `{ builder, rollup }`, `{ builder, rolldown }`, `{ builder, rspack }` or `{ builder, bun }`, * depending on the builder and bundler in use. */ "build:config": (nitro: Nitro, config: NitroBuildConfig) => HookResult; "vite:compile:before": (nitro: Nitro) => HookResult; compiled: (nitro: Nitro) => HookResult; "dev:reload": (payload?: { entry?: string; workerData?: EnvRunnerData; /** Host-side env-runner plugins for the dev runner. */ plugins?: EnvRunnerPluginOption[]; }) => HookResult; "dev:start": () => HookResult; "dev:error": (cause?: unknown) => HookResult; /** Called when the Nitro config is hot-reloaded to rebuild the server. */ "build:reload": () => HookResult; restart: () => HookResult; close: () => HookResult; "prerender:routes": (routes: Set) => HookResult; "prerender:config": (config: NitroConfig) => HookResult; "prerender:init": (prerenderer: Nitro) => HookResult; "prerender:generate": (route: PrerenderRoute, nitro: Nitro) => HookResult; "prerender:route": (route: PrerenderRoute) => HookResult; "prerender:done": (result: { prerenderedRoutes: PrerenderRoute[]; failedRoutes: PrerenderRoute[]; }) => HookResult; /** @deprecated Use `build:config` (the config is passed as `{ rollup }` or `{ rolldown }`). */ "rollup:before": (nitro: Nitro, config: RollupConfig) => HookResult; /** @deprecated Use `build:reload`. */ "rollup:reload": () => HookResult; } /** * 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/features#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 * export default { * name: "my-module", * nitro: { * setup(nitro) { * nitro.hooks.hook("compiled", () => { * console.log("Build complete!"); * }); * }, * }, * }; * ``` * * @see https://nitro.build/config/features#modules */ export interface NitroModule { name?: string; setup: (this: void, nitro: Nitro) => void | Promise; } /** * Swagger UI configuration options. * * @see https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/ */ interface SwaggerUIConfig { deepLinking?: boolean; displayOperationId?: boolean; defaultModelsExpandDepth?: number; defaultModelExpandDepth?: number; defaultModelRendering?: "example" | "model"; displayRequestDuration?: boolean; docExpansion?: "list" | "full" | "none"; filter?: boolean | string; persistAuthorization?: boolean; requestSnippetsEnabled?: boolean; showExtensions?: boolean; showCommonExtensions?: boolean; /** Only "alpha" is supported (function values are not JSON-serializable). */ tagsSorter?: "alpha"; /** * Note: function callbacks cannot be passed via Nitro configuration (not JSON-serializable). */ onComplete?: never; layout?: string; configUrl?: string; oauth2RedirectUrl?: string; withCredentials?: boolean; [key: string]: unknown; } /** * Nitro OpenAPI configuration. * * @see https://nitro.build/config/features#openapi * @see https://nitro.build/docs/openapi */ interface NitroOpenAPIConfig { /** * OpenAPI document metadata. */ meta?: { title?: string; description?: string; version?: string; }; /** * Route for the OpenAPI JSON endpoint. * * @default "/_openapi.json" */ route?: string; /** * 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/features#openapi */ production?: false | "runtime" | "prerender"; /** * UI configurations for interactive API documentation. */ ui?: { /** * Scalar UI configuration. * * Set to `false` to disable. */ scalar?: false | (Partial & { /** * Route for Scalar UI. * * @default "/_scalar" */ route?: string; }); /** * Swagger UI configuration. * * Set to `false` to disable. * * @see https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/ */ swagger?: false | (SwaggerUIConfig & { /** * Route for Swagger UI. * * @default "/_swagger" */ route?: string; }); }; } export type NitroPreset = NitroConfig | (() => NitroConfig); interface NitroPresetMeta$1 { name: string; stdName?: ProviderName; aliases?: string[]; static?: boolean; dev?: boolean; compatibilityDate?: DateString; } /** * 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 { _config: NitroConfig; _c12: ResolvedConfig | ConfigWatcher; _cli?: { command?: string; }; /** * Resolved config layers, ordered from highest to lowest priority. * * The first layer is always the project root. It is followed by layers * added with `extends` (local directories, config files, npm packages, or * remote sources). Presets and inline config overrides are not included. */ layers: NitroConfigLayer[]; /** * Opt-in date for deployment provider and runtime compatibility 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/general#compatibilitydate */ compatibilityDate: CompatibilityDates; /** * Enables debugging nitro (build time) hooks in the console. * * @see https://nitro.build/config/general#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/general#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/general#static */ static: boolean; /** * Log verbosity level. * * Defaults to `3`, or `1` when a testing environment is detected. * * @see https://nitro.build/config/general#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/general#runtimeconfig */ runtimeConfig: NitroRuntimeConfig; /** * Project workspace root directory. * * Auto-detected from the workspace (e.g. pnpm workspace) when not set. * * @see https://nitro.build/config/directories#workspacedir */ workspaceDir: string; /** * Project main root directory. * * @see https://nitro.build/config/directories#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/directories#serverdir */ serverDir: string | false; /** * Additional directories to scan and auto-register files such as API * route handlers. * * @see https://nitro.build/config/directories#scandirs */ scanDirs: string[]; /** * Directory name to scan for API route handlers. * * @default "api" * @see https://nitro.build/config/directories#apidir */ apiDir: string; /** * Directory name to scan for route handlers. * * @default "routes" * @see https://nitro.build/config/directories#routesdir */ routesDir: string; /** * Nitro's temporary working directory for build-related files. * * @default "node_modules/.nitro" * @see https://nitro.build/config/directories#builddir */ buildDir: string; /** * Output directories for the production bundle. * * @see https://nitro.build/config/directories#output */ output: { /** Production output root directory. */ dir: string; /** Server bundle output directory. */ serverDir: string; /** Public/static assets output directory. */ publicDir: string; }; /** * Directory (relative to the served base) for generated build assets. * * Applied as the bundler `assetsDir` for client and SSR environments, so * generated assets are emitted and referenced under this path. Presets can * use it to relocate content-addressed assets (e.g. Vercel immutable static * files under `_vercel/immutable`). */ buildAssetsDir?: string; /** @deprecated Migrate to `serverDir`. */ srcDir: string; /** * KV storage mount configuration. * * Keys are mount-point paths; values specify the unstorage driver and * its options. * * @see https://nitro.build/config/storage#kv * @see https://nitro.build/docs/storage */ kv: KVMounts; /** @deprecated Migrate to `kv`. */ storage: KVMounts; /** @deprecated Migrate to `kv` inside `$development` (and `$prerender`) config. */ devStorage: KVMounts; /** * Cache storage and global default options for cached functions, cached handlers * and `cache` route rules. * * @see https://nitro.build/config/storage#cache * @see https://nitro.build/docs/cache */ cache: NitroCacheConfig; /** * Database connection configurations. * * Requires `experimental.database: true`. * * @see https://nitro.build/config/storage#database * @see https://nitro.build/docs/database */ database: DatabaseConnectionConfigs; /** * Database connection overrides for development mode. * * @see https://nitro.build/config/storage#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/features#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`. * - `"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/assets#servestatic */ serveStatic: boolean | "node" | "inline"; /** * Disable the public output directory entirely. * * Skips preparing the `.output/public` directory, copying public * assets, and prerendering routes. * * @see https://nitro.build/config/assets#nopublicdir */ noPublicDir: boolean; tracingChannel?: undefined | TracingChannelOptions; /** * 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 */ features: { /** * Enable runtime hooks for request and response. * * By default this feature will be enabled if there is at least one nitro plugin. */ runtimeHooks?: boolean; /** * Enable WebSocket support. */ websocket?: boolean; /** * Replace the global `Response` with srvx `FastResponse`, so that * `new Response()` skips the native Response overhead in Node.js. * * Enabled by default when `node` is `true`. */ fastResponse?: boolean; }; /** * Native wasm compatibility/bundling support configuration. * * Set to `false` to disable. * * @see https://nitro.build/config/features#wasm * @see https://github.com/unjs/unwasm */ wasm?: false | UnwasmPluginOptions; /** * OpenAPI specification generation and UI configuration. * * @see https://nitro.build/config/features#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/features#experimental */ experimental: { /** * Enable experimental OpenAPI support * * @see https://nitro.build/docs/openapi */ openAPI?: boolean; /** * See https://github.com/microsoft/TypeScript/pull/51669 */ typescriptBundlerResolution?: boolean; /** * Enable native async context support for useRequest() */ asyncContext?: boolean; /** * Set to `false` to disable sourcemap minification in production builds. * * Sourcemap minification is enabled by default when `sourcemap` is on. */ sourcemapMinify?: false; /** * Set to `false` to disable entries-aware library chunks (Rolldown and Vite builders). * * By default, each `node_modules` package chunk is split by the entries (main entry and lazy * route handlers) that use it, so startup does not load code that only lazy routes need. * Disabling it produces fewer, larger library chunks. */ entriesAwareLibChunks?: false; /** * Allow env expansion in runtime config * * @see https://github.com/nitrojs/nitro/pull/2043 */ envExpansion?: boolean; /** * Enable WebSocket upgrade support * * @deprecated Use `features.websocket` instead. */ websocket?: boolean; /** * Enable experimental Database support * * @see https://nitro.build/docs/database */ database?: boolean; /** * Enable experimental Tasks support * * @see https://nitro.build/docs/tasks */ tasks?: boolean; /** * Log Nitro tracing-channel spans to the console. * * Enables a built-in, dependency-free telemetry sink that `console.log`s * each completed span (h3, srvx, unstorage, db0, …). Requires `tracingChannel` * to be enabled. */ tracingLogger?: boolean; }; /** * Server-side asset directories bundled at build time. * * @see https://nitro.build/config/assets#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/assets#publicassets * @see https://nitro.build/docs/assets */ publicAssets: PublicAssetDir[]; /** * Nitro modules to extend behavior during initialization. * * Accepts module path strings, {@link NitroModule} objects, or bare setup functions. * * @see https://nitro.build/config/features#modules */ modules?: NitroModuleInput[]; /** * Paths to Nitro runtime plugins. * * Plugins in the `plugins/` directory are auto-registered. * * @see https://nitro.build/config/features#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/features#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/features#scheduledtasks * @see https://nitro.build/docs/tasks */ scheduledTasks: { [cron: string]: string | string[]; }; /** * Scheduler options for `scheduledTasks`. * * @see https://nitro.build/config/features#scheduler */ scheduler: { /** * Run `scheduledTasks` in-process with the built-in cron runner, in presets that use it * (`dev`, `node_*`, `bun` and `deno_server`). * * Set to `false` when something else invokes the scheduled tasks, such as a system cron. * The tasks stay registered, so `runCronTasks()` and the `/_nitro/tasks` dev route keep * working. Platform schedules (Cloudflare Cron Triggers, Vercel Cron Jobs) are not affected. * * @default true */ runner?: boolean; }; /** * 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/features#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/assets#compresspublicassets */ compressPublicAssets: boolean | CompressOptions; /** * Glob patterns to ignore when scanning directories. * * @see https://nitro.build/config/directories#ignore */ ignore: string[]; /** * Additional dotted suffixes to keep as part of scanned file names (e.g. `"prompt"` for * `routes/system.prompt.ts` → `/system.prompt`). * * Nitro reserves trailing lowercase suffixes in scanned file names. Known file extensions * (e.g. `.json`, `.md`, `.xml`) are always kept. * * @see https://nitro.build/config/directories#scansuffixes */ scanSuffixes: string[]; /** * Whether the current build targets development mode. * * Defaults to `true` during development and `false` for production. * * @see https://nitro.build/config/advanced#dev */ dev: boolean; /** * Environment name used to apply `$env.` (or `$`) config overrides. * * Defaults to `"development"` in development and `"production"` otherwise. A custom * name (for example `"staging"`) can be set with the `--envName` CLI flag or the * `c12.envName` load option of `createNitro()`. Available in server code as * `import.meta.envName`. * * @see https://nitro.build/docs/configuration#environment-specific-config */ envName: string; /** * Development server options. * * @see https://nitro.build/config/dev#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; /** * Let the previous dev worker finish the requests and WebSockets it already accepted on * reloads, and shut it down once they settle (or after `timeout` ms, default `60_000`). * * New requests go to the new worker right away. * * @default false */ drain?: RunnerReloadOptions["drain"]; /** * Serve `/.well-known/appspecific/com.chrome.devtools.json` so Chrome DevTools can connect * the project folder as an automatic workspace. * * @default true * @see https://chromium.googlesource.com/devtools/devtools-frontend/+/main/docs/ecosystem/automatic_workspace_folders.md */ devtoolsJson?: boolean; }; /** * File watcher options for development mode. * * @see https://nitro.build/config/dev#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/dev#devproxy * @see https://github.com/unjs/httpxy */ devProxy: Record; /** * Build logging behavior. * * @see https://nitro.build/config/general#logging */ logging: { /** Report compressed bundle sizes after build. */ compressedSizes?: boolean; /** Show the build success message. */ buildSuccess?: boolean; }; /** * Server's main base URL prefix. * * Can also be set via the `NITRO_APP_BASE_URL` environment variable. * * @default "/" * @see https://nitro.build/config/routing#baseurl */ baseURL: string; /** * Base URL prefix for API routes. * * @default "/api" * @see https://nitro.build/config/routing#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/routing#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/routing#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/routing#routerules * @see https://nitro.build/docs/routing#route-rules */ routeRules: { [path: string]: NormalizedRouteRules; }; /** * Inline route definitions. * * A map from route pattern to handler path or handler options. * * @see https://nitro.build/config/routing#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/routing#errorhandler */ errorHandler: string | string[]; /** * Custom error handler function for development mode. * * @see https://nitro.build/config/advanced#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/routing#prerender */ prerender: { /** * 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 of routes to skip: a string prefix, a rou3 route pattern (a string * containing `*` or `:`, e.g. `/blog/**`), a RegExp, or a function. */ ignore?: Array undefined | null | boolean)>; /** * Status codes of failed routes that do not fail the build when `failOnError` is enabled * (e.g. `[404]`). These routes are still reported and not written. */ ignoreStatusCodes?: number[]; /** Skip prerendering assets without a base URL prefix. */ ignoreUnprefixedPublicAssets?: boolean; /** Explicit list of routes to prerender. */ routes?: string[]; }; /** * Bundler to use for production builds. * * Auto-detected when not set: `"vite"` if a `vite.config` with the * `nitro()` plugin is found, otherwise `"rolldown"` (installed on demand). In development, * `false` is used when `rolldown` is not installed. * Use the `NITRO_BUILDER` environment variable as an alternative. * * Set to `false` to run the server sources without bundling (experimental, `dev` and * `preview` only). * * `"rspack"` bundles the server with [Rspack](https://rspack.rs) (experimental). * Set to `"bun"` (experimental) to bundle with `Bun.build`. It requires running Nitro with Bun. * * @see https://nitro.build/config/build#builder */ builder?: "rollup" | "rolldown" | "rspack" | "vite" | "bun" | false; /** * Services of the app: server entries exporting a `fetch` handler, built by the builder * integration (e.g. `nitro/vite`) and fetched with `fetchService()` from `nitro/services`. * * An `ssr` service is detected from an `entry-server` file in `app/`, `src/` or the root * directory, and server environments with an entry are registered automatically. * * @see https://nitro.build/config/build#services */ services: Record; /** * Options for the `vite` builder and the `nitro/vite` plugin. */ vite?: { /** * The `vite` package to use, as a path or `file://` URL to its directory or entry * (e.g. `import.meta.resolve("vite")`). * * By default, the `nitro/vite` plugin uses the running `vite` and the `vite` builder * resolves it from the project root. */ path?: string; /** * Alias of the top-level `services` option (which takes precedence). * * @deprecated Use the top-level `services` option. */ services?: Record; /** * Enable `?assets` imports proposed by https://github.com/vitejs/vite/discussions/20913. * * @default true */ assetsImport?: boolean; /** * Reload the dev server (and the browser) when a server-only module is updated. * * When disabled, server-only modules are still invalidated but the dev worker * keeps its current evaluations. * * @default true */ serverReload?: boolean; }; /** * Options for the optional dependencies Nitro installs on demand (such as `vite`, `rolldown`, * `unstorage` or `db0`). * * @see https://nitro.build/config/build#deps */ deps?: NitroDepsOptions; /** * Build plugins, applied with every builder (`rollup`, `rolldown`, `rspack`, `vite`, `bun` and `false`). * * Plugins use the Rollup plugin interface. Only the `resolveId`, `load` and `transform` hooks * are supported by all builders; with `builder: false`, plugins run in * [env-runner](https://github.com/unjs/env-runner), which supports only these. * * Plugins with `enforce: "pre"` are placed before Nitro's own plugins, the others after them * (a hook's own `order` takes precedence). * * @see https://nitro.build/config/build#buildplugins */ buildPlugins: NitroBuildPluginOption[]; /** * Additional Rollup configuration. * * @see https://nitro.build/config/build#rollupconfig */ rollupConfig?: RollupConfig; /** * Additional Rolldown configuration. * * @see https://nitro.build/config/build#rolldownconfig */ rolldownConfig?: RolldownConfig; /** * Additional Rspack configuration (experimental `rspack` builder). * * @see https://nitro.build/config/build#rspackconfig */ rspackConfig?: RspackConfig; /** * Additional `Bun.build` options for the `bun` builder. * * @see https://nitro.build/config/build#bunconfig */ bunConfig?: BunConfig; /** * Bundler entry point path. * * @see https://nitro.build/config/build#entry */ entry: string; /** @deprecated Migrate to `alias`, `inject`, `polyfills` and `builtinModules`. */ unenv: LegacyUnenvPreset[]; /** * Path aliases for module resolution. * * @example * ```ts * alias: { * "~utils": "./src/utils", * "#shared": "./shared", * } * ``` * * @see https://nitro.build/config/build#alias */ alias: Record; /** * Globals to replace with imports when referenced in the bundle. * * Values are a module id (default export) or a `[id, exportName]` tuple. * Set a global to `false` to remove a default injection (e.g. one added * for `node: false` builds). * * @example * ```ts * inject: { * Buffer: ["node:buffer", "Buffer"], * } * ``` * * @see https://nitro.build/config/build#inject */ inject: Record; /** * Modules imported for their side effects before the server entry. * * Prefix an entry with `!` to remove a default polyfill. * * @see https://nitro.build/config/build#polyfills */ polyfills: string[]; /** * Modules provided by the target runtime (e.g. `node:fs` on Deno or * `cloudflare:workers`). * * Imports of these ids are kept as-is in the output: they are never bundled, * traced or copied, so only list modules the runtime itself provides. To * keep an npm package out of the bundle, use `traceDeps` instead. * * Prefix an entry with `!` to remove a default (e.g. one added by a preset). * * @see https://nitro.build/config/build#builtinmodules */ builtinModules: string[]; /** * Minify the production bundle. * * @see https://nitro.build/config/build#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/build#inlinedynamicimports */ inlineDynamicImports: boolean; /** * Enable source map generation. * * @see https://nitro.build/config/build#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 adds default `alias`, `inject` and `polyfills` * entries that polyfill Node.js globals and built-ins for non-Node * runtimes (workers, edge, Deno). * * @see https://nitro.build/config/build#node */ node: boolean; /** * OXC options for Rolldown builds (minification and transforms). * * @see https://nitro.build/config/build#oxc */ oxc?: OXCOptions; /** * Build-time string replacements. * * @see https://nitro.build/config/build#replace */ replace: Record string)>; /** * Additional configuration for the Rollup CommonJS plugin. * * @see https://nitro.build/config/build#commonjs */ commonJS?: CommonJSOptions; /** * Custom export conditions for module resolution. * * @see https://nitro.build/config/build#exportconditions */ exportConditions?: string[]; /** * Prevent packages from being externalized. * * Set to `true` to bundle all dependencies, or pass an array of patterns * matched against both the import specifier and the resolved module path. * * @see https://nitro.build/config/build#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/build#tracedeps */ traceDeps?: (string | RegExp)[]; /** * Advanced options for dependency tracing via nf3. * * @see https://nitro.build/config/build#traceopts * @see https://github.com/unjs/nf3 */ traceOpts?: Pick; /** * TypeScript configuration options. * * @see https://nitro.build/config/advanced#typescript */ typescript: { /** * TypeScript config used by the bundler (JSX options and path aliases). * * Defaults to the resolved `tsconfig.json` of the project root. */ tsConfig?: Partial; /** * Resolve path aliases (`compilerOptions.paths`) of `tsConfig` for the server sources. * * @default true */ tsconfigPaths?: boolean; }; /** * Nitro lifecycle hooks. * * @see https://nitro.build/config/advanced#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/advanced#commands */ commands: { /** Command to preview the production build locally. */ preview?: string; /** * Command to deploy the production build. * * Can be a shell command (`./` paths are resolved relative to the output directory) * or a function (used by presets that deploy programmatically). */ deploy?: string | ((nitro: Nitro, opts: DeployOptions) => void | Promise); }; /** * 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/advanced#framework */ framework: NitroFrameworkInfo; } /** * User-facing Nitro configuration used in `nitro.config.ts` or * `defineConfig()`. * * 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 Partial>, C12InputConfig { /** Config overrides applied when prerendering (on top of the build env overrides, `$production` by default). */ $prerender?: NitroConfig; preset?: PresetNameInput; /** * Customize the preset used as the **fallback** when no `preset` is set and * none of the known hosting providers are auto-detected. * * By default, Nitro falls back to the runtime-based preset (`node`, and * `deno` or `bun` when running on those runtimes). An explicit `preset`, * the `NITRO_PRESET` environment variable, and auto-detected providers * (Vercel, Netlify, Cloudflare Pages, …) all take precedence over this. * * Accepts a preset name or an inline preset definition. * * @see https://nitro.build/config/general#defaultpreset */ defaultPreset?: PresetNameInput | NitroPreset; extends?: string | string[] | NitroPreset; routeRules?: { [path: string]: RouteRuleConfig; }; rollupConfig?: Partial; compatibilityDate?: CompatibilityDateSpec; /** @deprecated Migrate to `alias`, `inject`, `polyfills` and `builtinModules`. */ unenv?: LegacyUnenvPreset | LegacyUnenvPreset[]; serverDir?: boolean | "./" | "./server" | (string & {}); serverEntry?: string | NitroOptions["serverEntry"]; renderer?: false | NitroOptions["renderer"]; output?: Partial; tracingChannel?: boolean | TracingChannelOptions; } /** Options for loading Nitro configuration via c12. */ export interface LoadConfigOptions { watch?: boolean; c12?: WatchConfigOptions; compatibilityDate?: CompatibilityDateSpec; dotenv?: boolean | DotenvOptions; } /** * A resolved config layer available on `nitro.options.layers`. */ export interface NitroConfigLayer { /** Absolute path to the layer directory. */ cwd: string; /** Absolute path to the layer config file, if one exists. */ configFile?: string; /** * Config defined by this layer (before merging with other layers and * defaults). Environment-specific overrides such as `$production` are * already applied. */ config: NitroConfig; /** Layer metadata from `$meta` in the layer config or `extends` options. */ meta?: { name?: string; [key: string]: unknown; }; } /** * Options for the optional dependencies Nitro installs on demand. * * @see https://nitro.build/config/build#deps */ export interface NitroDepsOptions { /** * Explicit packages to use, by package name, as a path or `file://` URL to the package * directory or entry (e.g. `import.meta.resolve("unstorage")`). Relative paths resolve * against `rootDir`. * * By default, these packages are resolved from the project root and installed on demand. A * framework built on top of Nitro can pass its own copies, so the versions it depends on are * the ones that run. `deps.paths.vite` and `vite.path` are aliases. */ paths?: Record; /** * Whether a missing package may be installed. Disable it to fail with the install command * instead, so a build only uses the committed dependencies. * * Interactive environments prompt before installing (except for the packages the server * bundle imports). Nothing is installed in tests, for an explicit package in `paths`, or * when `rootDir` is inside `node_modules`. * * @default true, or `false` in CI */ install?: boolean; } /** * Server entry exporting a `fetch` handler, fetched with `fetchService()` from `nitro/services`. * * @see https://nitro.build/config/build#services */ export interface NitroServiceConfig { /** Path to the service entry. */ entry: string; } /** * @deprecated Use {@link NitroServiceConfig}. */ export type ViteServiceConfig = NitroServiceConfig; /** * Configuration for a public asset directory served in development and * bundled in production. * * @see https://nitro.build/config/assets#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. * * Left `undefined` when unset, which some presets (such as Vercel) treat * differently from an explicit `0`. */ 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 (overrides global * `nitro.ignore` patterns). */ ignore?: false | string[]; } /** * Pre-compression options for public assets and prerendered routes. * * @see https://nitro.build/config/assets#compresspublicassets */ export interface CompressOptions { /** Enable gzip pre-compression. */ gzip?: boolean; /** Enable brotli pre-compression. */ brotli?: boolean; /** Enable zstd pre-compression. */ zstd?: boolean; } /** * Configuration for a server-side asset directory bundled at build time. * * @see https://nitro.build/config/assets#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[]; } /** * Tracing channel options. * * @see https://nitro.build/config/advanced#tracingchannel */ export interface TracingChannelOptions { srvx?: boolean; h3?: boolean; unstorage?: boolean; /** Database queries made with `useDatabase()` (`db0.query`). Requires `experimental.database`. */ db0?: boolean; } /** * Preset shape accepted by the deprecated `unenv` option (compatible with * unenv's `Preset`). * * @deprecated Migrate to `alias`, `inject`, `polyfills` and `builtinModules`. */ export interface LegacyUnenvPreset { meta?: { readonly name?: string; readonly version?: string; /** Path or URL used to resolve the preset's module ids. */ readonly url?: string | URL; }; alias?: Readonly>; inject?: Readonly>; polyfill?: readonly string[]; external?: readonly string[]; } /** Driver name (module id or alias) of a driver that is not builtin. */ type CustomDriverName = string & { _custom?: any; }; /** * Mount configuration for a builtin `unstorage` driver. * * Driver options are inferred from the `driver` name. */ export type BuiltinKVMount = { [Name in KVDriverName]: { driver: Name; } & (Name extends keyof BuiltinDriverOptions ? SerializableOptions : unknown); }[KVDriverName]; /** Builtin driver names (none when `unstorage` is not installed). */ type KVDriverName = OptionalDepType; /** Mount configuration for a custom driver (module id or alias). */ export type CustomKVMount = { driver: CustomDriverName; [option: string]: JsonValue; }; export type KVMount = BuiltinKVMount | CustomKVMount; /** * KV mount configuration mapping mount points to driver options. * * Keys are mount-point paths; values specify the unstorage driver * and its options. * * @see https://nitro.build/config/storage#kv * @see https://nitro.build/docs/storage */ export interface KVMounts { [path: string]: KVMount; } /** @deprecated Use {@link KVMount}. */ export type StorageMount = KVMount; /** @deprecated Use {@link KVMounts}. */ export type StorageMounts = KVMounts; /** Cache storage driver. */ export type NitroCacheDriver = "memory" | "fs" | "kv"; /** Options shared by cached functions and cached handlers. */ export type NitroCacheFunctionDefaults = Pick; /** Options that only apply to cached handlers and `cache` route rules. */ export type NitroCacheHandlerDefaults = Pick; /** Global default options for cached functions, cached handlers and `cache` route rules. */ export interface NitroCacheDefaults extends NitroCacheFunctionDefaults, NitroCacheHandlerDefaults {} /** * Cache configuration. * * @see https://nitro.build/config/storage#cache */ export interface NitroCacheConfig { /** * Cache storage driver. * * - `"memory"`: in-process LRU memory storage (not persisted across restarts). * - `"fs"`: filesystem storage (Node.js compatible runtimes only). * - `"kv"`: the Nitro [KV storage layer](https://nitro.build/docs/storage) (`useKV()`). * * Defaults to `"kv"` when a `cache` (or `cache:*` / `cache/*`) KV mount point is * configured, and to `"memory"` otherwise. */ driver?: NitroCacheDriver; /** Options for the `memory` driver. */ memory?: Omit; /** Options for the `fs` driver. */ fs?: { /** * Directory to store cache entries in. * * Relative paths resolve against `rootDir` in development and prerendering, and against * the working directory of the server process in production. * * Defaults to `.data/cache`. */ dir?: string; }; /** * Global default options for every cached function, cached handler and `cache` route rule. * * Shared options (`maxAge`, `swr`, `staleMaxAge`, `maxResolveTime`, `base`) apply to all of * them, handler-only options only apply to cached handlers and route rules. * Per-cache options take precedence. */ defaults?: NitroCacheDefaults; } /** 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/storage#database * @see https://nitro.build/docs/database */ export type DatabaseConnectionConfig = [DatabaseConnectorName] extends [never] ? { connector: string; options?: Record; } : { [Name in DatabaseConnectorName]: { connector: Name; options?: Name extends keyof ConnectorOptions ? SerializableOptions : Record; }; }[DatabaseConnectorName]; /** Connector names (none when `db0` is not installed). */ type DatabaseConnectorName = OptionalDepType; /** Map of {@link DatabaseConnectionName} to {@link DatabaseConnectionConfig}. */ export type DatabaseConnectionConfigs = Record; /** * 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/general#runtimeconfig */ export interface NitroRuntimeConfig { nitro?: { envPrefix?: string; envExpansion?: boolean; routeRules?: { [path: string]: RouteRuleConfig; }; openAPI?: NitroOpenAPIConfig; }; [key: string]: any; } export interface NitroImportMeta { dev?: boolean; envName?: string; preset?: NitroOptions["preset"]; prerender?: boolean; nitro?: boolean; server?: boolean; client?: boolean; baseURL?: string; runtimeConfig?: Record; _asyncContext?: boolean; _tasks?: boolean; _websocket?: boolean; } declare global { interface ImportMeta extends NitroImportMeta {} } declare module "srvx" { interface ServerRequestContext { routeRules?: Readonly; nitro?: { errors?: { error?: Error; context: CapturedErrorContext; }[]; }; } } /** * Default export of a server entry (`server.ts`). * * `fetch` handles requests no route matched (return nothing to continue to the renderer). * It is optional, for entries that only run startup logic or set server options. * Other options are passed to the srvx server of the `node`, `bun` and `deno` presets. * * Only server options that are safe to ignore by other presets (and explicit runtime specific * `node`, `bun` and `deno` options) are supported. Options that change request handling * (`middleware`, `plugins`, `error`) are not, as they would not apply to serverless presets or * `nitroApp.fetch`. * * @see https://nitro.build/docs/server-entry */ export interface NitroServerEntry extends Pick { fetch?: (request: ServerRequest$1) => Response | undefined | Promise; } export { type CacheEntry, type CachedFunction, type EnvRunner, type FetchHandler, type MatchedRouteRule, type MatchedRouteRules, type NitroOpenAPIConfig, NitroPresetMeta$1 as NitroPresetMeta, type NormalizedRouteRules, type PresetName, type PresetNameInput, type PresetOptions, type ProxyRuleOptions, type RedirectRuleOptions, type ResolvedRouteRules, type ResponseCacheEntry, type RouteRuleConfig, type RouteRules, type RunnerMessageListener, type RunnerRPCHooks, type ServerRequest, type ServerRequestContext, type ServerRuntimeContext, type UpgradeHandler, type WorkerAddress, type WorkerHooks };