import { Rule as Rule$1, CfModule, Environment as Environment$1, Entry, CfModuleType, StartDevWorkerInput, Config as Config$1, NodeJSCompatMode, CfScriptFormat, AsyncHook, CfAccount as CfAccount$1, AssetsOptions as AssetsOptions$1, Binding, ConfigBindingFieldName, RawConfig as RawConfig$1, NormalizeAndValidateConfigArgs, ResolveConfigPathOptions, ApiCredentials, ParseError, LoggerLevel, ComplianceConfig, UserError, FatalError } from '@cloudflare/workers-utils'; export { Binding, experimental_patchConfig, experimental_readRawConfig, defaultWranglerConfig as unstable_defaultWranglerConfig } from '@cloudflare/workers-utils'; import { Json as Json$1, WorkerdStructuredLog, DispatchFetch, Miniflare, WorkerRegistry, MiniflareOptions, Mutex, Response as Response$1, RemoteProxyConnectionString, WorkerOptions, ModuleRule, Request } from 'miniflare'; import * as undici from 'undici'; import { RequestInfo, RequestInit, Response, FormData } from 'undici'; import { Metafile } from 'esbuild'; import Protocol from 'devtools-protocol/types/protocol-mapping'; import { EventEmitter } from 'node:events'; import { ContainerNormalizedConfig } from '@cloudflare/containers-shared'; import { Rpc, ExportedHandler, D1Database, Workflow, Service } from '@cloudflare/workers-types'; import { FetcherScheduledOptions, FetcherScheduledResult, IncomingRequestCfProperties } from '@cloudflare/workers-types/experimental'; import { RouterConfig, AssetConfig } from '@cloudflare/workers-shared'; export { printBindings as unstable_printBindings } from '@cloudflare/deploy-helpers'; import { URLSearchParams } from 'node:url'; import { Argv, PositionalOptions, Options, ArgumentsCamelCase, InferredOptionTypes, InferredOptionType } from 'yargs'; import Cloudflare from 'cloudflare'; interface EnablePagesAssetsServiceBindingOptions { proxyPort?: number; directory?: string; } interface Unstable_DevOptions { config?: string; env?: string; envFiles?: string[]; ip?: string; port?: number; bundle?: boolean; inspectorPort?: number; localProtocol?: "http" | "https"; httpsKeyPath?: string; httpsCertPath?: string; assets?: string; site?: string; siteInclude?: string[]; siteExclude?: string[]; compatibilityDate?: string; compatibilityFlags?: string[]; persist?: boolean; persistTo?: string; vars?: Record; kv?: { binding: string; id?: string; preview_id?: string; remote?: boolean; }[]; durableObjects?: { name: string; class_name: string; script_name?: string | undefined; environment?: string | undefined; }[]; services?: { binding: string; service: string; environment?: string | undefined; entrypoint?: string | undefined; remote?: boolean; }[]; r2?: { binding: string; bucket_name?: string; preview_bucket_name?: string; remote?: boolean; }[]; ai?: { binding: string; }; version_metadata?: { binding: string; }; moduleRoot?: string; rules?: Rule$1[]; logLevel?: "none" | "info" | "error" | "log" | "warn" | "debug"; inspect?: boolean; local?: boolean; accountId?: string; experimental?: { processEntrypoint?: boolean; additionalModules?: CfModule[]; d1Databases?: Environment$1["d1_databases"]; disableExperimentalWarning?: boolean; disableDevRegistry?: boolean; enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions; forceLocal?: boolean; liveReload?: boolean; showInteractiveDevSession?: boolean; testScheduled?: boolean; watch?: boolean; fileBasedRegistry?: boolean; enableIpc?: boolean; enableContainers?: boolean; dockerPath?: string; containerEngine?: string; }; } interface Unstable_DevWorker { port: number; address: string; stop: () => Promise; fetch: (input?: RequestInfo, init?: RequestInit) => Promise; waitUntilExit: () => Promise; } /** * unstable_dev starts a wrangler dev server, and returns a promise that resolves with utility functions to interact with it. */ declare function unstable_dev(script: string, options?: Unstable_DevOptions, apiOptions?: unknown): Promise; interface PagesDeployOptions { /** * Path to static assets to deploy to Pages */ directory: string; /** * The Cloudflare Account ID that owns the project that's * being published */ accountId: string; /** * The name of the project to be published */ projectName: string; /** * Branch name to use. Defaults to production branch */ branch?: string; /** * Whether or not to skip local file upload result caching */ skipCaching?: boolean; /** * Commit message associated to deployment */ commitMessage?: string; /** * Commit hash associated to deployment */ commitHash?: string; /** * Whether or not the deployment should be considered to be * in a dirty commit state */ commitDirty?: boolean; /** * Path to the project's functions directory. Default uses * the current working directory + /functions since this is * typically called in a CLI */ functionsDirectory?: string; /** * Whether to run bundling on `_worker.js` before deploying. * Default: true */ bundle?: boolean; /** * Whether to upload any server-side sourcemaps with this deployment */ sourceMaps: boolean; /** * Command line args passed to the `pages deploy` cmd */ args?: Record; } /** * Publish a directory to an account/project. * NOTE: You will need the `CLOUDFLARE_API_KEY` environment * variable set */ declare function deploy({ directory, accountId, projectName, branch, skipCaching, commitMessage, commitHash, commitDirty, functionsDirectory: customFunctionsDirectory, bundle, sourceMaps, args, }: PagesDeployOptions): Promise<{ deploymentResponse: { id: string; url: string; environment: "production" | "preview"; build_config: { build_command: string; destination_dir: string; root_dir: string; web_analytics_tag?: string | undefined; web_analytics_token?: string | undefined; fast_builds?: boolean | undefined; }; created_on: string; production_branch: string; project_id: string; project_name: string; deployment_trigger: { type: string; metadata: { branch: string; commit_hash: string; commit_message: string; }; }; latest_stage: { status: "skipped" | "active" | "canceled" | "success" | "idle" | "failure"; name: "queued" | "build" | "deploy" | "initialize" | "clone_repo"; started_on: string | null; ended_on: string | null; }; stages: { status: "skipped" | "active" | "canceled" | "success" | "idle" | "failure"; name: "queued" | "build" | "deploy" | "initialize" | "clone_repo"; started_on: string | null; ended_on: string | null; }[]; aliases: string[]; modified_on: string; short_id: string; build_image_major_version: number; source?: { type: "github" | "gitlab"; config: { owner: string; repo_name: string; production_branch?: string | undefined; pr_comments_enabled?: boolean | undefined; deployments_enabled?: boolean | undefined; production_deployments_enabled?: boolean | undefined; preview_deployment_setting?: "custom" | "none" | "all" | undefined; preview_branch_includes?: string[] | undefined; preview_branch_excludes?: string[] | undefined; }; } | undefined; kv_namespaces?: any; env_vars?: any; durable_object_namespaces?: any; is_skipped?: boolean | undefined; files?: { [x: string]: string | undefined; } | undefined; }; formData: FormData; }>; declare const unstable_pages: { deploy: typeof deploy; }; interface GenerateTypesOptions { /** * Path to the Wrangler config file to use. Can be an array for multi-config type resolution. */ config?: string | string[]; /** * Name of the Wrangler environment to generate types for. */ env?: string; /** * Paths to `.env` files to load when inferring local variables and secrets. */ envFile?: string[]; /** * Name of the generated environment interface. */ envInterface?: string; /** * Whether to include environment/bindings types in the output. */ includeEnv?: boolean; /** * Whether to include runtime types in the output. */ includeRuntime?: boolean; /** * Path to the declaration file for generated types. */ path?: string; /** * Whether to generate strict literal/union variable types. */ strictVars?: boolean; } type Experimental_GenerateTypesOptions = GenerateTypesOptions; interface GenerateTypesResult { /** * Combined formatted output containing all generated sections. */ content: string; /** * Generated environment/bindings types, or `null` when env types are excluded. */ env: string | null; /** * Target declaration file path associated with this generation run. */ path: string; /** * Generated runtime types, or `null` when runtime types are excluded. */ runtime: string | null; } type Experimental_GenerateTypesResult = GenerateTypesResult; /** * Generate types from your Worker configuration * * @description Programmatically generate TypeScript type definitions for your * Worker, using the same logic that powers the `wrangler types` CLI command. * * @param options - Type generation configuration options that mirror the `wrangler types` CLI flags * * @returns Structured output containing combined content & split env/runtime sections. */ declare function generateTypes(options: Experimental_GenerateTypesOptions): Promise; type _Params = ParamsArray extends [infer P] ? P : undefined; type _EventMethods = keyof Protocol.Events; type DevToolsEvent = Method extends unknown ? { method: Method; params: _Params; } : never; /** * Information about Wrangler's bundling process that needs passed through * for DevTools sourcemap transformation */ interface SourceMapMetadata { tmpDir: string; entryDirectory: string; } type EsbuildBundle = { id: number; path: string; entrypointSource: string; entry: Entry; type: CfModuleType; modules: CfModule[]; dependencies: Metafile["outputs"][string]["inputs"]; sourceMapPath: string | undefined; sourceMapMetadata: SourceMapMetadata | undefined; }; declare class ConfigController extends Controller { #private; latestInput?: StartDevWorkerInput; latestWranglerConfig?: Config$1; latestConfig?: StartDevWorkerOptions; set(input: StartDevWorkerInput, throwErrors?: boolean): Promise; patch(input: Partial): Promise; onDevRegistryUpdate(event: DevRegistryUpdateEvent): void; teardown(): Promise; emitConfigUpdateEvent(config: StartDevWorkerOptions): void; } type MiniflareWorker = Awaited>; interface Worker { ready: Promise; url: Promise; inspectorUrl: Promise; config: StartDevWorkerOptions; setConfig: ConfigController["set"]; patchConfig: ConfigController["patch"]; fetch: DispatchFetch; scheduled: MiniflareWorker["scheduled"]; queue: MiniflareWorker["queue"]; dispose(): Promise; raw: DevEnv; } type StartDevWorkerOptions = Omit & { /** The configuration path of the worker */ config?: string; /** A worker's directory. Usually where the Wrangler configuration file is located */ projectRoot: string; build: StartDevWorkerInput["build"] & { nodejsCompatMode: NodeJSCompatMode; format: CfScriptFormat; moduleRoot: string; moduleRules: Rule$1[]; define: Record; additionalModules: CfModule[]; exports: string[]; processEntrypoint: boolean; }; legacy: StartDevWorkerInput["legacy"] & { site?: Config$1["site"]; }; dev: StartDevWorkerInput["dev"] & { persist: string | false; auth?: AsyncHook; /** Handles structured runtime logs. */ structuredLogsHandler?: (log: WorkerdStructuredLog) => void; /** An undici MockAgent to declaratively mock fetch calls to particular resources. */ mockFetch?: undici.MockAgent; }; entrypoint: string; assets?: AssetsOptions$1; containers?: ContainerNormalizedConfig[]; name: string; complianceRegion: Config$1["compliance_region"]; }; type Bundle = EsbuildBundle; type ErrorEvent = BaseErrorEvent<"ConfigController" | "BundlerController" | "LocalRuntimeController" | "RemoteRuntimeController" | "ProxyWorker" | "InspectorProxyWorker" | "MultiworkerRuntimeController"> | BaseErrorEvent<"ProxyController", { config?: StartDevWorkerOptions; bundle?: Bundle; }> | BaseErrorEvent<"BundlerController", { config?: StartDevWorkerOptions; filePath?: string; }>; type BaseErrorEvent = { type: "error"; reason: string; cause: Error | SerializedError; source: Source; data: Data; }; type ConfigUpdateEvent = { type: "configUpdate"; config: StartDevWorkerOptions; }; type BundleStartEvent = { type: "bundleStart"; config: StartDevWorkerOptions; }; type BundleCompleteEvent = { type: "bundleComplete"; config: StartDevWorkerOptions; bundle: Bundle; }; type ReloadStartEvent = { type: "reloadStart"; config: StartDevWorkerOptions; bundle: Bundle; }; type ReloadCompleteEvent = { type: "reloadComplete"; config: StartDevWorkerOptions; bundle: Bundle; proxyData: ProxyData; }; type DevRegistryUpdateEvent = { type: "devRegistryUpdate"; registry: WorkerRegistry; }; type PreviewTokenExpiredEvent = { type: "previewTokenExpired"; proxyData: ProxyData; }; type ReadyEvent = { type: "ready"; proxyWorker: Miniflare; url: URL; inspectorUrl: URL | undefined; }; type ProxyWorkerIncomingRequestBody = { type: "play"; proxyData: ProxyData; } | { type: "pause"; }; type ProxyWorkerOutgoingRequestBody = { type: "error"; error: SerializedError; } | { type: "sseResponseDetected"; } | { type: "previewTokenExpired"; proxyData: ProxyData; } | { type: "debug-log"; args: Parameters; }; type InspectorProxyWorkerIncomingWebSocketMessage = { type: ReloadStartEvent["type"]; } | { type: ReloadCompleteEvent["type"]; proxyData: ProxyData; }; type InspectorProxyWorkerOutgoingWebsocketMessage = DevToolsEvent<"Runtime.consoleAPICalled"> | DevToolsEvent<"Runtime.exceptionThrown">; type InspectorProxyWorkerOutgoingRequestBody = { type: "error"; error: SerializedError; } | { type: "runtime-websocket-error"; error: SerializedError; } | { type: "debug-log"; args: Parameters; } | { type: "load-network-resource"; url: string; }; type SerializedError = { message: string; name?: string; stack?: string | undefined; cause?: unknown; }; type UrlOriginParts = Pick; type UrlOriginAndPathnameParts = Pick; type ProxyData = { userWorkerUrl: UrlOriginParts; userWorkerInspectorUrl?: UrlOriginAndPathnameParts; userWorkerInnerUrlOverrides?: Partial; headers: Record; liveReload?: boolean; proxyLogsToController?: boolean; }; type ControllerEvent = ErrorEvent | ConfigUpdateEvent | BundleStartEvent | BundleCompleteEvent | ReloadStartEvent | ReloadCompleteEvent | DevRegistryUpdateEvent | PreviewTokenExpiredEvent; interface ControllerBus { dispatch(event: ControllerEvent): void; } declare abstract class Controller { #private; protected bus: ControllerBus; constructor(bus: ControllerBus); teardown(): Promise; protected emitErrorEvent(event: ErrorEvent): void; } declare abstract class RuntimeController extends Controller { abstract onBundleStart(_: BundleStartEvent): void; abstract onBundleComplete(_: BundleCompleteEvent): void; abstract onPreviewTokenExpired(_: PreviewTokenExpiredEvent): void; abstract get mf(): Miniflare | undefined; protected emitReloadStartEvent(data: ReloadStartEvent): void; protected emitReloadCompleteEvent(data: ReloadCompleteEvent): void; protected emitDevRegistryUpdateEvent(data: DevRegistryUpdateEvent): void; } declare class BundlerController extends Controller { #private; onConfigUpdate(event: ConfigUpdateEvent): void; teardown(): Promise; emitBundleStartEvent(config: StartDevWorkerOptions): void; emitBundleCompleteEvent(config: StartDevWorkerOptions, bundle: EsbuildBundle): void; } type MaybePromise = T | Promise; type DeferredPromise = { promise: Promise; resolve: (_: MaybePromise) => void; reject: (_: Error) => void; }; declare class ProxyController extends Controller { ready: DeferredPromise; localServerReady: DeferredPromise; proxyWorker?: Miniflare; proxyWorkerOptions?: MiniflareOptions; private inspectorProxyWorkerWebSocket?; protected latestConfig?: StartDevWorkerOptions; protected latestBundle?: EsbuildBundle; secret: `${string}-${string}-${string}-${string}-${string}`; protected createProxyWorker(): void; private reconnectInspectorProxyWorker; runtimeMessageMutex: Mutex; sendMessageToProxyWorker(message: ProxyWorkerIncomingRequestBody, retries?: number): Promise; sendMessageToInspectorProxyWorker(message: InspectorProxyWorkerIncomingWebSocketMessage, retries?: number): Promise; get inspectorEnabled(): boolean; onConfigUpdate(data: ConfigUpdateEvent): void; onBundleStart(data: BundleStartEvent): void; onReloadStart(data: ReloadStartEvent): void; onReloadComplete(data: ReloadCompleteEvent): void; onProxyWorkerMessage(message: ProxyWorkerOutgoingRequestBody): void; onInspectorProxyWorkerMessage(message: InspectorProxyWorkerOutgoingWebsocketMessage): void; onInspectorProxyWorkerRequest(message: InspectorProxyWorkerOutgoingRequestBody): Promise; _torndown: boolean; teardown(): Promise; emitReadyEvent(proxyWorker: Miniflare, url: URL, inspectorUrl: URL | undefined): void; emitPreviewTokenExpiredEvent(proxyData: ProxyData): void; emitErrorEvent(data: ErrorEvent): void; emitErrorEvent(reason: string, cause?: Error | SerializedError): void; } type ControllerFactory = (devEnv: DevEnv) => C; declare class DevEnv extends EventEmitter implements ControllerBus { config: ConfigController; bundler: BundlerController; runtimes: RuntimeController[]; proxy: ProxyController; startWorker(options: StartDevWorkerInput): Promise; constructor({ configFactory, bundlerFactory, runtimeFactories, proxyFactory, }?: { configFactory?: ControllerFactory; bundlerFactory?: ControllerFactory; runtimeFactories?: ControllerFactory[]; proxyFactory?: ControllerFactory; }); /** * Central message bus dispatch method. * All events from controllers flow through here, making the event routing explicit and traceable. * * Event flow: * - ConfigController emits configUpdate → BundlerController, ProxyController * - BundlerController emits bundleStart → ProxyController, RuntimeControllers * - BundlerController emits bundleComplete → RuntimeControllers * - RuntimeController emits reloadStart → ProxyController * - RuntimeController emits reloadComplete → ProxyController * - RuntimeController emits devRegistryUpdate → ConfigController * - ProxyController emits previewTokenExpired → RuntimeControllers * - Any controller emits error → DevEnv error handler * * `reloadComplete` is also re-emitted as an external EventEmitter event * (`devEnv.on("reloadComplete", ...)`) so callers like * `RemoteProxySession.updateBindings` can wait for the reload to finish. */ dispatch(event: ControllerEvent): void; private handleErrorEvent; teardown(): Promise; } declare function startWorker(options: StartDevWorkerInput): Promise; declare const dev: { args: { v: boolean | undefined; cwd: string | undefined; config: string | undefined; env: string | undefined; envFile: string[] | undefined; experimentalProvision: boolean | undefined; experimentalAutoCreate: boolean; installSkills: boolean; profile: string | undefined; script: string | undefined; name: string | undefined; compatibilityDate: string | undefined; compatibilityFlags: string[] | undefined; latest: boolean; assets: string | undefined; bundle: boolean | undefined; noBundle: boolean; ip: string | undefined; port: number | undefined; inspectorPort: number | undefined; inspectorIp: string | undefined; routes: string[] | undefined; host: string | undefined; localProtocol: "http" | "https" | undefined; httpsKeyPath: string | undefined; httpsCertPath: string | undefined; localUpstream: string | undefined; enableContainers: boolean | undefined; site: string | undefined; siteInclude: string[] | undefined; siteExclude: string[] | undefined; upstreamProtocol: "http" | "https" | undefined; var: string[] | undefined; define: string[] | undefined; alias: string[] | undefined; jsxFactory: string | undefined; jsxFragment: string | undefined; tsconfig: string | undefined; remote: boolean; local: boolean | undefined; minify: boolean | undefined; nodeCompat: boolean | undefined; persistTo: string | undefined; liveReload: boolean | undefined; legacyEnv: boolean | undefined; testScheduled: boolean; logLevel: "debug" | "none" | "error" | "log" | "info" | "warn" | undefined; showInteractiveDevSession: boolean | undefined; types: boolean | undefined; tunnel: boolean | undefined; tunnelName: string | undefined; experimentalNewConfig: boolean; _: (string | number)[]; $0: string; }; }; type AdditionalDevProps = { /** * Default vars that can be overridden by config vars. * Useful for injecting environment-specific defaults like CF_PAGES variables. */ defaultBindings?: Record>; vars?: Record; kv?: { binding: string; id?: string; preview_id?: string; }[]; durableObjects?: { name: string; class_name: string; script_name?: string | undefined; environment?: string | undefined; }[]; services?: { binding: string; service: string; environment?: string; entrypoint?: string; }[]; r2?: { binding: string; bucket_name?: string; preview_bucket_name?: string; jurisdiction?: string; }[]; ai?: { binding: string; }; stream?: { binding: string; remote?: boolean; }; version_metadata?: { binding: string; }; d1Databases?: Array & { database_id?: string; }>; processEntrypoint?: boolean; additionalModules?: CfModule[]; moduleRoot?: string; rules?: Rule$1[]; showInteractiveDevSession?: boolean; }; type DevArguments = Omit<(typeof dev)["args"], "installSkills" | "profile">; type StartDevOptions = DevArguments & AdditionalDevProps & { forceLocal?: boolean; accountId?: string; disableDevRegistry?: boolean; enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions; onReady?: (ip: string, port: number) => void; enableIpc?: boolean; dockerPath?: string; containerEngine?: string; /** Set to `false` to disable persistence. When `true` or `undefined`, uses default persistence path. */ persist?: boolean; }; declare function convertConfigBindingsToStartWorkerBindings(configBindings: Partial>): StartDevWorkerOptions["bindings"]; type WorkflowStepSelector = { name: string; index?: number; }; type WorkflowInstanceModifier = { disableSleeps(steps?: WorkflowStepSelector[]): Promise; disableRetryDelays(steps?: WorkflowStepSelector[]): Promise; mockStepResult(step: WorkflowStepSelector, stepResult: unknown): Promise; mockStepError(step: WorkflowStepSelector, error: Error, times?: number): Promise; forceStepTimeout(step: WorkflowStepSelector, times?: number): Promise; mockEvent(event: { type: string; payload: unknown; }): Promise; forceEventTimeout(step: WorkflowStepSelector): Promise; }; type ModifierCallback = (modifier: WorkflowInstanceModifier) => Promise; interface WorkflowInstanceIntrospector { modify(fn: ModifierCallback): Promise; waitForStepResult(step: WorkflowStepSelector): Promise; waitForStatus(status: string): Promise; getOutput(): Promise; getError(): Promise<{ name: string; message: string; }>; dispose(): Promise; [Symbol.asyncDispose](): Promise; } interface WorkflowIntrospector { modifyAll(fn: ModifierCallback): Promise; get(): Promise; dispose(): Promise; [Symbol.asyncDispose](): Promise; } type TestHarnessOptions = { /** * Base directory used to resolve relative worker config paths. * Defaults to `process.cwd()`. */ root?: string | undefined; /** * Workers to run in this server. The first worker is the primary worker. */ workers: WorkerInput[]; }; type BindingName = string extends keyof Env ? string : Extract<{ [K in keyof Env]-?: NonNullable extends Type ? K : never; }[keyof Env], string>; type WorkerModule = { default: WorkerExport; [key: string]: WorkerExport | undefined; }; type AnyExportedHandler = ExportedHandler; type AnyEnv = Record; type WorkerExport = (new (...args: any[]) => Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | AnyExportedHandler; type WorkerHandle = { /** * Dispatches a fetch event directly to this worker. * Relative URL inputs are resolved against the URL returned by `listen()`. * * @example * ```ts * const response = await worker.fetch("/", { * method: "POST", * body: "Hello, world!" * }); * ``` */ fetch: DispatchFetch; /** * Dispatches a scheduled event directly to this Worker. * * @example * ```ts * const result = await worker.scheduled({ * cron: "0 * * * *", * scheduledTime: new Date(), * }); * ``` */ scheduled(options: FetcherScheduledOptions): Promise; /** * Returns the full environment object configured on this Worker, including * vars, secrets, and bindings. * * @example * ```ts * type Env = { GREETING: string; STORE: KVNamespace }; * const worker = server.getWorker(); * const env = await worker.getEnv(); * await env.STORE.put("key", env.GREETING); * ``` */ getEnv(): Promise; /** * Applies D1 migration files that have not already run to a D1 binding on this Worker. * * @example * ```ts * beforeEach(async () => { * await worker.applyD1Migrations("DATABASE"); * }); * ``` */ applyD1Migrations(bindingName: BindingName): Promise; /** * Creates an introspector for a specific Workflow instance. */ introspectWorkflowInstance(bindingName: BindingName, instanceId: string): Promise; /** * Creates an introspector for Workflow instances created after this method is called. */ introspectWorkflow(bindingName: BindingName): Promise; /** * Returns the default Worker export, including JSRPC methods. * * @example * ```ts * type ApiWorkerModule = typeof import("../src/api-worker"); * * const worker = server.getWorker("api-worker"); * const api = await worker.getExport(); * api.getMessage(); * ``` */ getExport(): Promise>; }; type TestHarness = { /** * Starts the server and returns its current URL. * Calling this more than once returns the same running server session until * the server is closed or reset. * * If no options were passed to `createTestHarness()`, call `update(options)` * before starting the server. */ listen(): Promise<{ url: URL; }>; /** * Dispatches a fetch request through the server. * * - Relative URLs are resolved against the current server URL. Absolute URLs * are also accepted, and can be used to control the hostname seen by the Worker. * - Requests are matched against each Worker's configured routes and dispatched to * the first matching Worker, or to the primary Worker if no routes match. * - To dispatch directly to a specific Worker, use `server.getWorker(name).fetch()`. * * @example * ```ts * const server = createTestHarness({ * workers: [ * { configPath: "./wrangler.dashboard.jsonc" }, // No route pattern * { configPath: "./wrangler.api.jsonc" }, // Route pattern: "example.com/api/*" * { configPath: "./wrangler.admin.jsonc" }, // Route pattern: "admin.example.com/*" * ] * }); * * await server.fetch("/users"); * // Dispatches a request to the dashboard Worker (the first Worker) with URL "http://localhost:{port}/users" * * await server.fetch("http://admin.example.com/accounts"); * // Dispatches a request to the admin Worker with URL "http://admin.example.com/accounts" * * await server.fetch("http://example.com/api/data"); * // Dispatches a request to the API Worker with URL "http://example.com/api/data" * ``` */ fetch: DispatchFetch; /** * Returns a handle for dispatching events directly to a Worker. * When no name is provided, this returns the primary Worker, which is the first * Worker in the server's `workers` options. */ getWorker(name?: string): WorkerHandle; /** * Returns captured Workers runtime logs since the current server session * started or `clearLogs()` was last called. */ getLogs(): WorkerdStructuredLog[]; /** * Clears captured Workers runtime logs. */ clearLogs(): void; /** * Prints a diagnostic timeline for this test server. * * Use this to trace the sequence of server events and Workers runtime logs * leading up to a test failure. Call `server.debug()` from your test runner's * failure or cleanup hook when the current test has failed. */ debug(): void; /** * Updates the server configuration and reloads the running Workers. * * If the server has not started yet, this configures the options that will be * used by `listen()`. */ update(options: TestHarnessOptions | ((currentOptions: TestHarnessOptions) => TestHarnessOptions)): Promise; /** * Restores the server to the options used when the current session first * started. Storage is recreated, and the server URL may change after reset. */ reset(): Promise; /** * Stops the server and releases all runtime resources. */ close(): Promise; }; type InlineConfig = Omit; type WorkerInput = { /** * Path to a Wrangler config file for this Worker. * Relative paths resolve from server `root`. */ configPath: string | URL; /** * Wrangler environment to load from the config file. */ env?: string; /** * Test-only vars that override vars from the Wrangler config. */ vars?: Record; /** * Test-only secrets that override values loaded from `.dev.vars` and `.env` files. */ secrets?: Record; /** * Test-only service binding overrides. Keys are binding names in this * Worker's environment, and values are Worker names in this test harness. */ bindingOverrides?: Record; } | { /** * Inline Wrangler config for this Worker. */ config: InlineConfig; }; /** * Creates a local test server for running Workers. * * The server can run one or more Workers from Wrangler config files, including * generated configs from Vite, or from inline configuration objects. * * @example * ```ts * const server = createTestHarness({ * workers: [{ configPath: "./wrangler.jsonc" }], * }); * await server.listen(); * const response = await server.fetch("/api/users"); * await server.close(); * ``` */ declare function createTestHarness(options?: TestHarnessOptions): TestHarness; type ReadConfigCommandArgs = NormalizeAndValidateConfigArgs & { config?: string; script?: string; }; type ReadConfigOptions = ResolveConfigPathOptions & { hideWarnings?: boolean; preserveOriginalMain?: boolean; }; /** * Get the Wrangler configuration; read it from the give `configPath` if available. */ declare function readConfig(args: ReadConfigCommandArgs, options?: ReadConfigOptions): Config$1; /** * Infer Durable Object class names and storage backends from migrations and * live declarative `exports` entries. * * In practice only one of `migrations` or `exports` will have the Durable Object configuration. */ declare function getDurableObjectClassNameToUseSQLiteMap(migrations: Config$1["migrations"] | undefined, exports?: Config$1["exports"] | undefined): Map; /** * Note about this file: * * Here we are providing a no-op implementation of the runtime Cache API instead of using * the miniflare implementation (via `mf.getCaches()`). * * We are not using miniflare's implementation because that would require the user to provide * miniflare-specific Request objects and they would receive back miniflare-specific Response * objects, this (in particular the Request part) is not really suitable for `getPlatformProxy` * as people would ideally interact with their bindings in a very production-like manner and * requiring them to deal with miniflare-specific classes defeats a bit the purpose of the utility. * * Similarly the Request and Response types here are set to `undefined` as not to use specific ones * that would require us to make a choice right now or the user to adapt their code in order to work * with the api. * * We need to find a better/generic manner in which we can reuse the miniflare cache implementation, * but until then the no-op implementation below will have to do. */ /** * No-op implementation of CacheStorage */ declare class CacheStorage { constructor(); open(_cacheName: string): Promise; get default(): Cache; } type CacheRequest = any; type CacheResponse = any; /** * No-op implementation of Cache */ declare class Cache { delete(_request: CacheRequest, _options?: CacheQueryOptions): Promise; match(_request: CacheRequest, _options?: CacheQueryOptions): Promise; put(_request: CacheRequest, _response: CacheResponse): Promise; } type CacheQueryOptions = { ignoreMethod?: boolean; }; declare class ExecutionContext { waitUntil(promise: Promise): void; passThroughOnException(): void; props: any; } type Json = string | number | boolean | null | Json[] | { [id: string]: Json; }; type AssetsOptions = { directory: string; binding?: string; routerConfig: RouterConfig; assetConfig: AssetConfig; _redirects?: string; _headers?: string; run_worker_first?: boolean | string[]; }; /** * Wrangler configuration types. The JSDoc on these fields is also the source * of truth for the equivalent fields in `@cloudflare/config` * (`packages/config/src/types.ts` — `UserConfig` — and the binding option * interfaces in `packages/config/src/config.ts`). When editing prose here, * mirror the changes there. */ /** * The `Environment` interface declares all the configuration fields that * can be specified for an environment. * * This could be the top-level default environment, or a specific named environment. */ interface Environment extends EnvironmentInheritable, EnvironmentNonInheritable { } type SimpleRoute = string; type ZoneIdRoute = { pattern: string; zone_id: string; custom_domain?: boolean; }; type ZoneNameRoute = { pattern: string; zone_name: string; custom_domain?: boolean; }; type CustomDomainRoute = { pattern: string; custom_domain: boolean; enabled?: boolean; previews_enabled?: boolean; }; type Route = SimpleRoute | ZoneIdRoute | ZoneNameRoute | CustomDomainRoute; /** * Configuration in wrangler for Cloudchamber */ type CloudchamberConfig = { image?: string; location?: string; instance_type?: "dev" | "basic" | "standard" | "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4"; vcpu?: number; memory?: string; ipv4?: boolean; }; type UnsafeBinding = { /** * The name of the binding provided to the Worker */ name: string; /** * The 'type' of the unsafe binding. */ type: string; dev?: { plugin: { /** * Package is the bare specifier of the package that exposes plugins to integrate into Miniflare via a named `plugins` export. * @example "@cloudflare/my-external-miniflare-plugin" */ package: string; /** * Plugin is the name of the plugin exposed by the package. * @example "MY_UNSAFE_PLUGIN" */ name: string; }; /** * Optional mapping of unsafe bindings names to options provided for the plugin. */ options?: Record; }; [key: string]: unknown; }; /** * Configuration for a container application */ type ContainerApp = { /** * Name of the application * @optional Defaults to `worker_name-class_name` if not specified. */ name?: string; /** * Number of application instances * @deprecated * @hidden */ instances?: number; /** * Number of maximum application instances. * @optional */ max_instances?: number; /** * The path to a Dockerfile, or an image URI for the Cloudflare registry. */ image: string; /** * Build context of the application. * @optional - defaults to the directory of `image`. */ image_build_context?: string; /** * Image variables available to the image at build-time only. * For runtime env vars, refer to https://developers.cloudflare.com/containers/examples/env-vars-and-secrets/ * @optional */ image_vars?: Record; /** * The class name of the Durable Object the container is connected to. */ class_name: string; /** * The scheduling policy of the application * @optional * @default "default" */ scheduling_policy?: "default" | "moon" | "regional"; /** * The instance type to be used for the container. * Select from one of the following named instance types: * - lite: 1/16 vCPU, 256 MiB memory, and 2 GB disk * - basic: 1/4 vCPU, 1 GiB memory, and 4 GB disk * - standard-1: 1/2 vCPU, 4 GiB memory, and 8 GB disk * - standard-2: 1 vCPU, 6 GiB memory, and 12 GB disk * - standard-3: 2 vCPU, 8 GiB memory, and 16 GB disk * - standard-4: 4 vCPU, 12 GiB memory, and 20 GB disk * - dev: 1/16 vCPU, 256 MiB memory, and 2 GB disk (deprecated, use "lite" instead) * - standard: 1 vCPU, 4 GiB memory, and 4 GB disk (deprecated, use "standard-1" instead) * * Customers on an enterprise plan have the additional option to set custom limits. * * @optional * @default "dev" */ instance_type?: "dev" | "basic" | "standard" | "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4" | { /** @defaults to 0.0625 (1/16 vCPU) */ vcpu?: number; /** @defaults to 256 MiB */ memory_mib?: number; /** @defaults to 2 GB */ disk_mb?: number; }; ssh?: { /** * If enabled, those with write access to a container will be able to SSH into it through Wrangler. * @default false */ enabled: boolean; /** * Port that the SSH service is running on * @defaults to 22 */ port?: number; }; /** * @deprecated Use `ssh` instead. * @hidden */ wrangler_ssh?: { enabled: boolean; port?: number; }; /** * SSH public keys to put in the container's authorized_keys file. */ authorized_keys?: { name: string; public_key: string; }[]; /** * Trusted user CA keys to put in the container's trusted_user_ca_keys file. */ trusted_user_ca_keys?: { name?: string; public_key: string; }[]; /** * @deprecated Use top level `containers` fields instead. * `configuration.image` should be `image` * limits should be set via `instance_type` * @hidden */ configuration?: { image?: string; labels?: { name: string; value: string; }[]; secrets?: { name: string; type: "env"; secret: string; }[]; disk?: { size_mb: number; }; vcpu?: number; memory_mib?: number; }; /** * Scheduling constraints for container placement. */ constraints?: { /** * Limit container placement to specific geographic regions. */ regions?: ("ENAM" | "WNAM" | "EEUR" | "WEUR" | "APAC" | "SAM" | "ME" | "OC" | "AFR")[]; /** * Restrict containers to compliance boundaries. */ jurisdiction?: "eu" | "fedramp"; /** * @hidden */ cities?: string[]; /** * @deprecated Use `tiers` instead * @hidden */ tier?: number; /** * @hidden */ tiers?: number[]; }; /** * Scheduling affinities * @hidden */ affinities?: { colocation?: "datacenter"; hardware_generation?: "highest-overall-performance"; }; /** * @deprecated use the `class_name` field instead. * @hidden */ durable_objects?: { namespace_id: string; }; /** * Configures what percentage of instances should be updated at each step of a rollout. * You can specify this as a single number, or an array of numbers. * * If this is a single number, each step will progress by that percentage. * The options are 5, 10, 20, 25, 50 or 100. * * If this is an array, each step specifies the cumulative rollout progress. * The final step must be 100. * * This can be overridden adhoc by deploying with the `--containers-rollout=immediate` flag, * which will roll out to 100% of instances in one step. * * @optional * @default [10,100] * */ rollout_step_percentage?: number | number[]; /** * How a rollout should be created. It supports the following modes: * - full_auto: The container application will be rolled out fully automatically. * - none: The container application won't have a roll out or update. * - manual: The container application will be rollout fully by manually actioning progress steps. * @optional * @default "full_auto" * @hidden */ rollout_kind?: "full_auto" | "none" | "full_manual"; /** * Configures the grace period (in seconds) for active instances before being shutdown during a rollout. * @optional * @default 0 */ rollout_active_grace_period?: number; /** * Directly passed to the API without wrangler-side validation or transformation. * @hidden */ unsafe?: Record; }; /** * Configuration in wrangler for Durable Object Migrations */ type DurableObjectMigration = { /** A unique identifier for this migration. */ tag: string; /** The new Durable Objects being defined. */ new_classes?: string[]; /** The new SQLite Durable Objects being defined. */ new_sqlite_classes?: string[]; /** The Durable Objects being renamed. */ renamed_classes?: { from: string; to: string; }[]; /** The Durable Objects being removed. */ deleted_classes?: string[]; }; /** * Storage backend for a declarative Durable Object export. See * {@link DurableObjectExport}. */ type DurableObjectExportStorage = "sqlite" | "legacy-kv"; /** * A single declarative Durable Object export entry in the `exports` config * map. `type` is reserved for the export kind. `state` carries the Durable * Object lifecycle and defaults to `"created"` (live) when omitted. * * Mutually exclusive with {@link DurableObjectMigration} at the config- * validation boundary. * * - `created` (default, live): `storage` is required. * - `deleted` (tombstone): retire a provisioned namespace whose class has * been removed from code. * - `renamed` (tombstone): rewrite a provisioned namespace's class name to * `renamed_to`. The target name must also appear as a live (state * `"created"`) `durable-object` entry in the same map. * - `transferred` (tombstone): hand ownership of the namespace to another * script in the same account (`transferred_to`). Two-phase commit; * the target must first deploy an `expecting-transfer` entry naming this * script via `transfer_from`. * - `expecting-transfer` (live): receiving side of a two-phase transfer; * `storage` and `transfer_from` are both required. */ type DurableObjectExport = { type: "durable-object"; state?: "created"; storage: DurableObjectExportStorage; } | { type: "durable-object"; state: "deleted"; } | { type: "durable-object"; state: "renamed"; renamed_to: string; } | { type: "durable-object"; state: "transferred"; transferred_to: string; } | { type: "durable-object"; state: "expecting-transfer"; storage: DurableObjectExportStorage; transfer_from: string; }; interface WorkerEntrypointExport { type: "worker"; cache?: { /** Whether cache is enabled for this entrypoint. */ enabled: boolean; }; } type ConfiguredExport = DurableObjectExport | WorkerEntrypointExport; /** * The declarative `exports` map keyed by export name. Durable Object exports * are mutually exclusive with `migrations` at the wrangler config layer. */ type Exports = Record; /** * The `EnvironmentInheritable` interface declares all the configuration fields for an environment * that can be inherited (and overridden) from the top-level environment. */ interface EnvironmentInheritable { /** * The name of your Worker. Alphanumeric + dashes only. * * @inheritable */ name: string | undefined; /** * This is the ID of the account associated with your zone. * You might have more than one account, so make sure to use * the ID of the account associated with the zone/route you * provide, if you provide one. It can also be specified through * the CLOUDFLARE_ACCOUNT_ID environment variable. * * @inheritable */ account_id: string | undefined; /** * A date in the form yyyy-mm-dd, which will be used to determine * which version of the Workers runtime is used. * * More details at https://developers.cloudflare.com/workers/configuration/compatibility-dates * * @inheritable */ compatibility_date: string | undefined; /** * A list of flags that enable features from upcoming features of * the Workers runtime, usually used together with compatibility_date. * * More details at https://developers.cloudflare.com/workers/configuration/compatibility-flags/ * * @default [] * @inheritable */ compatibility_flags: string[]; /** * The entrypoint/path to the JavaScript file that will be executed. * * @inheritable */ main: string | undefined; /** * If true then Wrangler will traverse the file tree below `base_dir`; * Any files that match `rules` will be included in the deployed Worker. * Defaults to true if `no_bundle` is true, otherwise false. * * @inheritable */ find_additional_modules: boolean | undefined; /** * Determines whether Wrangler will preserve bundled file names. * Defaults to false. * If left unset, files will be named using the pattern ${fileHash}-${basename}, * for example, `34de60b44167af5c5a709e62a4e20c4f18c9e3b6-favicon.ico`. * * @inheritable */ preserve_file_names: boolean | undefined; /** * The directory in which module rules should be evaluated when including additional files into a Worker deployment. * This defaults to the directory containing the `main` entry point of the Worker if not specified. * * @inheritable */ base_dir: string | undefined; /** * Whether we use ..workers.dev to * test and deploy your Worker. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#workersdev * * @default true * @breaking * @inheritable */ workers_dev: boolean | undefined; /** * Whether we use -..workers.dev to * serve Preview URLs for your Worker. * * @default false * @inheritable */ preview_urls: boolean | undefined; /** * A list of routes that your Worker should be published to. * Only one of `routes` or `route` is required. * * Only required when workers_dev is false, and there's no scheduled Worker (see `triggers`) * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#types-of-routes * * @inheritable */ routes: Route[] | undefined; /** * A route that your Worker should be published to. Literally * the same as routes, but only one. * Only one of `routes` or `route` is required. * * Only required when workers_dev is false, and there's no scheduled Worker * * @inheritable */ route: Route | undefined; /** * Path to a custom tsconfig * * @inheritable */ tsconfig: string | undefined; /** * The function to use to replace jsx syntax. * * @default "React.createElement" * @inheritable */ jsx_factory: string; /** * The function to use to replace jsx fragment syntax. * * @default "React.Fragment" * @inheritable */ jsx_fragment: string; /** * A list of migrations that should be uploaded with your Worker. * * These define changes in your Durable Object declarations. * * More details at https://developers.cloudflare.com/workers/learning/using-durable-objects#configuring-durable-object-classes-with-migrations * * @default [] * @inheritable */ migrations: DurableObjectMigration[]; /** * Declarative exports configuration — a map of class name to export configuration. * * The configuration of Durable Objects via `exports` is mutually exclusive with `migrations`. * * @default {} * @inheritable */ exports: Exports; /** * "Cron" definitions to trigger a Worker's "scheduled" function. * * Lets you call Workers periodically, much like a cron job. * * More details here https://developers.cloudflare.com/workers/platform/cron-triggers * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#triggers * * @default {crons:[]} * @inheritable */ triggers: { crons: string[] | undefined; }; /** * Specify limits for runtime behavior. * Only supported for the "standard" Usage Model * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#limits * * @inheritable */ limits: UserLimits | undefined; /** * An ordered list of rules that define which modules to import, * and what type to import them as. You will need to specify rules * to use Text, Data, and CompiledWasm modules, or when you wish to * have a .js file be treated as an ESModule instead of CommonJS. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#bundling * * @inheritable */ rules: Rule[]; /** * Configures a custom build step to be run by Wrangler when building your Worker. * * Refer to the [custom builds documentation](https://developers.cloudflare.com/workers/cli-wrangler/configuration#build) * for more details. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#custom-builds * * @default {watch_dir:"./src"} */ build: { /** The command used to build your Worker. On Linux and macOS, the command is executed in the `sh` shell and the `cmd` shell for Windows. The `&&` and `||` shell operators may be used. */ command?: string; /** The directory in which the command is executed. */ cwd?: string; /** The directory to watch for changes while using wrangler dev, defaults to the current working directory */ watch_dir?: string | string[]; }; /** * Skip internal build steps and directly deploy script * @inheritable */ no_bundle: boolean | undefined; /** * Minify the script before uploading. * @inheritable */ minify: boolean | undefined; /** * Set the `name` property to the original name for functions and classes renamed during minification. * * See https://esbuild.github.io/api/#keep-names * * @default true * @inheritable */ keep_names: boolean | undefined; /** * Designates this Worker as an internal-only "first-party" Worker. * * @inheritable */ first_party_worker: boolean | undefined; /** * List of bindings that you will send to logfwdr * * @default {bindings:[]} * @inheritable */ logfwdr: { bindings: { /** The binding name used to refer to logfwdr */ name: string; /** The destination for this logged message */ destination: string; }[]; }; /** * Send Trace Events from this Worker to Workers Logpush. * * This will not configure a corresponding Logpush job automatically. * * For more information about Workers Logpush, see: * https://blog.cloudflare.com/logpush-for-workers/ * * @inheritable */ logpush: boolean | undefined; /** * Include source maps when uploading this worker. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#source-maps * * @inheritable */ upload_source_maps: boolean | undefined; /** * Specify how the Worker should be located to minimize round-trip time. * * More details: https://developers.cloudflare.com/workers/platform/smart-placement/ * * @inheritable */ placement: { mode: "off" | "smart"; hint?: string; } | { mode?: "targeted"; region: string; } | { mode?: "targeted"; host: string; } | { mode?: "targeted"; hostname: string; } | undefined; /** * Specify the directory of static assets to deploy/serve * * More details at https://developers.cloudflare.com/workers/frameworks/ * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#assets * * @inheritable */ assets: Assets | undefined; /** * Specify the observability behavior of the Worker. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#observability * * @inheritable */ observability: Observability | undefined; /** * Specify the cache behavior of the Worker. * * @inheritable */ cache: CacheOptions | undefined; /** * Specify the compliance region mode of the Worker. * * Although if the user does not specify a compliance region, the default is `public`, * it can be set to `undefined` in configuration to delegate to the CLOUDFLARE_COMPLIANCE_REGION environment variable. */ compliance_region: "public" | "fedramp_high" | undefined; /** * Configuration for Python modules. * * @inheritable */ python_modules: { /** * A list of glob patterns to exclude files from the python_modules directory when bundling. * * Patterns are relative to the python_modules directory and use glob syntax. * * @default ["**\*.pyc"] */ exclude: string[]; }; /** * Configuration for Worker Previews. * * Previews are branches of your Worker's main instance used to test features * in development outside of production. This block defines the settings * used when creating Preview deployments via `wrangler preview`. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#previews * * @inheritable */ previews: PreviewsConfig | undefined; } type DurableObjectBindings = { /** The name of the binding used to refer to the Durable Object */ name: string; /** The exported class name of the Durable Object */ class_name: string; /** The script where the Durable Object is defined (if it's external to this Worker) */ script_name?: string; /** The service environment of the script_name to bind to */ environment?: string; }[]; type WorkflowBinding = { /** The name of the binding used to refer to the Workflow */ binding: string; /** The name of the Workflow */ name: string; /** The exported class name of the Workflow */ class_name: string; /** The script where the Workflow is defined (if it's external to this Worker) */ script_name?: string; /** Whether the Workflow should be remote or not in local development */ remote?: boolean; /** Optional limits for the Workflow */ limits?: { /** Maximum number of steps a Workflow instance can execute */ steps?: number; }; /** Optional cron schedule(s) for automatically triggering workflow instances */ schedules?: string | string[]; }; /** * The `EnvironmentNonInheritable` interface declares all the configuration fields for an environment * that cannot be inherited from the top-level environment, and must be defined specifically. * * If any of these fields are defined at the top-level then they should also be specifically defined * for each named environment. */ interface EnvironmentNonInheritable { /** * A map of values to substitute when deploying your Worker. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default {} * @nonInheritable */ define: Record; /** * A map of environment variables to set when deploying your Worker. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#environment-variables * * @default {} * @nonInheritable */ vars: Record; /** * Secrets configuration. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#secrets-configuration-property * * @nonInheritable */ secrets?: { /** * List of secret names that are required by your Worker. * When defined, this property: * - Replaces .dev.vars/.env/process.env inference for type generation * - Enables local dev validation with warnings for missing secrets */ required?: string[]; }; /** * A list of durable objects that your Worker should be bound to. * * For more information about Durable Objects, see the documentation at * https://developers.cloudflare.com/workers/learning/using-durable-objects * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects * * @default {bindings:[]} * @nonInheritable */ durable_objects: { bindings: DurableObjectBindings; }; /** * A list of workflows that your Worker should be bound to. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ workflows: WorkflowBinding[]; /** * Cloudchamber configuration * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default {} * @nonInheritable */ cloudchamber: CloudchamberConfig; /** * Container related configuration * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ containers?: ContainerApp[]; /** * These specify any Workers KV Namespaces you want to * access from inside your Worker. * * To learn more about KV Namespaces, * see the documentation at https://developers.cloudflare.com/workers/learning/how-kv-works * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#kv-namespaces * * @default [] * @nonInheritable */ kv_namespaces: { /** The binding name used to refer to the KV Namespace */ binding: string; /** The ID of the KV namespace */ id?: string; /** The ID of the KV namespace used during `wrangler dev` */ preview_id?: string; /** Whether the KV namespace should be remote or not in local development */ remote?: boolean; }[]; /** * These specify bindings to send email from inside your Worker. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#email-bindings * * @default [] * @nonInheritable */ send_email: { /** The binding name used to refer to the this binding */ name: string; /** If this binding should be restricted to a specific verified address */ destination_address?: string; /** If this binding should be restricted to a set of verified addresses */ allowed_destination_addresses?: string[]; /** If this binding should be restricted to a set of sender addresses */ allowed_sender_addresses?: string[]; /** Whether the binding should be remote or not in local development */ remote?: boolean; }[]; /** * Specifies Queues that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#queues * * @default {consumers:[],producers:[]} * @nonInheritable */ queues: { /** Producer bindings */ producers?: { /** The binding name used to refer to the Queue in the Worker. */ binding: string; /** The name of this Queue. */ queue: string; /** The number of seconds to wait before delivering a message */ delivery_delay?: number; /** Whether the Queue producer should be remote or not in local development */ remote?: boolean; }[]; /** Consumer configuration */ consumers?: { /** The name of the queue from which this consumer should consume. */ queue: string; /** The consumer type. Only "worker" is supported in wrangler config. Default is "worker". */ type?: "worker"; /** The maximum number of messages per batch */ max_batch_size?: number; /** The maximum number of seconds to wait to fill a batch with messages. */ max_batch_timeout?: number; /** The maximum number of retries for each message. */ max_retries?: number; /** The queue to send messages that failed to be consumed. */ dead_letter_queue?: string; /** The maximum number of concurrent consumer Worker invocations. Leaving this unset will allow your consumer to scale to the maximum concurrency needed to keep up with the message backlog. */ max_concurrency?: number | null; /** The number of milliseconds to wait for pulled messages to become visible again */ visibility_timeout_ms?: number; /** The number of seconds to wait before retrying a message */ retry_delay?: number; }[]; }; /** * Specifies R2 buckets that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#r2-buckets * * @default [] * @nonInheritable */ r2_buckets: { /** The binding name used to refer to the R2 bucket in the Worker. */ binding: string; /** The name of this R2 bucket at the edge. */ bucket_name?: string; /** The preview name of this R2 bucket at the edge. */ preview_bucket_name?: string; /** The jurisdiction that the bucket exists in. Default if not present. */ jurisdiction?: string; /** Whether the R2 bucket should be remote or not in local development */ remote?: boolean; }[]; /** * Specifies D1 databases that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#d1-databases * * @default [] * @nonInheritable */ d1_databases: { /** The binding name used to refer to the D1 database in the Worker. */ binding: string; /** The name of this D1 database. */ database_name?: string; /** The UUID of this D1 database (not required). */ database_id?: string; /** The UUID of this D1 database for Wrangler Dev (if specified). */ preview_database_id?: string; /** The name of the migrations table for this D1 database (defaults to 'd1_migrations'). */ migrations_table?: string; /** The path to the directory of migrations for this D1 database (defaults to './migrations'). */ migrations_dir?: string; /** * A glob pattern (relative to the Wrangler config file) used to discover * migration files for this D1 database. Defaults to `${migrations_dir}/*.sql` * if not specified. * * Use this to opt in to nested layouts such as `migrations/*\/migration.sql` * (as produced by some ORMs). * * When `migrations_pattern` is set, `migrations_dir` must also be set, and * `migrations_pattern` must start with `${migrations_dir}/`. This keeps the * relationship between the two settings explicit and lets Wrangler record * each migration's name in the migrations table as a path relative to * `migrations_dir`. */ migrations_pattern?: string; /** Internal use only. */ database_internal_env?: string; /** Whether the D1 database should be remote or not in local development */ remote?: boolean; }[]; /** * Specifies Vectorize indexes that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#vectorize-indexes * * @default [] * @nonInheritable */ vectorize: { /** The binding name used to refer to the Vectorize index in the Worker. */ binding: string; /** The name of the index. */ index_name: string; /** Whether the Vectorize index should be remote or not in local development */ remote?: boolean; }[]; /** * Specifies AI Search namespace bindings that are bound to this Worker environment. * Each binding is scoped to a namespace and allows dynamic instance CRUD within it. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ ai_search_namespaces: { /** The binding name used to refer to the AI Search namespace in the Worker. */ binding: string; /** The user-chosen namespace name. Must exist in Cloudflare at deploy time. */ namespace: string; /** Whether the AI Search namespace binding should be remote in local development */ remote?: boolean; }[]; /** * Specifies AI Search instance bindings that are bound to this Worker environment. * Each binding is bound directly to a single pre-existing instance within the "default" namespace. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ ai_search: { /** The binding name used to refer to the AI Search instance in the Worker. */ binding: string; /** The user-chosen instance name. Must exist in Cloudflare at deploy time. */ instance_name: string; /** Whether the AI Search instance binding should be remote in local development */ remote?: boolean; }[]; /** * Specifies Agent Memory namespace bindings that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ agent_memory: { /** The binding name used to refer to the Agent Memory namespace in the Worker. */ binding: string; /** The user-chosen namespace name. Must exist in Cloudflare at deploy time. */ namespace: string; /** Whether the Agent Memory binding should be remote in local development */ remote?: boolean; }[]; /** * Cloudflare Web Search binding. There is exactly one shared web corpus, so the * binding is zero-config -- only the variable name is required, declared as a * single object (not an array). * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default {} * @nonInheritable */ websearch: { /** The binding name used to refer to Web Search in the Worker. */ binding: string; /** Whether the Web Search binding should be remote or not in local development */ remote?: boolean; } | undefined; /** * Specifies Hyperdrive configs that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#hyperdrive * * @default [] * @nonInheritable */ hyperdrive: { /** The binding name used to refer to the project in the Worker. */ binding: string; /** The id of the database. */ id: string; /** The local database connection string for `wrangler dev` */ localConnectionString?: string; }[]; /** * Specifies service bindings (Worker-to-Worker) that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#service-bindings * * @default [] * @nonInheritable */ services: { /** The binding name used to refer to the bound service. */ binding: string; /** * The name of the service. * To bind to a worker in a specific environment, * you should use the format `-`. */ service: string; /** * @hidden * @deprecated you should use `service: -` instead. * This refers to the deprecated concept of 'service environments'. * The environment of the service (e.g. production, staging, etc). */ environment?: string; /** Optionally, the entrypoint (named export) of the service to bind to. */ entrypoint?: string; /** Optional properties that will be made available to the service via ctx.props. */ props?: Record; /** Whether the service binding should be remote or not in local development */ remote?: boolean; }[] | undefined; /** * Specifies analytics engine datasets that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#analytics-engine-datasets * * @default [] * @nonInheritable */ analytics_engine_datasets: { /** The binding name used to refer to the dataset in the Worker. */ binding: string; /** The name of this dataset to write to. */ dataset?: string; }[]; /** * A browser that will be usable from the Worker. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#browser-rendering * * @default {} * @nonInheritable */ browser: { binding: string; /** Whether the Browser binding should be remote or not in local development */ remote?: boolean; } | undefined; /** * Binding to the AI project. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#workers-ai * * @default {} * @nonInheritable */ ai: { binding: string; staging?: boolean; /** Whether the AI binding should be remote or not in local development */ remote?: boolean; } | undefined; /** * Binding to Cloudflare Images * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#images * * @default {} * @nonInheritable */ images: { binding: string; /** Whether the Images binding should be remote or not in local development */ remote?: boolean; } | undefined; /** * Binding to Cloudflare Media Transformations * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default {} * @nonInheritable */ media: { binding: string; /** Whether the Media binding should be remote or not */ remote?: boolean; } | undefined; /** * Binding to Cloudflare Stream * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default {} * @nonInheritable */ stream: { binding: string; /** Whether the Stream binding should be remote or not in local development */ remote?: boolean; } | undefined; /** * Binding to the Worker Version's metadata */ version_metadata: { binding: string; } | undefined; /** * "Unsafe" tables for features that aren't directly supported by wrangler. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default {} * @nonInheritable */ unsafe: { /** * A set of bindings that should be put into a Worker's upload metadata without changes. These * can be used to implement bindings for features that haven't released and aren't supported * directly by wrangler or miniflare. */ bindings?: UnsafeBinding[]; /** * Arbitrary key/value pairs that will be included in the uploaded metadata. Values specified * here will always be applied to metadata last, so can add new or override existing fields. */ metadata?: { [key: string]: unknown; }; /** * Used for internal capnp uploads for the Workers runtime */ capnp?: { base_path: string; source_schemas: string[]; compiled_schema?: never; } | { base_path?: never; source_schemas?: never; compiled_schema: string; }; }; /** * Specifies a list of mTLS certificates that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#mtls-certificates * * @default [] * @nonInheritable */ mtls_certificates: { /** The binding name used to refer to the certificate in the Worker */ binding: string; /** The uuid of the uploaded mTLS certificate */ certificate_id: string; /** Whether the mtls fetcher should be remote or not in local development */ remote?: boolean; }[]; /** * Specifies a list of Tail Workers that are bound to this Worker environment * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ tail_consumers?: TailConsumer[]; /** * Specifies a list of Streaming Tail Workers that are bound to this Worker environment * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ streaming_tail_consumers?: StreamingTailConsumer[]; /** * Specifies namespace bindings that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#dispatch-namespace-bindings-workers-for-platforms * * @default [] * @nonInheritable */ dispatch_namespaces: { /** The binding name used to refer to the bound service. */ binding: string; /** The namespace to bind to. */ namespace: string; /** Details about the outbound Worker which will handle outbound requests from your namespace */ outbound?: DispatchNamespaceOutbound; /** Whether the Dispatch Namespace should be remote or not in local development */ remote?: boolean; }[]; /** * Specifies list of Pipelines bound to this Worker environment * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ pipelines: { /** The binding name used to refer to the bound service. */ binding: string; /** Id of the Stream to bind */ stream?: string; /** * Id of the Stream to bind * @deprecated Use `stream` instead. */ pipeline?: string; /** Whether the pipeline should be remote or not in local development */ remote?: boolean; }[]; /** * Specifies Secret Store bindings that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ secrets_store_secrets: { /** The binding name used to refer to the bound service. */ binding: string; /** Id of the secret store */ store_id: string; /** Name of the secret */ secret_name: string; }[]; /** * Specifies Artifacts bindings that are bound to this Worker environment. * Artifacts provides git-compatible file storage on Cloudflare Workers. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ artifacts: { /** The binding name used to refer to the Artifacts instance. */ binding: string; /** The namespace to use. */ namespace: string; /** Whether to use the remote Artifacts service in local dev. */ remote?: boolean; }[]; /** * **DO NOT USE**. Hello World Binding Config to serve as an explanatory example. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ unsafe_hello_world: { /** The binding name used to refer to the bound service. */ binding: string; /** Whether the timer is enabled */ enable_timer?: boolean; }[]; /** * Specifies Flagship feature flag bindings that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ flagship: { /** The binding name used to refer to the bound Flagship service. */ binding: string; /** The Flagship app ID to bind to. */ app_id: string; /** Set to `true` to suppress the remote binding warning in local dev. Flagship bindings are always remote. */ remote?: boolean; }[]; /** * Specifies rate limit bindings that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ ratelimits: { /** The binding name used to refer to the rate limiter in the Worker. */ name: string; /** The namespace ID for this rate limiter. */ namespace_id: string; /** Simple rate limiting configuration. */ simple: { /** The maximum number of requests allowed in the time period. */ limit: number; /** The time period in seconds (10 for ten seconds, 60 for one minute). */ period: 10 | 60; }; }[]; /** * Specifies Worker Loader bindings that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ worker_loaders: { /** The binding name used to refer to the Worker Loader in the Worker. */ binding: string; }[]; /** * Specifies VPC services that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ vpc_services: { /** The binding name used to refer to the VPC service in the Worker. */ binding: string; /** The service ID of the VPC connectivity service. */ service_id: string; /** Whether the VPC service is remote or not */ remote?: boolean; }[]; /** * Specifies VPC networks that are bound to this Worker environment. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @default [] * @nonInheritable */ vpc_networks: ({ /** The binding name used to refer to the VPC network in the Worker. */ binding: string; /** The tunnel ID of the Cloudflare Tunnel to route traffic through. Mutually exclusive with network_id. */ tunnel_id: string; /** Whether the VPC network is remote or not */ remote?: boolean; } | { /** The binding name used to refer to the VPC network in the Worker. */ binding: string; /** The network ID to route traffic through. Mutually exclusive with tunnel_id. */ network_id: string; /** Whether the VPC network is remote or not */ remote?: boolean; })[]; } /** * The raw environment configuration that we read from the config file. * * All the properties are optional, and will be replaced with defaults in the configuration that * is used in the rest of the codebase. */ type RawEnvironment = Partial; /** * A bundling resolver rule, defining the modules type for paths that match the specified globs. */ type Rule = { type: ConfigModuleRuleType; globs: string[]; fallthrough?: boolean; }; /** * The possible types for a `Rule`. */ type ConfigModuleRuleType = "ESModule" | "CommonJS" | "CompiledWasm" | "Text" | "Data" | "PythonModule" | "PythonRequirement"; type TailConsumer = { /** The name of the service tail events will be forwarded to. */ service: string; /** (Optional) The environment of the service. */ environment?: string; }; type StreamingTailConsumer = { /** The name of the service streaming tail events will be forwarded to. */ service: string; }; interface DispatchNamespaceOutbound { /** Name of the service handling the outbound requests */ service: string; /** (Optional) Name of the environment handling the outbound requests. */ environment?: string; /** (Optional) List of parameter names, for sending context from your dispatch Worker to the outbound handler */ parameters?: string[]; } interface UserLimits { /** Maximum allowed CPU time for a Worker's invocation in milliseconds */ cpu_ms?: number; /** Maximum allowed number of fetch requests that a Worker's invocation can execute */ subrequests?: number; } type Assets = { /** Absolute path to assets directory */ directory?: string; /** Name of `env` binding property in the User Worker. */ binding?: string; /** How to handle HTML requests. */ html_handling?: "auto-trailing-slash" | "force-trailing-slash" | "drop-trailing-slash" | "none"; /** How to handle requests that do not match an asset. */ not_found_handling?: "single-page-application" | "404-page" | "none"; /** * Matches will be routed to the User Worker, and matches to negative rules will go to the Asset Worker. * * Can also be `true`, indicating that every request should be routed to the User Worker. */ run_worker_first?: string[] | boolean; }; interface Observability { /** If observability is enabled for this Worker */ enabled?: boolean; /** The sampling rate */ head_sampling_rate?: number; logs?: { enabled?: boolean; /** The sampling rate */ head_sampling_rate?: number; /** Set to false to disable invocation logs */ invocation_logs?: boolean; /** * If logs should be persisted to the Cloudflare observability platform where they can be queried in the dashboard. * * @default true */ persist?: boolean; /** * What destinations logs emitted from the Worker should be sent to. * * @default [] */ destinations?: string[]; }; traces?: { enabled?: boolean; /** The sampling rate */ head_sampling_rate?: number; /** * If traces should be persisted to the Cloudflare observability platform where they can be queried in the dashboard. * * @default true */ persist?: boolean; /** * What destinations traces emitted from the Worker should be sent to. * * @default [] */ destinations?: string[]; }; } interface CacheOptions { /** If cache is enabled for this Worker */ enabled: boolean; /** Whether cached assets may be reused across Worker versions. */ cross_version_cache?: boolean; } type DockerConfiguration = { /** Socket used by miniflare to communicate with Docker */ socketPath: string; /** Docker image name for the container egress interceptor sidecar */ containerEgressInterceptorImage?: string; }; type ContainerEngine = { localDocker: DockerConfiguration; } | string; /** * Configuration for Worker Previews. * * This defines the settings used when creating Preview deployments. * Previews are branches of your Worker's main instance used to test features * during feature development outside of production. * * The `previews` block contains any intentionally divergent configuration intended solely for Previews, including: * - All non-inheritable properties (environment variables and bindings like KV, D1, R2, etc.) * - Select inheritable properties: `logpush`, `observability`, `limits`, `cache` * * @inheritable */ interface PreviewsConfig extends Partial, Partial> { } /** * This is the static type definition for the configuration object. * * It reflects a normalized and validated version of the configuration that you can write in a Wrangler configuration file, * and optionally augment with arguments passed directly to wrangler. * * For more information about the configuration object, see the * documentation at https://developers.cloudflare.com/workers/cli-wrangler/configuration * * Notes: * * - Fields that are only specified in `ConfigFields` and not `Environment` can only appear * in the top level config and should not appear in any environments. * - Fields that are specified in `PagesConfigFields` are only relevant for Pages projects * - All top level fields in config and environments are optional in the Wrangler configuration file. * * Legend for the annotations: * * - `@breaking`: the deprecation/optionality is a breaking change from Wrangler v1. * - `@todo`: there's more work to be done (with details attached). */ type Config = ComputedFields & ConfigFields & PagesConfigFields & Environment; type RawConfig = Partial> & PagesConfigFields & RawEnvironment & EnvironmentMap & { $schema?: string; }; interface ComputedFields { /** The path to the Wrangler configuration file (if any, and possibly redirected from the user Wrangler configuration) used to create this configuration. */ configPath: string | undefined; /** The path to the user's Wrangler configuration file (if any), which may have been redirected to another file that used to create this configuration. */ userConfigPath: string | undefined; /** * The original top level name for the Worker in the raw configuration. * * When a raw configuration has been flattened to a single environment the worker name may have been replaced or transformed. * It can be useful to know what the top-level name was before the flattening. */ topLevelName: string | undefined; /** A list of environment names declared in the raw configuration. */ definedEnvironments: string[] | undefined; /** The name of the environment being targeted. */ targetEnvironment: string | undefined; } interface ConfigFields { /** * A boolean to enable "legacy" style wrangler environments (from Wrangler v1). * These have been superseded by Services, but there may be projects that won't * (or can't) use them. If you're using a legacy environment, you can set this * to `true` to enable it. */ legacy_env: boolean; /** * Whether Wrangler should send usage metrics to Cloudflare for this project. * * When defined this will override any user settings. * Otherwise, Wrangler will use the user's preference. */ send_metrics: boolean | undefined; /** * Options to configure the development server that your worker will use. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#local-development-settings */ dev: Dev; /** * The definition of a Worker Site, a feature that lets you upload * static assets with your Worker. * * More details at https://developers.cloudflare.com/workers/platform/sites * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#workers-sites */ site: { /** * The directory containing your static assets. * * It must be a path relative to your Wrangler configuration file. * Example: bucket = "./public" * * If there is a `site` field then it must contain this `bucket` field. */ bucket: string; /** * The location of your Worker script. * * @deprecated DO NOT use this (it's a holdover from Wrangler v1.x). Either use the top level `main` field, or pass the path to your entry file as a command line argument. * @breaking */ "entry-point"?: string; /** * An exclusive list of .gitignore-style patterns that match file * or directory names from your bucket location. Only matched * items will be uploaded. Example: include = ["upload_dir"] * * @optional * @default [] */ include?: string[]; /** * A list of .gitignore-style patterns that match files or * directories in your bucket that should be excluded from * uploads. Example: exclude = ["ignore_dir"] * * @optional * @default [] */ exclude?: string[]; } | undefined; /** * A list of wasm modules that your worker should be bound to. This is * the "legacy" way of binding to a wasm module. ES module workers should * do proper module imports. */ wasm_modules: { [key: string]: string; } | undefined; /** * A list of text files that your worker should be bound to. This is * the "legacy" way of binding to a text file. ES module workers should * do proper module imports. */ text_blobs: { [key: string]: string; } | undefined; /** * A list of data files that your worker should be bound to. This is * the "legacy" way of binding to a data file. ES module workers should * do proper module imports. */ data_blobs: { [key: string]: string; } | undefined; /** * A map of module aliases. Lets you swap out a module for any others. * Corresponds with esbuild's `alias` config * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#module-aliasing */ alias: { [key: string]: string; } | undefined; /** * By default, the Wrangler configuration file is the source of truth for your environment configuration, like a terraform file. * * If you change your vars in the dashboard, wrangler *will* override/delete them on its next deploy. * * If you want to keep your dashboard vars when wrangler deploys, set this field to true. * * @default false * @nonInheritable */ keep_vars?: boolean; } interface PagesConfigFields { /** * The directory of static assets to serve. * * The presence of this field in a Wrangler configuration file indicates a Pages project, * and will prompt the handling of the configuration file according to the * Pages-specific validation rules. */ pages_build_output_dir?: string; } interface DevConfig { /** * IP address for the local dev server to listen on, * * @default localhost */ ip: string; /** * Port for the local dev server to listen on * * @default 8787 */ port: number | undefined; /** * Port for the local dev server's inspector to listen on * * @default 9229 */ inspector_port: number | undefined; /** * IP address for the local dev server's inspector to listen on * * @default 127.0.0.1 */ inspector_ip: string | undefined; /** * Protocol that local wrangler dev server listens to requests on. * * @default http */ local_protocol: "http" | "https"; /** * Protocol that wrangler dev forwards requests on * * Setting this to `http` is not currently implemented for remote mode. * See https://github.com/cloudflare/workers-sdk/issues/583 * * @default https */ upstream_protocol: "https" | "http"; /** * Host to forward requests to, defaults to the host of the first route of project */ host: string | undefined; /** * When developing, whether to build and connect to containers. This requires a Docker daemon to be running. * Defaults to `true`. * * @default true */ enable_containers: boolean; /** * Either the Docker unix socket i.e. `unix:///var/run/docker.sock` or a full configuration. * Note that windows is only supported via WSL at the moment */ container_engine: ContainerEngine | undefined; /** * Re-generate your worker types when your Wrangler configuration file changes. * * @default false */ generate_types: boolean; } type RawDevConfig = Partial; interface EnvironmentMap { /** * The `env` section defines overrides for the configuration for different environments. * * All environment fields can be specified at the top level of the config indicating the default environment settings. * * - Some fields are inherited and overridable in each environment. * - But some are not inherited and must be explicitly specified in every environment, if they are specified at the top level. * * For more information, see the documentation at https://developers.cloudflare.com/workers/cli-wrangler/configuration#environments * * @default {} */ env?: { [envName: string]: RawEnvironment; }; } /** * A binding type for vars - plain_text, json, or secret_text. * Used as the return type for getVarsForDev. */ type VarBinding = Extract; /** * Get the Worker `vars` bindings for a `wrangler dev` instance of a Worker. * * The `vars` bindings can be specified in the Wrangler configuration file. * But "secret" `vars` are usually only provided at the server - * either by creating them in the Dashboard UI, or using the `wrangler secret` command. * * It is useful during development, to provide these types of variable locally. * When running `wrangler dev` we will look for a file called `.dev.vars`, situated * next to the User's Wrangler configuration file (or in the current working directory if there is no * Wrangler configuration). If the `--env ` option is set, we'll first look for * `.dev.vars.`. * * If there are no `.dev.vars*` file, (and CLOUDFLARE_LOAD_DEV_VARS_FROM_DOT_ENV is not "false") * we will look for `.env*` files in the same directory. * If the `envFiles` option is set, we'll look for the `.env` files at those paths instead of the defaults. * * Any values in these files (all formatted like `.env` files) will add to or override `vars` * bindings provided in the Wrangler configuration file. * * When `secrets` is defined in the config, `.dev.vars` values will still * override existing config `vars` (so that local development overrides always * take effect). Additionally, any `required` secret keys that are not already * in the config vars will also be loaded from `.dev.vars`. Keys in `.dev.vars` * that are neither existing config vars nor declared required secrets are * excluded. A warning is emitted for any required secrets that are missing. * * @param configPath - The path to the Wrangler configuration file, if defined. * @param envFiles - An array of paths to .env files to load; if `undefined` the default .env files will be used (see `getDefaultEnvFiles()`). * The `envFiles` paths are resolved against the directory of the Wrangler configuration file, if there is one, otherwise against the current working directory. * @param vars - The existing `vars` bindings from the Wrangler configuration. * @param env - The specific environment name (e.g., "staging") or `undefined` if no specific environment is set. * @param silent - If true, will not log any messages about the loaded .dev.vars files or .env files. * @param secrets - If defined, only the declared secret keys are loaded from `.dev.vars` or `.env`/`process.env`. * @returns The merged `vars` as typed bindings. Config vars are `plain_text`/`json`, while `.dev.vars`/`.env` vars are `secret_text`. */ declare function getVarsForDev(configPath: string | undefined, envFiles: string[] | undefined, vars: Config$1["vars"], env: string | undefined, silent?: boolean, secrets?: Config$1["secrets"]): Record; /** * @deprecated Use today's date as the compatibility date instead. */ declare function unstable_getDevCompatibilityDate(): `${number}${number}${number}${number}-${number}${number}-${number}${number}`; /** * Options for the `getPlatformProxy` utility */ type GetPlatformProxyOptions = { /** * The name of the environment to use */ environment?: string; /** * The path to the config file to use. * If no path is specified the default behavior is to search from the * current directory up the filesystem for a Wrangler configuration file to use. * * Note: this field is optional but if a path is specified it must * point to a valid file on the filesystem */ configPath?: string; /** * Paths to `.env` files to load environment variables from, relative to the project directory. * * The project directory is computed as the directory containing `configPath` or the current working directory if `configPath` is undefined. * * If `envFiles` is defined, only the files in the array will be considered for loading local dev variables. * If `undefined`, the default behavior is: * - compute the project directory as that containing the Wrangler configuration file, * or the current working directory if no Wrangler configuration file is specified. * - look for `.env` and `.env.local` files in the project directory. * - if the `environment` option is specified, also look for `.env.` and `.env..local` * files in the project directory * - resulting in an `envFiles` array like: `[".env", ".env.local", ".env.", ".env..local"]`. * * The values from files earlier in the `envFiles` array (e.g. `envFiles[x]`) will be overridden by values from files later in the array (e.g. `envFiles[x+1)`). */ envFiles?: string[]; /** * Indicates if and where to persist the bindings data, if not present or `true` it defaults to the same location * used by wrangler: `.wrangler/state/v3` (so that the same data can be easily used by the caller and wrangler). * If `false` is specified no data is persisted on the filesystem. */ persist?: boolean | { path: string; }; /** * Whether remote bindings should be enabled or not (defaults to `true`) */ remoteBindings?: boolean; }; /** * Result of the `getPlatformProxy` utility */ type PlatformProxy, CfProperties extends Record = IncomingRequestCfProperties> = { /** * Environment object containing the various Cloudflare bindings */ env: Env; /** * Mock of the context object that Workers received in their request handler, all the object's methods are no-op */ cf: CfProperties; /** * Mock of the context object that Workers received in their request handler, all the object's methods are no-op */ ctx: ExecutionContext; /** * Caches object emulating the Workers Cache runtime API */ caches: CacheStorage; /** * Function used to dispose of the child process providing the bindings implementation */ dispose: () => Promise; }; /** * By reading from a Wrangler configuration file this function generates proxy objects that can be * used to simulate the interaction with the Cloudflare platform during local development * in a Node.js environment * * @param options The various options that can tweak this function's behavior * @returns An Object containing the generated proxies alongside other related utilities */ declare function getPlatformProxy, CfProperties extends Record = IncomingRequestCfProperties>(options?: GetPlatformProxyOptions): Promise>; type SourcelessWorkerOptions = Omit & { modulesRules?: ModuleRule[]; }; interface Unstable_MiniflareWorkerOptions { workerOptions: SourcelessWorkerOptions; define: Record; main?: string; externalWorkers: WorkerOptions[]; } declare function unstable_getMiniflareWorkerOptions(configPath: string, env?: string, options?: { remoteProxyConnectionString?: RemoteProxyConnectionString; overrides?: { assets?: Partial; enableContainers?: boolean; }; containerBuildId?: string; }): Unstable_MiniflareWorkerOptions; declare function unstable_getMiniflareWorkerOptions(config: Config, env?: string, options?: { remoteProxyConnectionString?: RemoteProxyConnectionString; overrides?: { assets?: Partial; enableContainers?: boolean; }; containerBuildId?: string; }): Unstable_MiniflareWorkerOptions; /** * A Cloudflare account. */ interface CfAccount { /** * An API token. * * @link https://api.cloudflare.com/#user-api-tokens-properties */ apiToken: ApiCredentials; /** * An account ID. */ accountId: string; } type StartRemoteProxySessionOptions = { workerName?: string; auth?: NonNullable["auth"]; /** If running in a non-public compliance region, set this here. */ complianceRegion?: Config$1["compliance_region"]; }; declare function startRemoteProxySession(bindings: StartDevWorkerInput["bindings"], options?: StartRemoteProxySessionOptions): Promise; type RemoteProxySession = Pick & { updateBindings: (bindings: StartDevWorkerInput["bindings"]) => Promise; remoteProxyConnectionString: RemoteProxyConnectionString; }; type WranglerConfigObject = { /** The path to the wrangler config file */ path: string; /** The target environment */ environment?: string; }; type WorkerConfigObject = { /** The name of the worker */ name?: string; /** The Worker's bindings */ bindings: NonNullable; /** If running in a non-public compliance region, set this here. */ complianceRegion?: Config$1["compliance_region"]; /** Id of the account owning the worker */ account_id?: Config$1["account_id"]; }; /** * Utility for potentially starting or updating a remote proxy session. * * @param wranglerOrWorkerConfigObject either a file path to a wrangler configuration file or an object containing the name of * the target worker alongside its bindings. * @param preExistingRemoteProxySessionData the optional data of a pre-existing remote proxy session if there was one, this * argument can be omitted or set to null if there is no pre-existing remote proxy session * @param auth the authentication information for establishing the remote proxy connection * @returns null if no existing remote proxy session was provided and one should not be created (because the worker is not * defining any remote bindings), the data associated to the created/updated remote proxy session otherwise. */ declare function maybeStartOrUpdateRemoteProxySession(wranglerOrWorkerConfigObject: WranglerConfigObject | WorkerConfigObject, preExistingRemoteProxySessionData?: { session: RemoteProxySession; remoteBindings: Record; auth?: AsyncHook | undefined; } | null, auth?: AsyncHook | undefined): Promise<{ session: RemoteProxySession; remoteBindings: Record; auth?: AsyncHook | undefined; } | null>; type TableRow = Record; declare class Logger { #private; constructor(); private overrideLoggerLevel?; private onceHistory; get loggerLevel(): "debug" | "none" | "error" | "log" | "info" | "warn"; set loggerLevel(val: "debug" | "none" | "error" | "log" | "info" | "warn"); resetLoggerLevel(): void; columns: number; json: (data: unknown) => void; debug: (...args: unknown[]) => void; debugWithSanitization: (label: string, ...args: unknown[]) => void; info: (...args: unknown[]) => void; log: (...args: unknown[]) => void; warn: (...args: unknown[]) => void; error(...args: unknown[]): void; error(error: ParseError): void; table(data: TableRow[], options?: { wordWrap: boolean; head?: Keys[]; }): void; console>(method: M, ...args: Parameters): void; get once(): { info: (...args: unknown[]) => void; log: (...args: unknown[]) => void; warn: (...args: unknown[]) => void; error: (...args: unknown[]) => void; }; clearHistory(): void; doLogOnce(messageLevel: Exclude, args: unknown[]): void; private doLog; static registerBeforeLogHook(callback: (() => void) | undefined): void; static registerAfterLogHook(callback: (() => void) | undefined): void; private formatMessage; } /** * Resolves the named tunnel to hostnames whose ingress rules * target the current local dev origin and the token needed * to start `cloudflared tunnel run`. */ declare function resolveNamedTunnel(name: string, origin: URL, options: { accountId: string | undefined; complianceRegion: Config$1["compliance_region"]; }): Promise<{ hostnames: string[]; token: string; }>; interface DevArgs { mode?: string; port?: number; host?: string; local?: boolean; } interface BuildArgs { mode?: string; } declare class ArgParseError extends Error { constructor(message: string); } declare function parseArgs(argv: string[]): DevArgs; declare function parseBuildArgs(argv: string[]): BuildArgs; declare function runCfWranglerBuild(args: BuildArgs): Promise; /** * Run the dev server until it tears down (a hotkey quit in a TTY, or a * signal from a non-interactive parent). Mirrors `wrangler dev`'s command * handler and installs no signal handlers of its own, so signal handling * and exit codes match `wrangler dev` exactly. * * @param options Fully-built `StartDevOptions` (built in `bin/cf-wrangler.js`). * @returns `0` on a clean teardown. */ declare function runCfWranglerDev(options: StartDevOptions): Promise; /** * Split an SQLQuery into an array of statements */ declare function splitSqlQuery(sql: string): string[]; /** * The implementation for fetching a kv value from the cloudflare API. * We special-case this one call, because it's the only API call that * doesn't return json. We inline the implementation and try not to share * any code with the other calls. We should push back on any new APIs that * try to introduce non-"standard" response structures. * * Note: any calls to fetchKVGetValue must call encodeURIComponent on key * before passing it */ declare function fetchKVGetValue(complianceConfig: ComplianceConfig, accountId: string, namespaceId: string, key: string): Promise; /** * Make a fetch request, and extract the `result` from the JSON response. */ declare function fetchResult(complianceConfig: ComplianceConfig, resource: string, init?: RequestInit, queryParams?: URLSearchParams, abortSignal?: AbortSignal, apiToken?: ApiCredentials): Promise; /** * Make a fetch request for a list of values, * extracting the `result` from the JSON response, * and repeating the request if the results are paginated. */ declare function fetchListResult(complianceConfig: ComplianceConfig, resource: string, init?: RequestInit, queryParams?: URLSearchParams): Promise; /** * Make a fetch request for a list of values, * extracting the `result` from the JSON response, * and repeating the request if the results are paginated. * * This is similar to fetchListResult, but it uses the `page` query parameter instead of `cursor`. */ declare function fetchPagedListResult(complianceConfig: ComplianceConfig, resource: string, init?: RequestInit, queryParams?: URLSearchParams): Promise; interface ConfirmOptions { defaultValue?: boolean; fallbackValue?: boolean; } declare function confirm(text: string, { defaultValue, fallbackValue }?: ConfirmOptions): Promise; interface PromptOptions { defaultValue?: string; isSecret?: boolean; validate?: (value: string) => boolean | string | Promise; } declare function prompt(text: string, options?: PromptOptions): Promise; type ExperimentalFlags = { MULTIWORKER: boolean; RESOURCES_PROVISION: boolean; AUTOCREATE_RESOURCES: boolean; }; /** * Yargs options included in every wrangler command. */ interface CommonYargsOptions { v: boolean | undefined; cwd: string | undefined; config: string | undefined; env: string | undefined; "env-file": string[] | undefined; "experimental-provision": boolean | undefined; "experimental-auto-create": boolean; "install-skills": boolean; profile: string | undefined; } type CommonYargsArgv = Argv; type RemoveIndex = { [K in keyof T as string extends K ? never : number extends K ? never : K]: T[K]; }; // Team names from https://wiki.cfdata.org/display/EW/Developer+Platform+Components+and+Pillar+Ownership type Teams = | "Workers: Onboarding & Integrations" | "Workers: Builds and Automation" | "Workers: Deploy and Config" | "Workers: Authoring and Testing" | "Workers: Frameworks and Runtime APIs" | "Workers: Runtime Platform" | "Workers: Workers Observability" | "Product: KV" | "Product: R2" | "Product: R2 Data Catalog" | "Product: R2 SQL" | "Product: D1" | "Product: Queues" | "Product: AI" | "Product: AI Search" | "Product: Agent Memory" | "Product: Web Search" | "Product: Hyperdrive" | "Product: Pipelines" | "Product: Vectorize" | "Product: Workflows" | "Product: Cloudchamber" | "Product: SSL" | "Product: WVPC" | "Product: Tunnels" | "Product: Email Service" | "Product: Browser Run" | "Product: Artifacts" | "Product: Flagship"; /** Convert literal string types like 'foo-bar' to 'FooBar' */ type PascalCase = string extends S ? string : S extends `${infer T}-${infer U}` ? `${Capitalize}${PascalCase}` : Capitalize; /** Convert literal string types like 'foo-bar' to 'fooBar' */ type CamelCase = string extends S ? string : S extends `${infer T}-${infer U}` ? `${T}${PascalCase}` : S; type CamelCaseKey = K extends string ? Exclude, ""> : K; type Alias = O extends { alias: infer T; } ? T extends Exclude ? { [key in T]: InferredOptionType; } : {} : {}; type StringKeyOf = Extract; type DeepFlatten = T extends object ? { [K in keyof T]: DeepFlatten; } : T; type MetadataCategory = "Account" | "Compute & AI" | "Storage & databases" | "Networking & security"; type Command = `wrangler${string}`; type Metadata = { description: string; status: "experimental" | "alpha" | "private beta" | "open beta" | "stable"; statusMessage?: string; deprecated?: boolean; deprecatedMessage?: string; hidden?: boolean; owner: Teams; /** Prints something at the bottom of the help */ epilogue?: string; examples?: { command: string; description: string; }[]; hideGlobalFlags?: string[]; /** * Optional category for grouping commands in the help output. * Commands with the same category will be grouped together under a shared heading. * Commands without a category will appear under the default "COMMANDS" group. */ category?: MetadataCategory; }; type ArgDefinition = Omit & Pick; type NamedArgDefinitions = { [key: string]: ArgDefinition; }; type OnlyCamelCase> = { [key in keyof T as CamelCaseKey]: T[key]; }; type HandlerArgs = DeepFlatten & Alias>>>>; type HandlerContext = { /** * The wrangler config file read from disk and parsed. */ config: Config$1; /** * The logger instance provided to the command implementor as a convenience. */ logger: Logger; /** * Use fetchResult to make *auth'd* requests to the Cloudflare API. */ fetchResult: typeof fetchResult; fetchListResult: typeof fetchListResult; fetchPagedListResult: typeof fetchPagedListResult; fetchKVGetValue: typeof fetchKVGetValue; /** * Interactive prompts */ confirm: typeof confirm; prompt: typeof prompt; /** * Whether the process is non-interactive or running in CI. */ isNonInteractiveOrCI: () => boolean; /** * Error classes provided to the command implementor as a convenience * to aid discoverability and to encourage their usage. */ errors: { UserError: typeof UserError; FatalError: typeof FatalError; }; /** * API SDK */ sdk: Cloudflare; }; type CommandDefinition = { /** * Descriptive information about the command which does not affect behaviour. * This is used for the CLI --help and subcommand --help output. * This should be used as the source-of-truth for status and ownership. */ metadata: Metadata; /** * Controls shared behaviour across all commands. * This will allow wrangler commands to remain consistent and only diverge intentionally. */ behaviour?: { /** * By default, wrangler's version banner will be printed before the handler is executed. * Set this value to `false` to skip printing the banner. * * @default true */ printBanner?: boolean | ((args: HandlerArgs) => boolean); /** * Opt-in to printing a metrics banner for this command. * @default false */ printMetricsBanner?: boolean; /** * By default, wrangler will print warnings about the Wrangler configuration file. * Set this value to `false` to skip printing these warnings. */ printConfigWarnings?: boolean; /** * By default, wrangler will read & provide the wrangler.toml/wrangler.json configuration. * Set this value to `false` to skip this. */ provideConfig?: boolean; /** * By default, wrangler will provide experimental flags in the handler context, * according to the default values in register-yargs.command.ts * Use this to override those defaults per command. */ overrideExperimentalFlags?: (args: HandlerArgs) => ExperimentalFlags; /** * If true, then look for a redirect file at `.wrangler/deploy/config.json` and use that to find the Wrangler configuration file. */ useConfigRedirectIfAvailable?: boolean; /** * If true, print a message about whether the command is operating on a local or remote resource */ printResourceLocation?: ((args: HandlerArgs) => boolean) | boolean; /** * If true, check for environments in the wrangler config, if there are some and the user hasn't specified an environment * using the `-e|--env` cli flag, show a warning suggesting that one should instead be specified. */ warnIfMultipleEnvsConfiguredButNoneSpecified?: boolean; /** * Opt out of sending metrics for this command * @default true */ sendMetrics?: boolean; /** * After the command handler completes successfully, suggest installing * Cloudflare skills for detected AI coding agents that don't have them. * * When set to `true`, the suggestion always runs after the handler. * When set to a function, it receives the parsed args and should return * `true` to enable the suggestion — use this to skip the prompt in modes * where interactive output is inappropriate (e.g. `--json`). * * @default false */ suggestSkillsAfterHandler?: boolean | ((args: HandlerArgs) => boolean); /** * Whether this command can authenticate with a temporary preview account * (via the hidden `--temporary` flag) when no real credentials are available. * Only enable this for commands whose API calls are covered by the temporary * preview-account deploy token (Workers, KV, D1, Hyperdrive, Queues, SSL/Certs). * @default false */ supportTemporary?: boolean; /** * By default, the banner will print "Active profile: " when a non-default * profile is resolved. Set to `false` to suppress this line while still printing * the rest of the banner. * * @default true */ printActiveProfile?: boolean; }; /** * A plain key-value object describing the CLI args for this command. * Shared args can be defined as another plain object and spread into this. */ args?: NamedArgDefs; /** * Optionally declare some of the named args as positional args. * The order of this array is the order they are expected in the command. * Use args[key].demandOption and args[key].array to declare required and variadic * positional args, respectively. */ positionalArgs?: Array>; /** * A hook to implement custom validation of the args before the handler is called. * Throw `CommandLineArgsError` with actionable error message if args are invalid. * The return value is ignored. * * @param args - The parsed CLI arguments * @param def - The command definition, useful for passing to helpers like `demandOneOfOption` */ validateArgs?: (args: HandlerArgs, def: CommandDefinition) => void | Promise; /** * The implementation of the command which is given camelCase'd args * and a ctx object of convenience properties */ handler: (args: HandlerArgs, ctx: HandlerContext) => void | Promise; }; type NamespaceDefinition = { metadata: Metadata; }; type AliasDefinition = { aliasOf: Command; metadata?: Partial; }; type InternalCommandDefinition = { type: "command"; command: Command; } & CommandDefinition; type InternalNamespaceDefinition = { type: "namespace"; command: Command; } & NamespaceDefinition; type InternalAliasDefinition = { type: "alias"; command: Command; } & AliasDefinition; type InternalDefinition = InternalCommandDefinition | InternalNamespaceDefinition | InternalAliasDefinition; type DefinitionTreeNode = { definition?: InternalDefinition; subtree: DefinitionTree; }; type DefinitionTree = Map; type CreateCommandResult = DeepFlatten<{ args: HandlerArgs; }>; /** * Map of category names to the top-level command segments that belong to them. * Used for grouping commands in the help output. */ type CategoryMap = Map>; /** * Class responsible for registering and managing commands within a command registry. */ declare class CommandRegistry { #private; /** * Initializes the command registry with the given command registration function. */ constructor(registerCommand: RegisterCommand); /** * Defines multiple commands and their corresponding definitions. */ define(defs: { command: Command; definition: AliasDefinition | CreateCommandResult | NamespaceDefinition; }[]): void; getDefinitionTreeRoot(): DefinitionTreeNode; /** * Registers all commands in the command registry, walking through the definition tree. */ registerAll(): void; /** * Registers a specific namespace if not already registered. * TODO: Remove this once all commands use the command registry. * See https://github.com/cloudflare/workers-sdk/pull/7357#discussion_r1862138470 for more details. */ registerNamespace(namespace: string): void; /** * Get a set of all top-level command names. * * Includes both registry-defined commands & legacy commands. */ get topLevelCommands(): Set; /** * Returns the map of categories to command segments, ordered according to * the category order. Commands within each category are sorted alphabetically. * Used for grouping commands in the help output. */ get orderedCategories(): CategoryMap; /** * Registers a legacy command that doesn't use the `CommandRegistry` class. * This is used for hidden commands like `cloudchamber` that use the old yargs pattern. */ registerLegacyCommand(command: string): void; /** * Registers a category for a legacy command that doesn't use the CommandRegistry. * This is used for commands like `containers`, etc, that use the old yargs pattern. */ registerLegacyCommandCategory(command: string, category: MetadataCategory): void; } /** * Type for the function used to register commands. */ type RegisterCommand = (segment: string, def: InternalDefinition, registerSubTreeCallback: () => void) => void; declare function createCLIParser(argv: string[]): { wrangler: CommonYargsArgv; registry: CommandRegistry; globalFlags: { readonly v: { readonly describe: "Show version number"; readonly alias: "version"; readonly type: "boolean"; }; readonly cwd: { readonly describe: "Run as if Wrangler was started in the specified directory instead of the current working directory"; readonly type: "string"; readonly requiresArg: true; }; readonly config: { readonly alias: "c"; readonly describe: "Path to Wrangler configuration file"; readonly type: "string"; readonly requiresArg: true; }; readonly env: { readonly alias: "e"; readonly describe: "Environment to use for operations, and for selecting .env and .dev.vars files"; readonly type: "string"; readonly requiresArg: true; }; readonly "env-file": { readonly describe: "Path to an .env file to load - can be specified multiple times - values from earlier files are overridden by values in later files"; readonly type: "string"; readonly array: true; readonly requiresArg: true; }; readonly "experimental-provision": { readonly describe: "Experimental: Enable automatic resource provisioning"; readonly type: "boolean"; readonly default: true; readonly hidden: true; readonly alias: readonly ["x-provision"]; }; readonly "experimental-auto-create": { readonly describe: "Automatically provision draft bindings with new resources"; readonly type: "boolean"; readonly default: true; readonly hidden: true; readonly alias: "x-auto-create"; }; readonly "install-skills": { readonly describe: "Install Cloudflare skills for detected AI coding agents before running the command"; readonly type: "boolean"; readonly default: false; }; readonly profile: { readonly describe: "Use a specific auth profile"; readonly type: "string"; readonly requiresArg: true; }; }; showHelpWithCategories: () => Promise; }; /** * EXPERIMENTAL: Get all registered Wrangler commands for documentation generation. * This API is experimental and may change without notice. * * @returns An object containing the command tree structure and global flags */ declare function experimental_getWranglerCommands(): { registry: DefinitionTreeNode; globalFlags: ReturnType["globalFlags"]; }; /** * This file is the main entrypoint for the CLI, which calls `main()` from `index.ts`. * It also re-exports the public API of the package. */ interface Unstable_ASSETSBindingsOptions { log: Logger; proxyPort?: number; directory?: string; signal?: AbortSignal; } declare const unstable_generateASSETSBinding: (opts: Unstable_ASSETSBindingsOptions) => (request: Request) => Promise; export { ArgParseError, type Experimental_GenerateTypesOptions, type Experimental_GenerateTypesResult, type GetPlatformProxyOptions, type PlatformProxy, type RemoteProxySession, type SourcelessWorkerOptions, type StartRemoteProxySessionOptions, type TestHarness, type TestHarnessOptions, type Unstable_ASSETSBindingsOptions, type Config as Unstable_Config, type Unstable_DevOptions, type Unstable_DevWorker, type Unstable_MiniflareWorkerOptions, type RawConfig as Unstable_RawConfig, type RawEnvironment as Unstable_RawEnvironment, type WorkerHandle, createTestHarness, generateTypes as experimental_generateTypes, experimental_getWranglerCommands, getPlatformProxy, maybeStartOrUpdateRemoteProxySession, parseArgs as parseCfWranglerArgs, parseBuildArgs as parseCfWranglerBuildArgs, runCfWranglerBuild, runCfWranglerDev, startRemoteProxySession, DevEnv as unstable_DevEnv, convertConfigBindingsToStartWorkerBindings as unstable_convertConfigBindingsToStartWorkerBindings, unstable_dev, unstable_generateASSETSBinding, unstable_getDevCompatibilityDate, getDurableObjectClassNameToUseSQLiteMap as unstable_getDurableObjectClassNameToUseSQLiteMap, unstable_getMiniflareWorkerOptions, getVarsForDev as unstable_getVarsForDev, unstable_pages, readConfig as unstable_readConfig, resolveNamedTunnel as unstable_resolveNamedTunnel, splitSqlQuery as unstable_splitSqlQuery, startWorker as unstable_startWorker };