type Result< T, E = Error > = { readonly ok: true; readonly value: T; } | { readonly ok: false; readonly error: E; }; declare function Ok(value: T): Result; declare function Err(error: E): Result; declare function isOk< T, E >(result: Result): result is { ok: true; value: T; }; declare function isErr< T, E >(result: Result): result is { ok: false; error: E; }; declare function unwrap< T, E >(result: Result): T; type InferOk = R extends Result ? T : never; type InferErr = R extends Result ? E : never; type AsyncResult< T, E = Error > = Promise>; declare const __brand: unique symbol; type Brand< T, B extends string > = T & { readonly [__brand]: B; }; /** A KV namespace key */ type KVKey = Brand; /** A D1 row identifier */ type D1RowId = Brand; /** An R2 object key */ type R2ObjectKey = Brand; /** A Durable Object ID (hex string) */ type DurableObjectId = Brand; /** A Queue message ID */ type QueueMessageId = Brand; declare function kvKey(key: string): KVKey; declare function d1RowId(id: string): D1RowId; declare function r2ObjectKey(key: string): R2ObjectKey; declare function durableObjectId(id: string): DurableObjectId; declare function queueMessageId(id: string): QueueMessageId; type Branded< T, B extends string > = Brand; declare function brand< T, B extends string >(value: T): Branded; /** A KV namespace with typed values. Wraps KVNamespace from @cloudflare/workers-types. */ interface TypedKVNamespace { /** The underlying untyped KV binding */ readonly raw: KVNamespace; get(key: string): Promise; getWithMetadata(key: string): Promise<{ value: T | null; metadata: M | null; }>; put(key: string, value: T, options?: KVNamespacePutOptions): Promise; delete(key: string): Promise; list(options?: KVNamespaceListOptions): Promise>; } /** Type-safe D1 query result */ interface TypedD1Result { results: T[]; success: boolean; meta: D1Meta; error?: string; } /** D1 meta information */ interface D1Meta { changed_db: boolean; changes: number; duration: number; last_row_id: number; rows_read: number; rows_written: number; size_after: number; } /** R2 object with typed custom metadata */ interface TypedR2Object = Record> { key: string; version: string; size: number; etag: string; httpEtag: string; uploaded: Date; httpMetadata?: R2HTTPMetadata; customMetadata: M; checksums: R2Checksums; } /** R2 get result — body + metadata */ interface TypedR2ObjectBody = Record> extends TypedR2Object { body: ReadableStream; bodyUsed: boolean; arrayBuffer(): Promise; text(): Promise; json(): Promise; blob(): Promise; } interface R2HTTPMetadata { contentType?: string; contentLanguage?: string; contentDisposition?: string; contentEncoding?: string; cacheControl?: string; cacheExpiry?: Date; } interface R2Checksums { md5?: ArrayBuffer; sha1?: ArrayBuffer; sha256?: ArrayBuffer; sha384?: ArrayBuffer; sha512?: ArrayBuffer; } /** A typed queue producer */ interface TypedQueue { send(body: Body, options?: QueueSendOptions): Promise; sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; } /** A typed message for sendBatch */ interface TypedMessageSendRequest { body: Body; contentType?: QueueContentType; delaySeconds?: number; } /** A typed message received from a queue */ interface TypedMessage { readonly id: string; readonly timestamp: Date; readonly body: Body; readonly attempts: number; ack(): void; retry(options?: QueueRetryOptions): void; } /** A typed message batch */ interface TypedMessageBatch { readonly queue: string; readonly messages: readonly TypedMessage[]; ackAll(): void; retryAll(options?: QueueRetryOptions): void; } interface QueueSendOptions { contentType?: QueueContentType; delaySeconds?: number; } interface QueueSendBatchOptions { delaySeconds?: number; } interface QueueRetryOptions { delaySeconds?: number; } type QueueContentType = "text" | "bytes" | "json" | "v8"; /** Typed Durable Object storage interface */ interface TypedDurableObjectStorage { get(key: string): Promise; get(keys: string[]): Promise>; put(key: string, value: T): Promise; put(entries: Record): Promise; delete(key: string): Promise; delete(keys: string[]): Promise; deleteAll(): Promise; list(options?: DurableObjectStorageListOptions): Promise>; transaction(closure: (txn: TypedDurableObjectStorage) => Promise): Promise; getAlarm(): Promise; setAlarm(scheduledTime: number | Date): Promise; deleteAlarm(): Promise; } interface DurableObjectStorageListOptions { start?: string; startAfter?: string; end?: string; prefix?: string; reverse?: boolean; limit?: number; allowConcurrency?: boolean; noCache?: boolean; } interface KVNamespacePutOptions { expiration?: number; expirationTtl?: number; metadata?: unknown; } interface KVNamespaceListOptions { prefix?: string; limit?: number; cursor?: string; } interface KVNamespaceListResult { keys: KVNamespaceListKey[]; list_complete: boolean; cursor?: string; cacheStatus: string | null; } interface KVNamespaceListKey { name: string; expiration?: number; metadata?: T; } /** The Standard Schema interface. */ interface StandardSchemaV1< Input = unknown, Output = Input > { /** The Standard Schema properties. */ readonly "~standard": StandardSchemaV1.Props; } /** A binding definition — either a Standard Schema validator or a binding type checker */ type BindingDef = StandardSchemaV1 | BindingTypeCheck; /** Binding type check for CF-specific bindings (KV, D1, R2, etc.) */ interface BindingTypeCheck { readonly __bindingType: string; readonly validate: (value: unknown) => boolean; } /** An env schema — mapping of binding names to their definitions */ type EnvSchema = Record; /** Infer the parsed env type from a schema definition */ type InferEnv = { [K in keyof S] : S[K] extends StandardSchemaV1 ? O : S[K] extends BindingTypeCheck ? InferBindingType : unknown }; /** Map binding type check to its runtime type */ type InferBindingType = B["__bindingType"] extends "KVNamespace" ? KVNamespace : B["__bindingType"] extends "D1Database" ? D1Database : B["__bindingType"] extends "R2Bucket" ? R2Bucket : B["__bindingType"] extends "DurableObjectNamespace" ? DurableObjectNamespace : B["__bindingType"] extends "Queue" ? Queue : B["__bindingType"] extends "Fetcher" ? Fetcher : B["__bindingType"] extends "AnalyticsEngineDataset" ? AnalyticsEngineDataset : unknown; interface EnvParseSuccess { readonly success: true; readonly env: T; } interface EnvParseFailure { readonly success: false; readonly errors: EnvValidationError[]; } interface EnvValidationError { readonly binding: string; readonly message: string; readonly expected: string; readonly received: string; } type EnvParseResult = EnvParseSuccess | EnvParseFailure; type JsonPrimitive = string | number | boolean | null; type JsonValue = JsonPrimitive | JsonObject | JsonArray; interface JsonObject { [key: string]: JsonValue; } type JsonArray = JsonValue[]; /** * Constrains T to be JSON-serializable. * Use as a bound: `function store>(value: T)` * This catches functions, symbols, undefined, BigInt, etc. at compile time. */ type JsonSerializable = T extends JsonPrimitive ? T : T extends readonly (infer U)[] ? JsonSerializable[] : T extends Record ? { [K in keyof T] : JsonSerializable } : never; type JsonParsed = T extends string ? JsonValue : T extends JsonValue ? T : never; type DeepPartial = T extends JsonPrimitive ? T : T extends readonly (infer U)[] ? readonly DeepPartial[] : T extends Record ? { [K in keyof T]? : DeepPartial } : T; type DeepReadonly = T extends JsonPrimitive ? T : T extends readonly (infer U)[] ? readonly DeepReadonly[] : T extends Record ? { readonly [K in keyof T] : DeepReadonly } : T; /** A Workers fetch handler, parameterized by env type */ type WorkerFetchHandler = (request: Request, env: E, ctx: ExecutionContext) => Response | Promise; /** A Workers scheduled handler */ type WorkerScheduledHandler = (event: ScheduledEvent, env: E, ctx: ExecutionContext) => void | Promise; /** A Workers queue handler */ type WorkerQueueHandler< E = unknown, Body = unknown > = (batch: TypedMessageBatch, env: E, ctx: ExecutionContext) => void | Promise; /** A Workers email handler */ type WorkerEmailHandler = (message: EmailMessage, env: E, ctx: ExecutionContext) => void | Promise; /** Complete Workers module */ interface WorkerModule { fetch?: WorkerFetchHandler; scheduled?: WorkerScheduledHandler; queue?: WorkerQueueHandler; email?: WorkerEmailHandler; tail?: (events: TraceItem[], env: E, ctx: ExecutionContext) => void | Promise; trace?: (traces: TraceItem[], env: E, ctx: ExecutionContext) => void | Promise; } interface ExecutionContext { waitUntil(promise: Promise): void; passThroughOnException(): void; abort(reason?: any): void; } interface ScheduledEvent { scheduledTime: number; cron: string; noRetry(): void; } interface EmailMessage { readonly from: string; readonly to: string; readonly headers: Headers; readonly raw: ReadableStream; readonly rawSize: number; setReject(reason: string): void; forward(rcptTo: string, headers?: Headers): Promise; } interface TraceItem { readonly event: TraceEvent | null; readonly eventTimestamp: number | null; readonly logs: TraceLog[]; readonly exceptions: TraceException[]; readonly scriptName: string | null; readonly scriptVersion?: string; readonly dispatchNamespace?: string; readonly scriptTags?: string[]; readonly outcome: string; } interface TraceEvent { [key: string]: unknown; } interface TraceLog { timestamp: number; level: string; message: JsonValue; } interface TraceException { timestamp: number; name: string; message: string; } /** A value that may or may not be wrapped in a Promise */ type MaybePromise = T | Promise; /** Extract the resolved type from a Promise */ type Awaited = T extends Promise ? U : T; /** Flatten an intersection into a single object type (improves IDE display) */ type Prettify = { [K in keyof T] : T[K] } & {}; /** Make specific keys required */ type RequireKeys< T, K extends keyof T > = Prettify & Required>>; /** Make specific keys optional */ type OptionalKeys< T, K extends keyof T > = Prettify & Partial>>; /** Extract keys whose values extend a given type */ type KeysMatching< T, V > = { [K in keyof T]-? : T[K] extends V ? K : never }[keyof T]; /** Enforce a string starts with a given prefix */ type StringWithPrefix

= `${P}${string}`; /** KV key with prefix — e.g., StringWithPrefix<'user:'> */ type PrefixedKey

= StringWithPrefix

; /** A non-empty array */ type NonEmptyArray = [T, ...T[]]; /** Use in switch default to get compile error if a case is missed */ declare function assertNever(value: never): never; /** Like Record but with better inference */ type Dict = Record; /** A readonly dictionary */ type ReadonlyDict = Readonly>; /** A state definition for DO state machines */ interface StateDefinition< States extends string, Events extends string, Context extends Record = Record > { /** All valid states */ states: readonly States[]; /** Initial state */ initial: States; /** Transitions: [currentState, event] -> nextState */ transitions: Record>>; /** Context type for storing data alongside state */ context: Context; } /** Current state of a DO state machine */ interface MachineState< States extends string, Context extends Record = Record > { current: States; context: Context; updatedAt: number; } /** Alarm configuration */ interface AlarmConfig { /** When to fire (absolute timestamp or relative ms) */ scheduledTime: number | Date; /** Retry configuration */ retry?: { maxAttempts: number; backoffMs: number; }; } /** Alarm handler result */ interface AlarmResult { /** Whether the alarm was handled successfully */ success: boolean; /** If failed, optional next alarm to schedule */ reschedule?: AlarmConfig; } /** Typed WebSocket message */ type WSMessage = { type: "text"; data: string; } | { type: "binary"; data: ArrayBuffer; } | { type: "json"; data: T; }; /** WebSocket event handlers for hibernatable DOs */ interface HibernatableWSHandlers { onMessage?(ws: WebSocket, message: WSMessage): MaybePromise; onClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): MaybePromise; onError?(ws: WebSocket, error: unknown): MaybePromise; } export { unwrap, r2ObjectKey, queueMessageId, kvKey, isOk, isErr, durableObjectId, d1RowId, brand, assertNever, WorkerScheduledHandler, WorkerQueueHandler, WorkerModule, WorkerFetchHandler, WorkerEmailHandler, WSMessage, TypedR2ObjectBody, TypedR2Object, TypedQueue, TypedMessageSendRequest, TypedMessageBatch, TypedMessage, TypedKVNamespace, TypedDurableObjectStorage, TypedD1Result, TraceLog, TraceItem, TraceException, TraceEvent, StringWithPrefix, StateDefinition, ScheduledEvent, Result, RequireKeys, ReadonlyDict, R2ObjectKey, R2HTTPMetadata, R2Checksums, QueueSendOptions, QueueSendBatchOptions, QueueRetryOptions, QueueMessageId, QueueContentType, Prettify, PrefixedKey, OptionalKeys, Ok, NonEmptyArray, MaybePromise, MachineState, KeysMatching, KVNamespacePutOptions, KVNamespaceListResult, KVNamespaceListOptions, KVNamespaceListKey, KVKey, JsonValue, JsonSerializable, JsonPrimitive, JsonParsed, JsonObject, JsonArray, InferOk, InferErr, InferEnv, InferBindingType, HibernatableWSHandlers, ExecutionContext, Err, EnvValidationError, EnvSchema, EnvParseSuccess, EnvParseResult, EnvParseFailure, EmailMessage, DurableObjectStorageListOptions, DurableObjectId, Dict, DeepReadonly, DeepPartial, D1RowId, D1Meta, Branded, BindingTypeCheck, BindingDef, Awaited, AsyncResult, AlarmResult, AlarmConfig };