Skip to content
File

Blob: worker-configuration.d.ts

typescript15405 lines
1/* eslint-disable */
2// Generated by Wrangler by running `wrangler types --env-file=.dev.vars.example` (hash: bb971ab37a9fdbccd3ec95b1c6c1c354)
3// Runtime types generated with workerd@1.20260908.1 2026-03-16 nodejs_compat
4interface __BaseEnv_Env {
5 SESSIONS: KVNamespace;
6 LOG_TICKETS: KVNamespace;
7 DB: D1Database;
8 RUN_QUEUE: Queue;
9 ASSETS: Fetcher;
10 AUTH_SESSION_TTL_SECONDS: "21600";
11 AUTH_SESSION_REFRESH_THRESHOLD_SECONDS: "3600";
12 SESSION_VERSION: "1";
13 SANDBOX_TRANSPORT: "rpc";
14 APP_ENCRYPTION_KEY_CURRENT_VERSION: string;
15 APP_ENCRYPTION_KEYS_JSON: string;
16 TESSERA_OIDC_ISSUER: string;
17 TESSERA_OIDC_CLIENT_ID: string;
18 TESSERA_OIDC_CLIENT_SECRET: string;
19 PROJECT_DO: DurableObjectNamespace<import("./src/worker/index").ProjectDO>;
20 RUN_DO: DurableObjectNamespace<import("./src/worker/index").RunDO>;
21 Sandbox: DurableObjectNamespace<import("./src/worker/index").Sandbox>;
22 RUN_WORKFLOWS: Workflow<Parameters<import("./src/worker/index").RunWorkflows['run']>[0]['payload']>;
23}
24declare namespace Cloudflare {
25 interface GlobalProps {
26 mainModule: typeof import("./src/worker/index");
27 durableNamespaces: "ProjectDO" | "RunDO" | "Sandbox";
28 }
29 interface Env extends __BaseEnv_Env {}
30}
31interface Env extends __BaseEnv_Env {}
32type StringifyValues<EnvType extends Record<string, unknown>> = {
33 [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;
34};
35declare namespace NodeJS {
36 interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "AUTH_SESSION_TTL_SECONDS" | "AUTH_SESSION_REFRESH_THRESHOLD_SECONDS" | "SESSION_VERSION" | "SANDBOX_TRANSPORT" | "APP_ENCRYPTION_KEY_CURRENT_VERSION" | "APP_ENCRYPTION_KEYS_JSON" | "TESSERA_OIDC_ISSUER" | "TESSERA_OIDC_CLIENT_ID" | "TESSERA_OIDC_CLIENT_SECRET">> {}
37}
38 
39// Begin runtime types
40/*! *****************************************************************************
41Copyright (c) Cloudflare. All rights reserved.
42Copyright (c) Microsoft Corporation. All rights reserved.
43
44Licensed under the Apache License, Version 2.0 (the "License"); you may not use
45this file except in compliance with the License. You may obtain a copy of the
46License at http://www.apache.org/licenses/LICENSE-2.0
47THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
48KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
49WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
50MERCHANTABLITY OR NON-INFRINGEMENT.
51See the Apache Version 2.0 License for specific language governing permissions
52and limitations under the License.
53***************************************************************************** */
54/* eslint-disable */
55// noinspection JSUnusedGlobalSymbols
56declare var onmessage: never;
57/**
58 * The **`DOMException`** interface represents an abnormal event (called an exception) that occurs as a result of calling a method or accessing a property of a web API. This is how error conditions are described in web APIs.
59 *
60 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException)
61 */
62declare class DOMException extends Error {
63 constructor(message?: string, name?: string);
64 /**
65 * The **`message`** read-only property of the DOMException interface returns a string representing a message or description associated with the given error name.
66 *
67 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message)
68 */
69 readonly message: string;
70 /**
71 * The **`name`** read-only property of the DOMException interface returns a string that contains one of the strings associated with an error name.
72 *
73 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name)
74 */
75 readonly name: string;
76 /**
77 * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or 0 if none match.
78 * @deprecated
79 *
80 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code)
81 */
82 readonly code: number;
83 static readonly INDEX_SIZE_ERR: number;
84 static readonly DOMSTRING_SIZE_ERR: number;
85 static readonly HIERARCHY_REQUEST_ERR: number;
86 static readonly WRONG_DOCUMENT_ERR: number;
87 static readonly INVALID_CHARACTER_ERR: number;
88 static readonly NO_DATA_ALLOWED_ERR: number;
89 static readonly NO_MODIFICATION_ALLOWED_ERR: number;
90 static readonly NOT_FOUND_ERR: number;
91 static readonly NOT_SUPPORTED_ERR: number;
92 static readonly INUSE_ATTRIBUTE_ERR: number;
93 static readonly INVALID_STATE_ERR: number;
94 static readonly SYNTAX_ERR: number;
95 static readonly INVALID_MODIFICATION_ERR: number;
96 static readonly NAMESPACE_ERR: number;
97 static readonly INVALID_ACCESS_ERR: number;
98 static readonly VALIDATION_ERR: number;
99 static readonly TYPE_MISMATCH_ERR: number;
100 static readonly SECURITY_ERR: number;
101 static readonly NETWORK_ERR: number;
102 static readonly ABORT_ERR: number;
103 static readonly URL_MISMATCH_ERR: number;
104 static readonly QUOTA_EXCEEDED_ERR: number;
105 static readonly TIMEOUT_ERR: number;
106 static readonly INVALID_NODE_TYPE_ERR: number;
107 static readonly DATA_CLONE_ERR: number;
108 get stack(): any;
109 set stack(value: any);
110}
111type WorkerGlobalScopeEventMap = {
112 fetch: FetchEvent;
113 scheduled: ScheduledEvent;
114 queue: QueueEvent;
115 unhandledrejection: PromiseRejectionEvent;
116 rejectionhandled: PromiseRejectionEvent;
117};
118declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> {
119 EventTarget: typeof EventTarget;
120}
121/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). *
122 * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox).
123 *
124 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console)
125 */
126interface Console {
127 "assert"(condition?: boolean, ...data: any[]): void;
128 /**
129 * The **`console.clear()`** static method clears the console if possible.
130 *
131 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static)
132 */
133 clear(): void;
134 /**
135 * The **`console.count()`** static method logs the number of times that this particular call to count() has been called.
136 *
137 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static)
138 */
139 count(label?: string): void;
140 /**
141 * The **`console.countReset()`** static method resets counter used with console.count().
142 *
143 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static)
144 */
145 countReset(label?: string): void;
146 /**
147 * The **`console.debug()`** static method outputs a message to the console at the "debug" log level. The message is only displayed to the user if the console is configured to display debug output. In most cases, the log level is configured within the console UI. This log level might correspond to the Debug or Verbose log level.
148 *
149 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static)
150 */
151 debug(...data: any[]): void;
152 /**
153 * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. In browser consoles, the output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.
154 *
155 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static)
156 */
157 dir(item?: any, options?: any): void;
158 /**
159 * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. If it is not possible to display as an element the JavaScript Object view is shown instead. The output is presented as a hierarchical listing of expandable nodes that let you see the contents of child nodes.
160 *
161 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static)
162 */
163 dirxml(...data: any[]): void;
164 /**
165 * The **`console.error()`** static method outputs a message to the console at the "error" log level. The message is only displayed to the user if the console is configured to display error output. In most cases, the log level is configured within the console UI. The message may be formatted as an error, with red colors and call stack information.
166 *
167 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)
168 */
169 error(...data: any[]): void;
170 /**
171 * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console.groupEnd() is called.
172 *
173 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static)
174 */
175 group(...data: any[]): void;
176 /**
177 * The **`console.groupCollapsed()`** static method creates a new inline group in the console. Unlike console.group(), however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group.
178 *
179 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static)
180 */
181 groupCollapsed(...data: any[]): void;
182 /**
183 * The **`console.groupEnd()`** static method exits the current inline group in the console. See Using groups in the console in the console documentation for details and examples.
184 *
185 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static)
186 */
187 groupEnd(): void;
188 /**
189 * The **`console.info()`** static method outputs a message to the console at the "info" log level. The message is only displayed to the user if the console is configured to display info output. In most cases, the log level is configured within the console UI. The message may receive special formatting, such as a small "i" icon next to it.
190 *
191 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static)
192 */
193 info(...data: any[]): void;
194 /**
195 * The **`console.log()`** static method outputs a message to the console.
196 *
197 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
198 */
199 log(...data: any[]): void;
200 /**
201 * The **`console.table()`** static method displays tabular data as a table.
202 *
203 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static)
204 */
205 table(tabularData?: any, properties?: string[]): void;
206 /**
207 * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. You give each timer a unique name, and may have up to 10,000 timers running on a given page. When you call console.timeEnd() with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.
208 *
209 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static)
210 */
211 time(label?: string): void;
212 /**
213 * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console.time().
214 *
215 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static)
216 */
217 timeEnd(label?: string): void;
218 /**
219 * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console.time().
220 *
221 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static)
222 */
223 timeLog(label?: string, ...data: any[]): void;
224 /* The **`console.timeStamp()`** static method adds a single marker to the browser's Performance tool (Firefox bug 1387528, Chrome). This lets you correlate a point in your code with the other events recorded in the timeline, such as layout and paint events. */
225 timeStamp(label?: string): void;
226 /**
227 * The **`console.trace()`** static method outputs a stack trace to the console.
228 *
229 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static)
230 */
231 trace(...data: any[]): void;
232 /**
233 * The **`console.warn()`** static method outputs a warning message to the console at the "warning" log level. The message is only displayed to the user if the console is configured to display warning output. In most cases, the log level is configured within the console UI. The message may receive special formatting, such as yellow colors and a warning icon.
234 *
235 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static)
236 */
237 warn(...data: any[]): void;
238}
239declare const console: Console;
240type BufferSource = ArrayBufferView | ArrayBuffer;
241type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
242declare namespace WebAssembly {
243 class CompileError extends Error {
244 constructor(message?: string);
245 }
246 class RuntimeError extends Error {
247 constructor(message?: string);
248 }
249 type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128";
250 interface GlobalDescriptor {
251 value: ValueType;
252 mutable?: boolean;
253 }
254 class Global {
255 constructor(descriptor: GlobalDescriptor, value?: any);
256 value: any;
257 valueOf(): any;
258 }
259 type ImportValue = ExportValue | number;
260 type ModuleImports = Record<string, ImportValue>;
261 type Imports = Record<string, ModuleImports>;
262 type ExportValue = Function | Global | Memory | Table;
263 type Exports = Record<string, ExportValue>;
264 class Instance {
265 constructor(module: Module, imports?: Imports);
266 readonly exports: Exports;
267 }
268 interface MemoryDescriptor {
269 initial: number;
270 maximum?: number;
271 shared?: boolean;
272 }
273 class Memory {
274 constructor(descriptor: MemoryDescriptor);
275 readonly buffer: ArrayBuffer;
276 grow(delta: number): number;
277 }
278 type ImportExportKind = "function" | "global" | "memory" | "table";
279 interface ModuleExportDescriptor {
280 kind: ImportExportKind;
281 name: string;
282 }
283 interface ModuleImportDescriptor {
284 kind: ImportExportKind;
285 module: string;
286 name: string;
287 }
288 abstract class Module {
289 static customSections(module: Module, sectionName: string): ArrayBuffer[];
290 static exports(module: Module): ModuleExportDescriptor[];
291 static imports(module: Module): ModuleImportDescriptor[];
292 }
293 type TableKind = "anyfunc" | "externref";
294 interface TableDescriptor {
295 element: TableKind;
296 initial: number;
297 maximum?: number;
298 }
299 class Table {
300 constructor(descriptor: TableDescriptor, value?: any);
301 readonly length: number;
302 get(index: number): any;
303 grow(delta: number, value?: any): number;
304 set(index: number, value?: any): void;
305 }
306 function instantiate(module: Module, imports?: Imports): Promise<Instance>;
307 function validate(bytes: BufferSource): boolean;
308}
309/**
310 * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker.
311 * Available only in secure contexts.
312 *
313 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope)
314 */
315interface ServiceWorkerGlobalScope extends WorkerGlobalScope {
316 DOMException: typeof DOMException;
317 WorkerGlobalScope: typeof WorkerGlobalScope;
318 btoa(data: string): string;
319 atob(data: string): string;
320 setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;
321 setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
322 clearTimeout(timeoutId: number | null): void;
323 setInterval(callback: (...args: any[]) => void, msDelay?: number): number;
324 setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
325 clearInterval(timeoutId: number | null): void;
326 queueMicrotask(task: Function): void;
327 structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;
328 reportError(error: any): void;
329 fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;
330 self: ServiceWorkerGlobalScope;
331 crypto: Crypto;
332 caches: CacheStorage;
333 scheduler: Scheduler;
334 performance: Performance;
335 Cloudflare: Cloudflare;
336 readonly origin: string;
337 Event: typeof Event;
338 ExtendableEvent: typeof ExtendableEvent;
339 CustomEvent: typeof CustomEvent;
340 PromiseRejectionEvent: typeof PromiseRejectionEvent;
341 FetchEvent: typeof FetchEvent;
342 TailEvent: typeof TailEvent;
343 TraceEvent: typeof TailEvent;
344 ScheduledEvent: typeof ScheduledEvent;
345 MessageEvent: typeof MessageEvent;
346 CloseEvent: typeof CloseEvent;
347 ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader;
348 ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader;
349 ReadableStream: typeof ReadableStream;
350 WritableStream: typeof WritableStream;
351 WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter;
352 TransformStream: typeof TransformStream;
353 ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy;
354 CountQueuingStrategy: typeof CountQueuingStrategy;
355 ErrorEvent: typeof ErrorEvent;
356 MessageChannel: typeof MessageChannel;
357 MessagePort: typeof MessagePort;
358 EventSource: typeof EventSource;
359 ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest;
360 ReadableStreamDefaultController: typeof ReadableStreamDefaultController;
361 ReadableByteStreamController: typeof ReadableByteStreamController;
362 WritableStreamDefaultController: typeof WritableStreamDefaultController;
363 TransformStreamDefaultController: typeof TransformStreamDefaultController;
364 CompressionStream: typeof CompressionStream;
365 DecompressionStream: typeof DecompressionStream;
366 TextEncoderStream: typeof TextEncoderStream;
367 TextDecoderStream: typeof TextDecoderStream;
368 Headers: typeof Headers;
369 Body: typeof Body;
370 Request: typeof Request;
371 Response: typeof Response;
372 WebSocket: typeof WebSocket;
373 WebSocketPair: typeof WebSocketPair;
374 WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair;
375 AbortController: typeof AbortController;
376 AbortSignal: typeof AbortSignal;
377 TextDecoder: typeof TextDecoder;
378 TextEncoder: typeof TextEncoder;
379 navigator: Navigator;
380 Navigator: typeof Navigator;
381 URL: typeof URL;
382 URLSearchParams: typeof URLSearchParams;
383 URLPattern: typeof URLPattern;
384 Blob: typeof Blob;
385 File: typeof File;
386 FormData: typeof FormData;
387 Crypto: typeof Crypto;
388 SubtleCrypto: typeof SubtleCrypto;
389 CryptoKey: typeof CryptoKey;
390 CacheStorage: typeof CacheStorage;
391 Cache: typeof Cache;
392 FixedLengthStream: typeof FixedLengthStream;
393 IdentityTransformStream: typeof IdentityTransformStream;
394 HTMLRewriter: typeof HTMLRewriter;
395}
396declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;
397declare function removeEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;
398/**
399 * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().
400 *
401 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)
402 */
403declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean;
404/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */
405declare function btoa(data: string): string;
406/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */
407declare function atob(data: string): string;
408/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */
409declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;
410/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */
411declare function setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
412/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */
413declare function clearTimeout(timeoutId: number | null): void;
414/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */
415declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number;
416/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */
417declare function setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
418/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */
419declare function clearInterval(timeoutId: number | null): void;
420/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */
421declare function queueMicrotask(task: Function): void;
422/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */
423declare function structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;
424/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */
425declare function reportError(error: any): void;
426/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */
427declare function fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;
428declare const self: ServiceWorkerGlobalScope;
429/**
430* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.
431* The Workers runtime implements the full surface of this API, but with some differences in
432* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)
433* compared to those implemented in most browsers.
434*
435* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)
436*/
437declare const crypto: Crypto;
438/**
439* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.
440*
441* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)
442*/
443declare const caches: CacheStorage;
444/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/scheduler) */
445declare const scheduler: Scheduler;
446/**
447* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,
448* as well as timing of subrequests and other operations.
449*
450* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)
451*/
452declare const performance: Performance;
453declare const Cloudflare: Cloudflare;
454declare const origin: string;
455declare const navigator: Navigator;
456interface TestController {
457}
458interface ExecutionContext<Props = unknown> {
459 waitUntil(promise: Promise<any>): void;
460 passThroughOnException(): void;
461 readonly exports: Cloudflare.Exports;
462 readonly props: Props;
463 cache?: CacheContext;
464 readonly access?: CloudflareAccessContext;
465 tracing: Tracing;
466 abort(reason?: any): void;
467}
468type ExportedHandlerFetchHandler<Env = unknown, CfHostMetadata = unknown, Props = unknown> = (request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, env: Env, ctx: ExecutionContext<Props>) => Response | Promise<Response>;
469type ExportedHandlerConnectHandler<Env = unknown, Props = unknown> = (socket: Socket, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
470type ExportedHandlerTailHandler<Env = unknown, Props = unknown> = (events: TraceItem[], env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
471type ExportedHandlerTraceHandler<Env = unknown, Props = unknown> = (traces: TraceItem[], env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
472type ExportedHandlerTailStreamHandler<Env = unknown, Props = unknown> = (event: TailStream.TailEvent<TailStream.Onset>, env: Env, ctx: ExecutionContext<Props>) => TailStream.TailEventHandlerType | Promise<TailStream.TailEventHandlerType>;
473type ExportedHandlerScheduledHandler<Env = unknown, Props = unknown> = (controller: ScheduledController, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
474type ExportedHandlerQueueHandler<Env = unknown, Message = unknown, Props = unknown> = (batch: MessageBatch<Message>, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
475type ExportedHandlerTestHandler<Env = unknown, Props = unknown> = (controller: TestController, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
476interface ExportedHandler<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown, Props = unknown> {
477 fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata, Props>;
478 connect?: ExportedHandlerConnectHandler<Env, Props>;
479 tail?: ExportedHandlerTailHandler<Env, Props>;
480 trace?: ExportedHandlerTraceHandler<Env, Props>;
481 tailStream?: ExportedHandlerTailStreamHandler<Env, Props>;
482 scheduled?: ExportedHandlerScheduledHandler<Env, Props>;
483 test?: ExportedHandlerTestHandler<Env, Props>;
484 email?: EmailExportedHandler<Env, Props>;
485 queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage, Props>;
486}
487interface StructuredSerializeOptions {
488 transfer?: any[];
489}
490declare abstract class Navigator {
491 sendBeacon(url: string, body?: BodyInit): boolean;
492 readonly userAgent: string;
493 readonly hardwareConcurrency: number;
494 readonly platform: string;
495 readonly language: string;
496 readonly languages: string[];
497}
498interface AlarmInvocationInfo {
499 readonly isRetry: boolean;
500 readonly retryCount: number;
501 readonly scheduledTime: number;
502}
503interface Cloudflare {
504 readonly compatibilityFlags: Record<string, boolean>;
505}
506interface CachePurgeError {
507 code: number;
508 message: string;
509}
510interface CachePurgeResult {
511 success: boolean;
512 errors: CachePurgeError[];
513}
514interface CachePurgeOptions {
515 tags?: string[];
516 pathPrefixes?: string[];
517 purgeEverything?: boolean;
518}
519interface CacheContext {
520 purge(options: CachePurgeOptions): Promise<CachePurgeResult>;
521}
522interface CloudflareAccessContext {
523 readonly aud: string;
524 getIdentity(): Promise<CloudflareAccessIdentity | undefined>;
525}
526declare abstract class ColoLocalActorNamespace {
527 get(actorId: string): Fetcher;
528}
529interface DurableObject {
530 fetch(request: Request): Response | Promise<Response>;
531 connect?(socket: Socket): void | Promise<void>;
532 alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;
533 webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;
534 webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;
535 webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;
536}
537type DurableObjectStub<T extends Rpc.DurableObjectBranded | undefined = undefined> = Fetcher<T, "alarm" | "connect" | "webSocketMessage" | "webSocketClose" | "webSocketError"> & {
538 readonly id: DurableObjectId;
539 readonly name?: string;
540};
541interface DurableObjectId {
542 toString(): string;
543 equals(other: DurableObjectId): boolean;
544 readonly name?: string;
545 readonly jurisdiction?: string;
546}
547declare abstract class DurableObjectNamespace<T extends Rpc.DurableObjectBranded | undefined = undefined> {
548 newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId;
549 idFromName(name: string): DurableObjectId;
550 idFromString(id: string): DurableObjectId;
551 get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;
552 getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;
553 jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace<T>;
554}
555type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high" | "us";
556interface DurableObjectNamespaceNewUniqueIdOptions {
557 jurisdiction?: DurableObjectJurisdiction;
558}
559type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "apac-ne" | "apac-se" | "oc" | "afr" | "me";
560type DurableObjectRoutingMode = "primary-only";
561interface DurableObjectNamespaceGetDurableObjectOptions {
562 locationHint?: DurableObjectLocationHint;
563 routingMode?: DurableObjectRoutingMode;
564}
565interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> {
566}
567interface DurableObjectState<Props = unknown> {
568 waitUntil(promise: Promise<any>): void;
569 readonly exports: Cloudflare.Exports;
570 readonly props: Props;
571 readonly id: DurableObjectId;
572 readonly storage: DurableObjectStorage;
573 container?: Container;
574 facets: DurableObjectFacets;
575 blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>;
576 acceptWebSocket(ws: WebSocket, tags?: string[]): void;
577 getWebSockets(tag?: string): WebSocket[];
578 setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void;
579 getWebSocketAutoResponse(): WebSocketRequestResponsePair | null;
580 getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null;
581 setHibernatableWebSocketEventTimeout(timeoutMs?: number): void;
582 getHibernatableWebSocketEventTimeout(): number | null;
583 getTags(ws: WebSocket): string[];
584 abort(reason?: string, options?: DurableObjectAbortOptions): void;
585}
586interface DurableObjectTransaction {
587 get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;
588 get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;
589 list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;
590 put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;
591 put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;
592 delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;
593 delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;
594 rollback(): void;
595 getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;
596 setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;
597 deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;
598}
599interface DurableObjectStorage {
600 get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;
601 get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;
602 list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;
603 put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;
604 put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;
605 delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;
606 delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;
607 deleteAll(options?: DurableObjectPutOptions): Promise<void>;
608 transaction<T>(closure: (txn: DurableObjectTransaction) => Promise<T>): Promise<T>;
609 getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;
610 setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;
611 deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;
612 sync(): Promise<void>;
613 sql: SqlStorage;
614 kv: SyncKvStorage;
615 transactionSync<T>(closure: () => T): T;
616 getCurrentBookmark(): Promise<string>;
617 getBookmarkForTime(timestamp: number | Date): Promise<string>;
618 onNextSessionRestoreBookmark(bookmark: string): Promise<string>;
619}
620interface DurableObjectAbortOptions {
621 retryAlarm?: boolean;
622}
623interface DurableObjectListOptions {
624 start?: string;
625 startAfter?: string;
626 end?: string;
627 prefix?: string;
628 reverse?: boolean;
629 limit?: number;
630 allowConcurrency?: boolean;
631 noCache?: boolean;
632}
633interface DurableObjectGetOptions {
634 allowConcurrency?: boolean;
635 noCache?: boolean;
636}
637interface DurableObjectGetAlarmOptions {
638 allowConcurrency?: boolean;
639}
640interface DurableObjectPutOptions {
641 allowConcurrency?: boolean;
642 allowUnconfirmed?: boolean;
643 noCache?: boolean;
644}
645interface DurableObjectSetAlarmOptions {
646 allowConcurrency?: boolean;
647 allowUnconfirmed?: boolean;
648}
649declare class WebSocketRequestResponsePair {
650 constructor(request: string, response: string);
651 get request(): string;
652 get response(): string;
653}
654interface DurableObjectFacets {
655 get<T extends Rpc.DurableObjectBranded | undefined = undefined>(name: string, getStartupOptions: () => FacetStartupOptions<T> | Promise<FacetStartupOptions<T>>): Fetcher<T>;
656 abort(name: string, reason: any): void;
657 delete(name: string): void;
658 clone(src: string, dst: string): void;
659}
660interface FacetStartupOptions<T extends Rpc.DurableObjectBranded | undefined = undefined> {
661 id?: DurableObjectId | string;
662 class: DurableObjectClass<T>;
663}
664interface AnalyticsEngineDataset {
665 writeDataPoint(event?: AnalyticsEngineDataPoint): void;
666}
667interface AnalyticsEngineDataPoint {
668 indexes?: ((ArrayBuffer | string) | null)[];
669 doubles?: number[];
670 blobs?: ((ArrayBuffer | string) | null)[];
671}
672/**
673 * The **`Event`** interface represents an event which takes place on an EventTarget.
674 *
675 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event)
676 */
677declare class Event {
678 constructor(type: string, init?: EventInit);
679 /**
680 * The **`type`** read-only property of the Event interface returns a string containing the event's type. It is set when the event is constructed and is the name commonly used to refer to the specific event, such as click, load, or error.
681 *
682 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type)
683 */
684 get type(): string;
685 /**
686 * The **`eventPhase`** read-only property of the Event interface indicates which phase of the event flow is currently being evaluated.
687 *
688 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase)
689 */
690 get eventPhase(): number;
691 /**
692 * The read-only **`composed`** property of the Event interface returns a boolean value which indicates whether or not the event will propagate across the shadow DOM boundary into the standard DOM.
693 *
694 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed)
695 */
696 get composed(): boolean;
697 /**
698 * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not.
699 *
700 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles)
701 */
702 get bubbles(): boolean;
703 /**
704 * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened.
705 *
706 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable)
707 */
708 get cancelable(): boolean;
709 /**
710 * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event.
711 *
712 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented)
713 */
714 get defaultPrevented(): boolean;
715 /**
716 * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not.
717 * @deprecated
718 *
719 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue)
720 */
721 get returnValue(): boolean;
722 /**
723 * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached.
724 *
725 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget)
726 */
727 get currentTarget(): EventTarget | undefined;
728 /**
729 * The read-only **`target`** property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.
730 *
731 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target)
732 */
733 get target(): EventTarget | undefined;
734 /**
735 * The deprecated **`Event.srcElement`** is an alias for the Event.target property. Use Event.target instead.
736 * @deprecated
737 *
738 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement)
739 */
740 get srcElement(): EventTarget | undefined;
741 /**
742 * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created.
743 *
744 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp)
745 */
746 get timeStamp(): number;
747 /**
748 * The **`isTrusted`** read-only property of the Event interface is a boolean value that is true when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and false when the event was dispatched via EventTarget.dispatchEvent(). The only exception is the click event, which initializes the isTrusted property to false in user agents.
749 *
750 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted)
751 */
752 get isTrusted(): boolean;
753 /**
754 * The **`cancelBubble`** property of the Event interface is deprecated. Use Event.stopPropagation() instead. Setting its value to true before returning from an event handler prevents propagation of the event. In later implementations, setting this to false does nothing. See Browser compatibility for details.
755 * @deprecated
756 *
757 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)
758 */
759 get cancelBubble(): boolean;
760 /**
761 * The **`cancelBubble`** property of the Event interface is deprecated. Use Event.stopPropagation() instead. Setting its value to true before returning from an event handler prevents propagation of the event. In later implementations, setting this to false does nothing. See Browser compatibility for details.
762 * @deprecated
763 *
764 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)
765 */
766 set cancelBubble(value: boolean);
767 /**
768 * The **`stopImmediatePropagation()`** method of the Event interface prevents other listeners of the same event from being called.
769 *
770 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation)
771 */
772 stopImmediatePropagation(): void;
773 /**
774 * The **`preventDefault()`** method of the Event interface tells the user agent that the event is being explicitly handled, so its default action, such as page scrolling, link navigation, or pasting text, should not be taken.
775 *
776 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault)
777 */
778 preventDefault(): void;
779 /**
780 * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, see the preventDefault() method. It also does not prevent propagation to other event-handlers of the current element. If you want to stop those, see stopImmediatePropagation().
781 *
782 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation)
783 */
784 stopPropagation(): void;
785 /**
786 * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. This does not include nodes in shadow trees if the shadow root was created with its ShadowRoot.mode closed.
787 *
788 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath)
789 */
790 composedPath(): EventTarget[];
791 static readonly NONE: number;
792 static readonly CAPTURING_PHASE: number;
793 static readonly AT_TARGET: number;
794 static readonly BUBBLING_PHASE: number;
795}
796interface EventInit {
797 bubbles?: boolean;
798 cancelable?: boolean;
799 composed?: boolean;
800}
801type EventListener<EventType extends Event = Event> = (event: EventType) => void;
802interface EventListenerObject<EventType extends Event = Event> {
803 handleEvent(event: EventType): void;
804}
805type EventListenerOrEventListenerObject<EventType extends Event = Event> = EventListener<EventType> | EventListenerObject<EventType>;
806/**
807 * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface.
808 *
809 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget)
810 */
811declare class EventTarget<EventMap extends Record<string, Event> = Record<string, Event>> {
812 constructor();
813 /**
814 * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
815 *
816 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener)
817 */
818 addEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;
819 /**
820 * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal.
821 *
822 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener)
823 */
824 removeEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;
825 /**
826 * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().
827 *
828 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)
829 */
830 dispatchEvent(event: EventMap[keyof EventMap]): boolean;
831}
832interface EventTargetEventListenerOptions {
833 capture?: boolean;
834}
835interface EventTargetAddEventListenerOptions {
836 capture?: boolean;
837 passive?: boolean;
838 once?: boolean;
839 signal?: AbortSignal;
840}
841interface EventTargetHandlerObject {
842 handleEvent: (event: Event) => any | undefined;
843}
844/**
845 * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired.
846 *
847 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController)
848 */
849declare class AbortController {
850 constructor();
851 /**
852 * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired.
853 *
854 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal)
855 */
856 get signal(): AbortSignal;
857 /**
858 * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. This is able to abort fetch requests, the consumption of any response bodies, or streams.
859 *
860 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort)
861 */
862 abort(reason?: any): void;
863}
864/**
865 * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object.
866 *
867 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal)
868 */
869declare abstract class AbortSignal extends EventTarget {
870 /**
871 * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an abort event).
872 *
873 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static)
874 */
875 static abort(reason?: any): AbortSignal;
876 /**
877 * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time.
878 *
879 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static)
880 */
881 static timeout(delay: number): AbortSignal;
882 /**
883 * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. The returned abort signal is aborted when any of the input iterable abort signals are aborted. The abort reason will be set to the reason of the first signal that is aborted. If any of the given abort signals are already aborted then so will be the returned AbortSignal.
884 *
885 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static)
886 */
887 static any(signals: AbortSignal[]): AbortSignal;
888 /**
889 * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (true) or not (false).
890 *
891 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted)
892 */
893 get aborted(): boolean;
894 /**
895 * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason.
896 *
897 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason)
898 */
899 get reason(): any;
900 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */
901 get onabort(): any | null;
902 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */
903 set onabort(value: any | null);
904 /**
905 * The **`throwIfAborted()`** method throws the signal's abort reason if the signal has been aborted; otherwise it does nothing.
906 *
907 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted)
908 */
909 throwIfAborted(): void;
910}
911/**
912 * The **`Scheduler`** interface of the Prioritized Task Scheduling API provides methods for scheduling prioritized tasks.
913 *
914 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Scheduler)
915 */
916interface Scheduler {
917 wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>;
918}
919interface SchedulerWaitOptions {
920 signal?: AbortSignal;
921}
922/**
923 * The **`ExtendableEvent`** interface extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries.
924 *
925 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent)
926 */
927declare abstract class ExtendableEvent extends Event {
928 /**
929 * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. It can also be used to detect whether that work was successful. In service workers, waitUntil() tells the browser that work is ongoing until the promise settles, and it shouldn't terminate the service worker if it wants that work to complete.
930 *
931 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil)
932 */
933 waitUntil(promise: Promise<any>): void;
934}
935/**
936 * The **`CustomEvent`** interface can be used to attach custom data to an event generated by an application.
937 *
938 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent)
939 */
940declare class CustomEvent<T = any> extends Event {
941 constructor(type: string, init?: CustomEventCustomEventInit);
942 /**
943 * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event.
944 *
945 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail)
946 */
947 get detail(): T;
948}
949interface CustomEventCustomEventInit {
950 bubbles?: boolean;
951 cancelable?: boolean;
952 composed?: boolean;
953 detail?: any;
954}
955/**
956 * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data.
957 *
958 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob)
959 */
960declare class Blob {
961 constructor(bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions);
962 /**
963 * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes.
964 *
965 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size)
966 */
967 get size(): number;
968 /**
969 * The **`type`** read-only property of the Blob interface returns the MIME type of the file.
970 *
971 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type)
972 */
973 get type(): string;
974 /**
975 * The **`slice()`** method of the Blob interface creates and returns a new Blob object which contains data from a subset of the blob on which it's called.
976 *
977 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice)
978 */
979 slice(start?: number, end?: number, type?: string): Blob;
980 /**
981 * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer.
982 *
983 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer)
984 */
985 arrayBuffer(): Promise<ArrayBuffer>;
986 /**
987 * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes.
988 *
989 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes)
990 */
991 bytes(): Promise<Uint8Array>;
992 /**
993 * The **`text()`** method of the Blob interface returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8.
994 *
995 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text)
996 */
997 text(): Promise<string>;
998 /**
999 * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the Blob.
1000 *
1001 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream)
1002 */
1003 stream(): ReadableStream;
1004}
1005interface BlobOptions {
1006 type?: string;
1007}
1008/**
1009 * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content.
1010 *
1011 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File)
1012 */
1013declare class File extends Blob {
1014 constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions);
1015 /**
1016 * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property.
1017 *
1018 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name)
1019 */
1020 get name(): string;
1021 /**
1022 * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
1023 *
1024 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified)
1025 */
1026 get lastModified(): number;
1027}
1028interface FileOptions {
1029 type?: string;
1030 lastModified?: number;
1031}
1032/**
1033* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.
1034*
1035* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)
1036*/
1037declare abstract class CacheStorage {
1038 /**
1039 * The **`open()`** method of the CacheStorage interface returns a Promise that resolves to the Cache object matching the cacheName.
1040 *
1041 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open)
1042 */
1043 open(cacheName: string): Promise<Cache>;
1044 readonly default: Cache;
1045}
1046/**
1047* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.
1048*
1049* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)
1050*/
1051declare abstract class Cache {
1052 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */
1053 delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;
1054 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */
1055 match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;
1056 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */
1057 put(request: RequestInfo | URL, response: Response): Promise<void>;
1058}
1059interface CacheQueryOptions {
1060 ignoreMethod?: boolean;
1061}
1062/**
1063* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.
1064* The Workers runtime implements the full surface of this API, but with some differences in
1065* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)
1066* compared to those implemented in most browsers.
1067*
1068* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)
1069*/
1070declare abstract class Crypto {
1071 /**
1072 * The **`Crypto.subtle`** read-only property returns a SubtleCrypto which can then be used to perform low-level cryptographic operations.
1073 * Available only in secure contexts.
1074 *
1075 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle)
1076 */
1077 get subtle(): SubtleCrypto;
1078 /**
1079 * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning).
1080 *
1081 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues)
1082 */
1083 getRandomValues<T extends Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | BigInt64Array | BigUint64Array>(buffer: T): T;
1084 /**
1085 * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.
1086 * Available only in secure contexts.
1087 *
1088 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID)
1089 */
1090 randomUUID(): string;
1091 DigestStream: typeof DigestStream;
1092}
1093/**
1094 * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions.
1095 * Available only in secure contexts.
1096 *
1097 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto)
1098 */
1099declare abstract class SubtleCrypto {
1100 /**
1101 * The **`encrypt()`** method of the SubtleCrypto interface encrypts data.
1102 *
1103 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt)
1104 */
1105 encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;
1106 /**
1107 * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. It takes as arguments a key to decrypt with, some optional extra parameters, and the data to decrypt (also known as "ciphertext"). It returns a Promise which will be fulfilled with the decrypted data (also known as "plaintext").
1108 *
1109 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt)
1110 */
1111 decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;
1112 /**
1113 * The **`sign()`** method of the SubtleCrypto interface generates a digital signature.
1114 *
1115 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign)
1116 */
1117 sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;
1118 /**
1119 * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature.
1120 *
1121 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify)
1122 */
1123 verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise<boolean>;
1124 /**
1125 * The **`digest()`** method of the SubtleCrypto interface generates a digest of the given data, using the specified hash function. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value.
1126 *
1127 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest)
1128 */
1129 digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;
1130 /**
1131 * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms).
1132 *
1133 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey)
1134 */
1135 generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey | CryptoKeyPair>;
1136 /**
1137 * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key.
1138 *
1139 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey)
1140 */
1141 deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;
1142 /**
1143 * The **`deriveBits()`** method of the SubtleCrypto interface can be used to derive an array of bits from a base key.
1144 *
1145 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits)
1146 */
1147 deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise<ArrayBuffer>;
1148 /**
1149 * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API.
1150 *
1151 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey)
1152 */
1153 importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;
1154 /**
1155 * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format.
1156 *
1157 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey)
1158 */
1159 exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>;
1160 /**
1161 * The **`wrapKey()`** method of the SubtleCrypto interface "wraps" a key. This means that it exports the key in an external, portable format, then encrypts the exported key. Wrapping a key helps protect it in untrusted environments, such as inside an otherwise unprotected data store or in transmission over an unprotected network.
1162 *
1163 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey)
1164 */
1165 wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise<ArrayBuffer>;
1166 /**
1167 * The **`unwrapKey()`** method of the SubtleCrypto interface "unwraps" a key. This means that it takes as its input a key that has been exported and then encrypted (also called "wrapped"). It decrypts the key and then imports it, returning a CryptoKey object that can be used in the Web Crypto API.
1168 *
1169 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey)
1170 */
1171 unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;
1172 timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean;
1173}
1174/**
1175 * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods generateKey(), deriveKey(), importKey(), or unwrapKey().
1176 * Available only in secure contexts.
1177 *
1178 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey)
1179 */
1180declare abstract class CryptoKey {
1181 /**
1182 * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. It can have the following values:
1183 *
1184 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type)
1185 */
1186 readonly type: string;
1187 /**
1188 * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey().
1189 *
1190 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable)
1191 */
1192 readonly extractable: boolean;
1193 /**
1194 * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters.
1195 *
1196 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm)
1197 */
1198 readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm;
1199 /**
1200 * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key.
1201 *
1202 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages)
1203 */
1204 readonly usages: string[];
1205}
1206interface CryptoKeyPair {
1207 publicKey: CryptoKey;
1208 privateKey: CryptoKey;
1209}
1210interface JsonWebKey {
1211 kty: string;
1212 use?: string;
1213 key_ops?: string[];
1214 alg?: string;
1215 ext?: boolean;
1216 crv?: string;
1217 x?: string;
1218 y?: string;
1219 d?: string;
1220 n?: string;
1221 e?: string;
1222 p?: string;
1223 q?: string;
1224 dp?: string;
1225 dq?: string;
1226 qi?: string;
1227 oth?: RsaOtherPrimesInfo[];
1228 k?: string;
1229}
1230interface RsaOtherPrimesInfo {
1231 r?: string;
1232 d?: string;
1233 t?: string;
1234}
1235interface SubtleCryptoDeriveKeyAlgorithm {
1236 name: string;
1237 salt?: (ArrayBuffer | ArrayBufferView);
1238 iterations?: number;
1239 hash?: (string | SubtleCryptoHashAlgorithm);
1240 $public?: CryptoKey;
1241 info?: (ArrayBuffer | ArrayBufferView);
1242}
1243interface SubtleCryptoEncryptAlgorithm {
1244 name: string;
1245 iv?: (ArrayBuffer | ArrayBufferView);
1246 additionalData?: (ArrayBuffer | ArrayBufferView);
1247 tagLength?: number;
1248 counter?: (ArrayBuffer | ArrayBufferView);
1249 length?: number;
1250 label?: (ArrayBuffer | ArrayBufferView);
1251}
1252interface SubtleCryptoGenerateKeyAlgorithm {
1253 name: string;
1254 hash?: (string | SubtleCryptoHashAlgorithm);
1255 modulusLength?: number;
1256 publicExponent?: (ArrayBuffer | ArrayBufferView);
1257 length?: number;
1258 namedCurve?: string;
1259}
1260interface SubtleCryptoHashAlgorithm {
1261 name: string;
1262}
1263interface SubtleCryptoImportKeyAlgorithm {
1264 name: string;
1265 hash?: (string | SubtleCryptoHashAlgorithm);
1266 length?: number;
1267 namedCurve?: string;
1268 compressed?: boolean;
1269}
1270interface SubtleCryptoSignAlgorithm {
1271 name: string;
1272 hash?: (string | SubtleCryptoHashAlgorithm);
1273 dataLength?: number;
1274 saltLength?: number;
1275}
1276interface CryptoKeyKeyAlgorithm {
1277 name: string;
1278}
1279interface CryptoKeyAesKeyAlgorithm {
1280 name: string;
1281 length: number;
1282}
1283interface CryptoKeyHmacKeyAlgorithm {
1284 name: string;
1285 hash: CryptoKeyKeyAlgorithm;
1286 length: number;
1287}
1288interface CryptoKeyRsaKeyAlgorithm {
1289 name: string;
1290 modulusLength: number;
1291 publicExponent: ArrayBuffer | ArrayBufferView;
1292 hash?: CryptoKeyKeyAlgorithm;
1293}
1294interface CryptoKeyEllipticKeyAlgorithm {
1295 name: string;
1296 namedCurve: string;
1297}
1298interface CryptoKeyArbitraryKeyAlgorithm {
1299 name: string;
1300 hash?: CryptoKeyKeyAlgorithm;
1301 namedCurve?: string;
1302 length?: number;
1303}
1304declare class DigestStream extends WritableStream<ArrayBuffer | ArrayBufferView> {
1305 constructor(algorithm: string | SubtleCryptoHashAlgorithm, options?: DigestStreamOptions);
1306 readonly digest: Promise<ArrayBuffer>;
1307 get bytesWritten(): number | bigint;
1308}
1309interface DigestStreamOptions {
1310 toWellFormed?: boolean;
1311}
1312/**
1313 * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as UTF-8, ISO-8859-2, or GBK. A decoder takes an array of bytes as input and returns a JavaScript string.
1314 *
1315 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder)
1316 */
1317declare class TextDecoder {
1318 constructor(label?: string, options?: TextDecoderConstructorOptions);
1319 /**
1320 * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter.
1321 *
1322 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode)
1323 */
1324 decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string;
1325 get encoding(): string;
1326 get fatal(): boolean;
1327 get ignoreBOM(): boolean;
1328}
1329/**
1330 * The **`TextEncoder`** interface enables you to encode a JavaScript string using UTF-8.
1331 *
1332 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder)
1333 */
1334declare class TextEncoder {
1335 constructor();
1336 /**
1337 * The **`TextEncoder.encode()`** method takes a string as input, and returns a Uint8Array containing the string encoded using UTF-8.
1338 *
1339 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode)
1340 */
1341 encode(input?: string): Uint8Array;
1342 /**
1343 * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns an object indicating the progress of the encoding. This is potentially more performant than the encode() method โ€” especially when the target buffer is a view into a Wasm heap.
1344 *
1345 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto)
1346 */
1347 encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult;
1348 get encoding(): string;
1349}
1350interface TextDecoderConstructorOptions {
1351 fatal: boolean;
1352 ignoreBOM: boolean;
1353}
1354interface TextDecoderDecodeOptions {
1355 stream: boolean;
1356}
1357interface TextEncoderEncodeIntoResult {
1358 read: number;
1359 written: number;
1360}
1361/**
1362 * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files.
1363 *
1364 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent)
1365 */
1366declare class ErrorEvent extends Event {
1367 constructor(type: string, init?: ErrorEventErrorEventInit);
1368 /**
1369 * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred.
1370 *
1371 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename)
1372 */
1373 get filename(): string;
1374 /**
1375 * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem.
1376 *
1377 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message)
1378 */
1379 get message(): string;
1380 /**
1381 * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred.
1382 *
1383 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno)
1384 */
1385 get lineno(): number;
1386 /**
1387 * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred.
1388 *
1389 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno)
1390 */
1391 get colno(): number;
1392 /**
1393 * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event.
1394 *
1395 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error)
1396 */
1397 get error(): any;
1398}
1399interface ErrorEventErrorEventInit {
1400 bubbles?: boolean;
1401 cancelable?: boolean;
1402 composed?: boolean;
1403 message?: string;
1404 filename?: string;
1405 lineno?: number;
1406 colno?: number;
1407 error?: any;
1408}
1409/**
1410 * The **`MessageEvent`** interface represents a message received by a target object.
1411 *
1412 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent)
1413 */
1414declare class MessageEvent extends Event {
1415 constructor(type: string, initializer?: MessageEventInit);
1416 /**
1417 * The **`data`** read-only property of the MessageEvent interface represents the data sent by the message emitter.
1418 *
1419 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data)
1420 */
1421 readonly data: any;
1422 /**
1423 * The **`origin`** read-only property of the MessageEvent interface is a string representing the origin of the message emitter.
1424 *
1425 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin)
1426 */
1427 readonly origin: string | null;
1428 /**
1429 * The **`lastEventId`** read-only property of the MessageEvent interface is a string representing a unique ID for the event.
1430 *
1431 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId)
1432 */
1433 readonly lastEventId: string;
1434 /**
1435 * The **`source`** read-only property of the MessageEvent interface is a MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter.
1436 *
1437 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source)
1438 */
1439 readonly source: MessagePort | null;
1440 /**
1441 * The **`ports`** read-only property of the MessageEvent interface is an array of MessagePort objects containing all MessagePort objects sent with the message, in order.
1442 *
1443 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports)
1444 */
1445 readonly ports: MessagePort[];
1446}
1447interface MessageEventInit {
1448 bubbles?: boolean;
1449 cancelable?: boolean;
1450 composed?: boolean;
1451 data?: any;
1452 origin?: string;
1453 lastEventId?: string;
1454 source?: MessagePort;
1455 ports?: MessagePort[];
1456}
1457/**
1458 * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. These events are particularly useful for telemetry and debugging purposes.
1459 *
1460 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent)
1461 */
1462declare abstract class PromiseRejectionEvent extends Event {
1463 /**
1464 * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript Promise which was rejected. You can examine the event's PromiseRejectionEvent.reason property to learn why the promise was rejected.
1465 *
1466 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise)
1467 */
1468 readonly promise: Promise<any>;
1469 /**
1470 * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). This in theory provides information about why the promise was rejected.
1471 *
1472 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason)
1473 */
1474 readonly reason: any;
1475}
1476/**
1477 * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the fetch(), XMLHttpRequest.send() or navigator.sendBeacon() methods. It uses the same format a form would use if the encoding type were set to "multipart/form-data".
1478 *
1479 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData)
1480 */
1481declare class FormData {
1482 constructor();
1483 /**
1484 * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
1485 *
1486 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)
1487 */
1488 append(name: string, value: string | Blob): void;
1489 /**
1490 * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
1491 *
1492 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)
1493 */
1494 append(name: string, value: string): void;
1495 /**
1496 * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
1497 *
1498 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)
1499 */
1500 append(name: string, value: Blob, filename?: string): void;
1501 /**
1502 * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a FormData object.
1503 *
1504 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete)
1505 */
1506 delete(name: string): void;
1507 /**
1508 * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
1509 *
1510 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get)
1511 */
1512 get(name: string): (File | string) | null;
1513 /**
1514 * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a FormData object.
1515 *
1516 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll)
1517 */
1518 getAll(name: string): (File | string)[];
1519 /**
1520 * The **`has()`** method of the FormData interface returns whether a FormData object contains a certain key.
1521 *
1522 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has)
1523 */
1524 has(name: string): boolean;
1525 /**
1526 * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.
1527 *
1528 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)
1529 */
1530 set(name: string, value: string | Blob): void;
1531 /**
1532 * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.
1533 *
1534 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)
1535 */
1536 set(name: string, value: string): void;
1537 /**
1538 * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.
1539 *
1540 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)
1541 */
1542 set(name: string, value: Blob, filename?: string): void;
1543 entries(): IterableIterator<[
1544 key: string,
1545 value: File | string
1546 ]>;
1547 keys(): IterableIterator<string>;
1548 values(): IterableIterator<(File | string)>;
1549 forEach<This = unknown>(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void;
1550 [Symbol.iterator](): IterableIterator<[
1551 key: string,
1552 value: File | string
1553 ]>;
1554}
1555interface ContentOptions {
1556 html?: boolean;
1557}
1558declare class HTMLRewriter {
1559 constructor();
1560 on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter;
1561 onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter;
1562 transform(response: Response): Response;
1563}
1564interface HTMLRewriterElementContentHandlers {
1565 element?(element: Element): void | Promise<void>;
1566 comments?(comment: Comment): void | Promise<void>;
1567 text?(element: Text): void | Promise<void>;
1568}
1569interface HTMLRewriterDocumentContentHandlers {
1570 doctype?(doctype: Doctype): void | Promise<void>;
1571 comments?(comment: Comment): void | Promise<void>;
1572 text?(text: Text): void | Promise<void>;
1573 end?(end: DocumentEnd): void | Promise<void>;
1574}
1575interface Doctype {
1576 readonly name: string | null;
1577 readonly publicId: string | null;
1578 readonly systemId: string | null;
1579}
1580interface Element {
1581 tagName: string;
1582 readonly attributes: IterableIterator<string[]>;
1583 readonly removed: boolean;
1584 readonly namespaceURI: string;
1585 getAttribute(name: string): string | null;
1586 hasAttribute(name: string): boolean;
1587 setAttribute(name: string, value: string): Element;
1588 removeAttribute(name: string): Element;
1589 before(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1590 after(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1591 prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1592 append(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1593 replace(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1594 remove(): Element;
1595 removeAndKeepContent(): Element;
1596 setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1597 onEndTag(handler: (tag: EndTag) => void | Promise<void>): void;
1598}
1599interface EndTag {
1600 name: string;
1601 before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;
1602 after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;
1603 remove(): EndTag;
1604}
1605interface Comment {
1606 text: string;
1607 readonly removed: boolean;
1608 before(content: string, options?: ContentOptions): Comment;
1609 after(content: string, options?: ContentOptions): Comment;
1610 replace(content: string, options?: ContentOptions): Comment;
1611 remove(): Comment;
1612}
1613interface Text {
1614 readonly text: string;
1615 readonly lastInTextNode: boolean;
1616 readonly removed: boolean;
1617 before(content: string | ReadableStream | Response, options?: ContentOptions): Text;
1618 after(content: string | ReadableStream | Response, options?: ContentOptions): Text;
1619 replace(content: string | ReadableStream | Response, options?: ContentOptions): Text;
1620 remove(): Text;
1621}
1622interface DocumentEnd {
1623 append(content: string, options?: ContentOptions): DocumentEnd;
1624}
1625/**
1626 * This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch.
1627 *
1628 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent)
1629 */
1630declare abstract class FetchEvent extends ExtendableEvent {
1631 /**
1632 * The **`request`** read-only property of the FetchEvent interface returns the Request that triggered the event handler.
1633 *
1634 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request)
1635 */
1636 readonly request: Request;
1637 /**
1638 * The **`respondWith()`** method of FetchEvent prevents the browser's default fetch handling, and allows you to provide a promise for a Response yourself.
1639 *
1640 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith)
1641 */
1642 respondWith(promise: Response | Promise<Response>): void;
1643 passThroughOnException(): void;
1644}
1645type HeadersInit = Headers | Iterable<Iterable<string>> | Record<string, string>;
1646/**
1647 * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request's headers.
1648 *
1649 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers)
1650 */
1651declare class Headers {
1652 constructor(init?: HeadersInit);
1653 /**
1654 * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn't exist in the Headers object, it returns null.
1655 *
1656 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get)
1657 */
1658 get(name: string): string | null;
1659 getAll(name: string): string[];
1660 /**
1661 * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. This allows Headers objects to handle having multiple Set-Cookie headers, which wasn't possible prior to its implementation.
1662 *
1663 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie)
1664 */
1665 getSetCookie(): string[];
1666 /**
1667 * The **`has()`** method of the Headers interface returns a boolean stating whether a Headers object contains a certain header.
1668 *
1669 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has)
1670 */
1671 has(name: string): boolean;
1672 /**
1673 * The **`set()`** method of the Headers interface sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
1674 *
1675 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set)
1676 */
1677 set(name: string, value: string): void;
1678 /**
1679 * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a Headers object, or adds the header if it does not already exist.
1680 *
1681 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append)
1682 */
1683 append(name: string, value: string): void;
1684 /**
1685 * The **`delete()`** method of the Headers interface deletes a header from the current Headers object.
1686 *
1687 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete)
1688 */
1689 delete(name: string): void;
1690 forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void;
1691 entries(): IterableIterator<[
1692 key: string,
1693 value: string
1694 ]>;
1695 keys(): IterableIterator<string>;
1696 values(): IterableIterator<string>;
1697 [Symbol.iterator](): IterableIterator<[
1698 key: string,
1699 value: string
1700 ]>;
1701}
1702type BodyInit = ReadableStream<Uint8Array> | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData | Iterable<ArrayBuffer | ArrayBufferView> | AsyncIterable<ArrayBuffer | ArrayBufferView>;
1703declare abstract class Body {
1704 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */
1705 get body(): ReadableStream | null;
1706 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */
1707 get bodyUsed(): boolean;
1708 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */
1709 arrayBuffer(): Promise<ArrayBuffer>;
1710 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */
1711 bytes(): Promise<Uint8Array>;
1712 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */
1713 text(): Promise<string>;
1714 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */
1715 json<T>(): Promise<T>;
1716 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */
1717 formData(): Promise<FormData>;
1718 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */
1719 blob(): Promise<Blob>;
1720}
1721/**
1722 * The **`Response`** interface of the Fetch API represents the response to a request.
1723 *
1724 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
1725 */
1726declare var Response: {
1727 prototype: Response;
1728 new (body?: BodyInit | null, init?: ResponseInit): Response;
1729 error(): Response;
1730 redirect(url: string, status?: number): Response;
1731 json(any: any, maybeInit?: (ResponseInit | Response)): Response;
1732};
1733/**
1734 * The **`Response`** interface of the Fetch API represents the response to a request.
1735 *
1736 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
1737 */
1738interface Response extends Body {
1739 /**
1740 * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable.
1741 *
1742 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone)
1743 */
1744 clone(): Response;
1745 /**
1746 * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response.
1747 *
1748 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status)
1749 */
1750 status: number;
1751 /**
1752 * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status.
1753 *
1754 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText)
1755 */
1756 statusText: string;
1757 /**
1758 * The **`headers`** read-only property of the Response interface contains the Headers object associated with the response.
1759 *
1760 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers)
1761 */
1762 headers: Headers;
1763 /**
1764 * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not.
1765 *
1766 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok)
1767 */
1768 ok: boolean;
1769 /**
1770 * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected.
1771 *
1772 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected)
1773 */
1774 redirected: boolean;
1775 /**
1776 * The **`url`** read-only property of the Response interface contains the URL of the response. The value of the url property will be the final URL obtained after any redirects.
1777 *
1778 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url)
1779 */
1780 url: string;
1781 webSocket: WebSocket | null;
1782 cf: any | undefined;
1783 /**
1784 * The **`type`** read-only property of the Response interface contains the type of the response. The type determines whether scripts are able to access the response body and headers.
1785 *
1786 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type)
1787 */
1788 type: "default" | "error";
1789}
1790interface ResponseInit {
1791 status?: number;
1792 statusText?: string;
1793 headers?: HeadersInit;
1794 cf?: any;
1795 webSocket?: (WebSocket | null);
1796 encodeBody?: "automatic" | "manual";
1797}
1798type RequestInfo<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> = Request<CfHostMetadata, Cf> | string;
1799/**
1800 * The **`Request`** interface of the Fetch API represents a resource request.
1801 *
1802 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)
1803 */
1804declare var Request: {
1805 prototype: Request;
1806 new <CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>>(input: RequestInfo<CfProperties> | URL, init?: RequestInit<Cf>): Request<CfHostMetadata, Cf>;
1807};
1808/**
1809 * The **`Request`** interface of the Fetch API represents a resource request.
1810 *
1811 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)
1812 */
1813interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> extends Body {
1814 /**
1815 * The **`clone()`** method of the Request interface creates a copy of the current Request object.
1816 *
1817 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone)
1818 */
1819 clone(): Request<CfHostMetadata, Cf>;
1820 /**
1821 * The **`method`** read-only property of the Request interface contains the request's method (GET, POST, etc.)
1822 *
1823 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method)
1824 */
1825 method: string;
1826 /**
1827 * The **`url`** read-only property of the Request interface contains the URL of the request.
1828 *
1829 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url)
1830 */
1831 url: string;
1832 /**
1833 * The **`headers`** read-only property of the Request interface contains the Headers object associated with the request.
1834 *
1835 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers)
1836 */
1837 headers: Headers;
1838 /**
1839 * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled.
1840 *
1841 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect)
1842 */
1843 redirect: string;
1844 fetcher: Fetcher | null;
1845 /**
1846 * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request.
1847 *
1848 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal)
1849 */
1850 signal: AbortSignal;
1851 cf?: Cf;
1852 /**
1853 * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request.
1854 *
1855 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity)
1856 */
1857 integrity: string;
1858 /**
1859 * The **`keepalive`** read-only property of the Request interface contains the request's keepalive setting (true or false), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete.
1860 *
1861 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive)
1862 */
1863 keepalive: boolean;
1864 /**
1865 * The **`cache`** read-only property of the Request interface contains the cache mode of the request. It controls how the request will interact with the browser's HTTP cache.
1866 *
1867 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache)
1868 */
1869 cache?: "no-store" | "no-cache";
1870}
1871interface RequestInit<Cf = CfProperties> {
1872 /* A string to set request's method. */
1873 method?: string;
1874 /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */
1875 headers?: HeadersInit;
1876 /* A BodyInit object or null to set request's body. */
1877 body?: BodyInit | null;
1878 /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */
1879 redirect?: string;
1880 fetcher?: (Fetcher | null);
1881 cf?: Cf;
1882 /* A string indicating how the request will interact with the browser's cache to set request's cache. */
1883 cache?: "no-store" | "no-cache";
1884 /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */
1885 integrity?: string;
1886 /* An AbortSignal to set request's signal. */
1887 signal?: (AbortSignal | null);
1888 encodeResponseBody?: "automatic" | "manual";
1889}
1890type Service<T extends (new (...args: any[]) => Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler<any, any, any> | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher<InstanceType<T>> : T extends Rpc.WorkerEntrypointBranded ? Fetcher<T> : T extends Exclude<Rpc.EntrypointBranded, Rpc.WorkerEntrypointBranded> ? never : Fetcher<undefined>;
1891type Fetcher<T extends Rpc.EntrypointBranded | undefined = undefined, Reserved extends string = never> = (T extends Rpc.EntrypointBranded ? Rpc.Provider<T, Reserved | "fetch" | "connect"> : unknown) & {
1892 fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
1893 connect(address: SocketAddress | string, options?: SocketOptions): Socket;
1894};
1895interface KVNamespaceListKey<Metadata, Key extends string = string> {
1896 name: Key;
1897 expiration?: number;
1898 metadata?: Metadata;
1899}
1900type KVNamespaceListResult<Metadata, Key extends string = string> = {
1901 list_complete: false;
1902 keys: KVNamespaceListKey<Metadata, Key>[];
1903 cursor: string;
1904 cacheStatus: string | null;
1905} | {
1906 list_complete: true;
1907 keys: KVNamespaceListKey<Metadata, Key>[];
1908 cacheStatus: string | null;
1909};
1910interface KVNamespace<Key extends string = string> {
1911 get(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<string | null>;
1912 get(key: Key, type: "text"): Promise<string | null>;
1913 get<ExpectedValue = unknown>(key: Key, type: "json"): Promise<ExpectedValue | null>;
1914 get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>;
1915 get(key: Key, type: "stream"): Promise<ReadableStream | null>;
1916 get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise<string | null>;
1917 get<ExpectedValue = unknown>(key: Key, options?: KVNamespaceGetOptions<"json">): Promise<ExpectedValue | null>;
1918 get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise<ArrayBuffer | null>;
1919 get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise<ReadableStream | null>;
1920 get(key: Array<Key>, type: "text"): Promise<Map<string, string | null>>;
1921 get<ExpectedValue = unknown>(key: Array<Key>, type: "json"): Promise<Map<string, ExpectedValue | null>>;
1922 get(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, string | null>>;
1923 get(key: Array<Key>, options?: KVNamespaceGetOptions<"text">): Promise<Map<string, string | null>>;
1924 get<ExpectedValue = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"json">): Promise<Map<string, ExpectedValue | null>>;
1925 list<Metadata = unknown>(options?: KVNamespaceListOptions): Promise<KVNamespaceListResult<Metadata, Key>>;
1926 put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise<void>;
1927 getWithMetadata<Metadata = unknown>(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;
1928 getWithMetadata<Metadata = unknown>(key: Key, type: "text"): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;
1929 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, type: "json"): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;
1930 getWithMetadata<Metadata = unknown>(key: Key, type: "arrayBuffer"): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;
1931 getWithMetadata<Metadata = unknown>(key: Key, type: "stream"): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;
1932 getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"text">): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;
1933 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"json">): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;
1934 getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;
1935 getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"stream">): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;
1936 getWithMetadata<Metadata = unknown>(key: Array<Key>, type: "text"): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;
1937 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, type: "json"): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;
1938 getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;
1939 getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"text">): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;
1940 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"json">): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;
1941 delete(key: Key): Promise<void>;
1942}
1943interface KVNamespaceListOptions {
1944 limit?: number;
1945 prefix?: (string | null);
1946 cursor?: (string | null);
1947}
1948interface KVNamespaceGetOptions<Type> {
1949 type: Type;
1950 cacheTtl?: number;
1951}
1952interface KVNamespacePutOptions {
1953 expiration?: number;
1954 expirationTtl?: number;
1955 metadata?: (any | null);
1956}
1957interface KVNamespaceGetWithMetadataResult<Value, Metadata> {
1958 value: Value | null;
1959 metadata: Metadata | null;
1960 cacheStatus: string | null;
1961}
1962type QueueContentType = "text" | "bytes" | "json" | "v8";
1963interface Queue<Body = unknown> {
1964 metrics(): Promise<QueueMetrics>;
1965 send(message: Body, options?: QueueSendOptions): Promise<QueueSendResponse>;
1966 sendBatch(messages: Iterable<MessageSendRequest<Body>>, options?: QueueSendBatchOptions): Promise<QueueSendBatchResponse>;
1967}
1968interface QueueSendMetrics {
1969 backlogCount: number;
1970 backlogBytes: number;
1971 oldestMessageTimestamp?: Date;
1972}
1973interface QueueSendMetadata {
1974 metrics: QueueSendMetrics;
1975}
1976interface QueueSendResponse {
1977 metadata: QueueSendMetadata;
1978}
1979interface QueueSendBatchMetrics {
1980 backlogCount: number;
1981 backlogBytes: number;
1982 oldestMessageTimestamp?: Date;
1983}
1984interface QueueSendBatchMetadata {
1985 metrics: QueueSendBatchMetrics;
1986}
1987interface QueueSendBatchResponse {
1988 metadata: QueueSendBatchMetadata;
1989}
1990interface QueueSendOptions {
1991 contentType?: QueueContentType;
1992 delaySeconds?: number;
1993}
1994interface QueueSendBatchOptions {
1995 delaySeconds?: number;
1996}
1997interface MessageSendRequest<Body = unknown> {
1998 body: Body;
1999 contentType?: QueueContentType;
2000 delaySeconds?: number;
2001}
2002interface QueueMetrics {
2003 backlogCount: number;
2004 backlogBytes: number;
2005 oldestMessageTimestamp?: Date;
2006}
2007interface MessageBatchMetrics {
2008 backlogCount: number;
2009 backlogBytes: number;
2010 oldestMessageTimestamp?: Date;
2011}
2012interface MessageBatchMetadata {
2013 metrics: MessageBatchMetrics;
2014}
2015interface QueueRetryOptions {
2016 delaySeconds?: number;
2017}
2018interface Message<Body = unknown> {
2019 readonly id: string;
2020 readonly timestamp: Date;
2021 readonly body: Body;
2022 readonly attempts: number;
2023 retry(options?: QueueRetryOptions): void;
2024 ack(): void;
2025}
2026interface QueueEvent<Body = unknown> extends ExtendableEvent {
2027 readonly messages: readonly Message<Body>[];
2028 readonly queue: string;
2029 readonly metadata: MessageBatchMetadata;
2030 retryAll(options?: QueueRetryOptions): void;
2031 ackAll(): void;
2032}
2033interface MessageBatch<Body = unknown> {
2034 readonly messages: readonly Message<Body>[];
2035 readonly queue: string;
2036 readonly metadata: MessageBatchMetadata;
2037 retryAll(options?: QueueRetryOptions): void;
2038 ackAll(): void;
2039}
2040interface R2Error extends Error {
2041 readonly name: string;
2042 readonly code: number;
2043 readonly message: string;
2044 readonly action: string;
2045 readonly stack: any;
2046}
2047interface R2ListOptions {
2048 limit?: number;
2049 prefix?: string;
2050 cursor?: string;
2051 delimiter?: string;
2052 startAfter?: string;
2053 include?: ("httpMetadata" | "customMetadata")[];
2054}
2055interface R2Bucket {
2056 head(key: string): Promise<R2Object | null>;
2057 get(key: string, options: R2GetOptions & {
2058 onlyIf: R2Conditional | Headers;
2059 }): Promise<R2ObjectBody | R2Object | null>;
2060 get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>;
2061 put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & {
2062 onlyIf: R2Conditional | Headers;
2063 }): Promise<R2Object | null>;
2064 put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise<R2Object>;
2065 createMultipartUpload(key: string, options?: R2MultipartOptions): Promise<R2MultipartUpload>;
2066 resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload;
2067 delete(keys: string | string[]): Promise<void>;
2068 list(options?: R2ListOptions): Promise<R2Objects>;
2069}
2070interface R2MultipartUpload {
2071 readonly key: string;
2072 readonly uploadId: string;
2073 uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise<R2UploadedPart>;
2074 abort(): Promise<void>;
2075 complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>;
2076}
2077interface R2UploadedPart {
2078 partNumber: number;
2079 etag: string;
2080}
2081declare abstract class R2Object {
2082 readonly key: string;
2083 readonly version: string;
2084 readonly size: number;
2085 readonly etag: string;
2086 readonly httpEtag: string;
2087 readonly checksums: R2Checksums;
2088 readonly uploaded: Date;
2089 readonly httpMetadata?: R2HTTPMetadata;
2090 readonly customMetadata?: Record<string, string>;
2091 readonly range?: R2Range;
2092 readonly storageClass: string;
2093 readonly ssecKeyMd5?: string;
2094 writeHttpMetadata(headers: Headers): void;
2095}
2096interface R2ObjectBody extends R2Object {
2097 get body(): ReadableStream;
2098 get bodyUsed(): boolean;
2099 arrayBuffer(): Promise<ArrayBuffer>;
2100 bytes(): Promise<Uint8Array>;
2101 text(): Promise<string>;
2102 json<T>(): Promise<T>;
2103 blob(): Promise<Blob>;
2104}
2105type R2Range = {
2106 offset: number;
2107 length?: number;
2108} | {
2109 offset?: number;
2110 length: number;
2111} | {
2112 suffix: number;
2113};
2114interface R2Conditional {
2115 etagMatches?: string;
2116 etagDoesNotMatch?: string;
2117 uploadedBefore?: Date;
2118 uploadedAfter?: Date;
2119 secondsGranularity?: boolean;
2120}
2121interface R2GetOptions {
2122 onlyIf?: (R2Conditional | Headers);
2123 range?: (R2Range | Headers);
2124 ssecKey?: (ArrayBuffer | string);
2125}
2126interface R2PutOptions {
2127 onlyIf?: (R2Conditional | Headers);
2128 httpMetadata?: (R2HTTPMetadata | Headers);
2129 customMetadata?: Record<string, string>;
2130 md5?: ((ArrayBuffer | ArrayBufferView) | string);
2131 sha1?: ((ArrayBuffer | ArrayBufferView) | string);
2132 sha256?: ((ArrayBuffer | ArrayBufferView) | string);
2133 sha384?: ((ArrayBuffer | ArrayBufferView) | string);
2134 sha512?: ((ArrayBuffer | ArrayBufferView) | string);
2135 storageClass?: string;
2136 ssecKey?: (ArrayBuffer | string);
2137}
2138interface R2MultipartOptions {
2139 httpMetadata?: (R2HTTPMetadata | Headers);
2140 customMetadata?: Record<string, string>;
2141 storageClass?: string;
2142 ssecKey?: (ArrayBuffer | string);
2143}
2144interface R2Checksums {
2145 readonly md5?: ArrayBuffer;
2146 readonly sha1?: ArrayBuffer;
2147 readonly sha256?: ArrayBuffer;
2148 readonly sha384?: ArrayBuffer;
2149 readonly sha512?: ArrayBuffer;
2150 toJSON(): R2StringChecksums;
2151}
2152interface R2StringChecksums {
2153 md5?: string;
2154 sha1?: string;
2155 sha256?: string;
2156 sha384?: string;
2157 sha512?: string;
2158}
2159interface R2HTTPMetadata {
2160 contentType?: string;
2161 contentLanguage?: string;
2162 contentDisposition?: string;
2163 contentEncoding?: string;
2164 cacheControl?: string;
2165 cacheExpiry?: Date;
2166}
2167type R2Objects = {
2168 objects: R2Object[];
2169 delimitedPrefixes: string[];
2170} & ({
2171 truncated: true;
2172 cursor: string;
2173} | {
2174 truncated: false;
2175});
2176interface R2UploadPartOptions {
2177 ssecKey?: (ArrayBuffer | string);
2178}
2179declare abstract class ScheduledEvent extends ExtendableEvent {
2180 readonly scheduledTime: number;
2181 readonly cron: string;
2182 noRetry(): void;
2183}
2184interface ScheduledController {
2185 readonly scheduledTime: number;
2186 readonly cron: string;
2187 noRetry(): void;
2188}
2189interface QueuingStrategy<T = any> {
2190 highWaterMark?: (number | bigint);
2191 size?: (chunk: T) => number | bigint;
2192}
2193interface UnderlyingSink<W = any> {
2194 type?: string;
2195 start?: (controller: WritableStreamDefaultController) => void | Promise<void>;
2196 write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise<void>;
2197 abort?: (reason: any) => void | Promise<void>;
2198 close?: () => void | Promise<void>;
2199}
2200interface UnderlyingByteSource {
2201 type: "bytes";
2202 autoAllocateChunkSize?: number;
2203 start?: (controller: ReadableByteStreamController) => void | Promise<void>;
2204 pull?: (controller: ReadableByteStreamController) => void | Promise<void>;
2205 cancel?: (reason: any) => void | Promise<void>;
2206}
2207interface UnderlyingSource<R = any> {
2208 type?: "" | undefined;
2209 start?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;
2210 pull?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;
2211 cancel?: (reason: any) => void | Promise<void>;
2212 expectedLength?: (number | bigint);
2213}
2214interface Transformer<I = any, O = any> {
2215 readableType?: string;
2216 writableType?: string;
2217 start?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;
2218 transform?: (chunk: I, controller: TransformStreamDefaultController<O>) => void | Promise<void>;
2219 flush?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;
2220 cancel?: (reason: any) => void | Promise<void>;
2221 expectedLength?: number;
2222}
2223interface StreamPipeOptions {
2224 preventAbort?: boolean;
2225 preventCancel?: boolean;
2226 /**
2227 * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.
2228 *
2229 * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
2230 *
2231 * Errors and closures of the source and destination streams propagate as follows:
2232 *
2233 * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination.
2234 *
2235 * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source.
2236 *
2237 * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error.
2238 *
2239 * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source.
2240 *
2241 * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set.
2242 */
2243 preventClose?: boolean;
2244 signal?: AbortSignal;
2245}
2246type ReadableStreamReadResult<R = any> = {
2247 done: false;
2248 value: R;
2249} | {
2250 done: true;
2251 value?: undefined;
2252};
2253/**
2254 * The **`ReadableStream`** interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.
2255 *
2256 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)
2257 */
2258interface ReadableStream<R = any> {
2259 /**
2260 * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader.
2261 *
2262 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked)
2263 */
2264 get locked(): boolean;
2265 /**
2266 * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled.
2267 *
2268 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel)
2269 */
2270 cancel(reason?: any): Promise<void>;
2271 /**
2272 * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.
2273 *
2274 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader)
2275 */
2276 getReader(): ReadableStreamDefaultReader<R>;
2277 /**
2278 * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.
2279 *
2280 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader)
2281 */
2282 getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader;
2283 /**
2284 * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair.
2285 *
2286 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough)
2287 */
2288 pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>;
2289 /**
2290 * The **`pipeTo()`** method of the ReadableStream interface pipes the current ReadableStream to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.
2291 *
2292 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo)
2293 */
2294 pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
2295 /**
2296 * The **`tee()`** method of the ReadableStream interface tees the current readable stream, returning a two-element array containing the two resulting branches as new ReadableStream instances.
2297 *
2298 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee)
2299 */
2300 tee(): [
2301 ReadableStream<R>,
2302 ReadableStream<R>
2303 ];
2304 values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;
2305 [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;
2306}
2307/**
2308 * The **`ReadableStream`** interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.
2309 *
2310 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)
2311 */
2312declare const ReadableStream: {
2313 prototype: ReadableStream;
2314 new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy<Uint8Array>): ReadableStream<Uint8Array>;
2315 new <R = any>(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;
2316};
2317/**
2318 * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request).
2319 *
2320 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader)
2321 */
2322declare class ReadableStreamDefaultReader<R = any> {
2323 constructor(stream: ReadableStream);
2324 get closed(): Promise<void>;
2325 cancel(reason?: any): Promise<void>;
2326 /**
2327 * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue.
2328 *
2329 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read)
2330 */
2331 read(): Promise<ReadableStreamReadResult<R>>;
2332 /**
2333 * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream.
2334 *
2335 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock)
2336 */
2337 releaseLock(): void;
2338}
2339/**
2340 * The **`ReadableStreamBYOBReader`** interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. It is used for efficient copying from underlying sources where the data is delivered as an "anonymous" sequence of bytes, such as files.
2341 *
2342 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader)
2343 */
2344declare class ReadableStreamBYOBReader {
2345 constructor(stream: ReadableStream);
2346 get closed(): Promise<void>;
2347 cancel(reason?: any): Promise<void>;
2348 /**
2349 * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source.
2350 *
2351 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read)
2352 */
2353 read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamReadResult<T>>;
2354 /**
2355 * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active.
2356 *
2357 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock)
2358 */
2359 releaseLock(): void;
2360 readAtLeast<T extends ArrayBufferView>(minElements: number, view: T): Promise<ReadableStreamReadResult<T>>;
2361}
2362interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions {
2363 min?: number;
2364}
2365interface ReadableStreamGetReaderOptions {
2366 /**
2367 * Creates a ReadableStreamBYOBReader and locks the stream to the new reader.
2368 *
2369 * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation.
2370 */
2371 mode: "byob";
2372}
2373/**
2374 * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a "pull request" for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues).
2375 *
2376 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest)
2377 */
2378declare abstract class ReadableStreamBYOBRequest {
2379 /**
2380 * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view.
2381 *
2382 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view)
2383 */
2384 get view(): Uint8Array | null;
2385 /**
2386 * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view.
2387 *
2388 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond)
2389 */
2390 respond(bytesWritten: number): void;
2391 /**
2392 * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view.
2393 *
2394 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView)
2395 */
2396 respondWithNewView(view: ArrayBuffer | ArrayBufferView): void;
2397 get atLeast(): number | null;
2398}
2399/**
2400 * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. Default controllers are for streams that are not byte streams.
2401 *
2402 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController)
2403 */
2404declare abstract class ReadableStreamDefaultController<R = any> {
2405 /**
2406 * The **`desiredSize`** read-only property of the ReadableStreamDefaultController interface returns the desired size required to fill the stream's internal queue.
2407 *
2408 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize)
2409 */
2410 get desiredSize(): number | null;
2411 /**
2412 * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream.
2413 *
2414 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close)
2415 */
2416 close(): void;
2417 /**
2418 * The **`enqueue()`** method of the ReadableStreamDefaultController interface enqueues a given chunk in the associated stream.
2419 *
2420 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue)
2421 */
2422 enqueue(chunk?: R): void;
2423 /**
2424 * The **`error()`** method of the ReadableStreamDefaultController interface causes any future interactions with the associated stream to error.
2425 *
2426 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error)
2427 */
2428 error(reason: any): void;
2429}
2430/**
2431 * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. It allows control of the state and internal queue of a ReadableStream with an underlying byte source, and enables efficient zero-copy transfer of data from the underlying source to a consumer when the stream's internal queue is empty.
2432 *
2433 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController)
2434 */
2435declare abstract class ReadableByteStreamController {
2436 /**
2437 * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or null if there are no pending requests.
2438 *
2439 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest)
2440 */
2441 get byobRequest(): ReadableStreamBYOBRequest | null;
2442 /**
2443 * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its "desired size".
2444 *
2445 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize)
2446 */
2447 get desiredSize(): number | null;
2448 /**
2449 * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream.
2450 *
2451 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close)
2452 */
2453 close(): void;
2454 /**
2455 * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is transferred into the stream's internal queues).
2456 *
2457 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue)
2458 */
2459 enqueue(chunk: ArrayBuffer | ArrayBufferView): void;
2460 /**
2461 * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason.
2462 *
2463 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error)
2464 */
2465 error(reason: any): void;
2466}
2467/**
2468 * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate.
2469 *
2470 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController)
2471 */
2472declare abstract class WritableStreamDefaultController {
2473 /**
2474 * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller.
2475 *
2476 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal)
2477 */
2478 get signal(): AbortSignal;
2479 /**
2480 * The **`error()`** method of the WritableStreamDefaultController interface causes any future interactions with the associated stream to error.
2481 *
2482 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error)
2483 */
2484 error(reason?: any): void;
2485}
2486/**
2487 * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream.
2488 *
2489 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController)
2490 */
2491declare abstract class TransformStreamDefaultController<O = any> {
2492 /**
2493 * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream.
2494 *
2495 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize)
2496 */
2497 get desiredSize(): number | null;
2498 /**
2499 * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream.
2500 *
2501 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue)
2502 */
2503 enqueue(chunk?: O): void;
2504 /**
2505 * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded.
2506 *
2507 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error)
2508 */
2509 error(reason: any): void;
2510 /**
2511 * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream.
2512 *
2513 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate)
2514 */
2515 terminate(): void;
2516}
2517interface ReadableWritablePair<R = any, W = any> {
2518 readable: ReadableStream<R>;
2519 /**
2520 * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use.
2521 *
2522 * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
2523 */
2524 writable: WritableStream<W>;
2525}
2526/**
2527 * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.
2528 *
2529 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream)
2530 */
2531declare class WritableStream<W = any> {
2532 constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy);
2533 /**
2534 * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the WritableStream is locked to a writer.
2535 *
2536 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked)
2537 */
2538 get locked(): boolean;
2539 /**
2540 * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.
2541 *
2542 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort)
2543 */
2544 abort(reason?: any): Promise<void>;
2545 /**
2546 * The **`close()`** method of the WritableStream interface closes the associated stream. All chunks written before this method is called are sent before the returned promise is fulfilled.
2547 *
2548 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close)
2549 */
2550 close(): Promise<void>;
2551 /**
2552 * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released.
2553 *
2554 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter)
2555 */
2556 getWriter(): WritableStreamDefaultWriter<W>;
2557}
2558/**
2559 * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the WritableStream ensuring that no other streams can write to the underlying sink.
2560 *
2561 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter)
2562 */
2563declare class WritableStreamDefaultWriter<W = any> {
2564 constructor(stream: WritableStream);
2565 /**
2566 * The **`closed`** read-only property of the WritableStreamDefaultWriter interface returns a Promise that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released.
2567 *
2568 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed)
2569 */
2570 get closed(): Promise<void>;
2571 /**
2572 * The **`ready`** read-only property of the WritableStreamDefaultWriter interface returns a Promise that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure.
2573 *
2574 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready)
2575 */
2576 get ready(): Promise<void>;
2577 /**
2578 * The **`desiredSize`** read-only property of the WritableStreamDefaultWriter interface returns the desired size required to fill the stream's internal queue.
2579 *
2580 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize)
2581 */
2582 get desiredSize(): number | null;
2583 /**
2584 * The **`abort()`** method of the WritableStreamDefaultWriter interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.
2585 *
2586 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort)
2587 */
2588 abort(reason?: any): Promise<void>;
2589 /**
2590 * The **`close()`** method of the WritableStreamDefaultWriter interface closes the associated writable stream.
2591 *
2592 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close)
2593 */
2594 close(): Promise<void>;
2595 /**
2596 * The **`write()`** method of the WritableStreamDefaultWriter interface writes a passed chunk of data to a WritableStream and its underlying sink, then returns a Promise that resolves to indicate the success or failure of the write operation.
2597 *
2598 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write)
2599 */
2600 write(chunk?: W): Promise<void>;
2601 /**
2602 * The **`releaseLock()`** method of the WritableStreamDefaultWriter interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed.
2603 *
2604 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock)
2605 */
2606 releaseLock(): void;
2607}
2608/**
2609 * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain transform stream concept.
2610 *
2611 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream)
2612 */
2613declare class TransformStream<I = any, O = any> {
2614 constructor(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);
2615 /**
2616 * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this TransformStream. This stream emits the transformed output data.
2617 *
2618 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable)
2619 */
2620 get readable(): ReadableStream<O>;
2621 /**
2622 * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this TransformStream. This stream accepts input data that will be transformed and emitted to the readable stream.
2623 *
2624 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable)
2625 */
2626 get writable(): WritableStream<I>;
2627}
2628declare class FixedLengthStream extends IdentityTransformStream {
2629 constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy);
2630}
2631declare class IdentityTransformStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {
2632 constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy);
2633}
2634interface IdentityTransformStreamQueuingStrategy {
2635 highWaterMark?: (number | bigint);
2636}
2637interface ReadableStreamValuesOptions {
2638 preventCancel?: boolean;
2639}
2640/**
2641 * The **`CompressionStream`** interface of the Compression Streams API compresses a stream of data. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.
2642 *
2643 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream)
2644 */
2645declare class CompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {
2646 constructor(format: "gzip" | "deflate" | "deflate-raw");
2647}
2648/**
2649 * The **`DecompressionStream`** interface of the Compression Streams API decompresses a stream of data. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.
2650 *
2651 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream)
2652 */
2653declare class DecompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {
2654 constructor(format: "gzip" | "deflate" | "deflate-raw");
2655}
2656/**
2657 * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. It is the streaming equivalent of TextEncoder. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.
2658 *
2659 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream)
2660 */
2661declare class TextEncoderStream extends TransformStream<string, Uint8Array> {
2662 constructor();
2663 get encoding(): string;
2664}
2665/**
2666 * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. It is the streaming equivalent of TextDecoder. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.
2667 *
2668 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream)
2669 */
2670declare class TextDecoderStream extends TransformStream<ArrayBuffer | ArrayBufferView, string> {
2671 constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit);
2672 get encoding(): string;
2673 get fatal(): boolean;
2674 get ignoreBOM(): boolean;
2675}
2676interface TextDecoderStreamTextDecoderStreamInit {
2677 fatal?: boolean;
2678 ignoreBOM?: boolean;
2679}
2680/**
2681 * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams.
2682 *
2683 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy)
2684 */
2685declare class ByteLengthQueuingStrategy implements QueuingStrategy<ArrayBufferView> {
2686 constructor(init: QueuingStrategyInit);
2687 /**
2688 * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied.
2689 *
2690 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark)
2691 */
2692 get highWaterMark(): number;
2693 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */
2694 get size(): (chunk?: any) => number;
2695}
2696/**
2697 * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams.
2698 *
2699 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy)
2700 */
2701declare class CountQueuingStrategy implements QueuingStrategy {
2702 constructor(init: QueuingStrategyInit);
2703 /**
2704 * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied.
2705 *
2706 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark)
2707 */
2708 get highWaterMark(): number;
2709 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */
2710 get size(): (chunk?: any) => number;
2711}
2712interface QueuingStrategyInit {
2713 /**
2714 * Creates a new ByteLengthQueuingStrategy with the provided high water mark.
2715 *
2716 * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw.
2717 */
2718 highWaterMark: number;
2719}
2720interface TracePreviewInfo {
2721 id: string;
2722 slug: string;
2723 name: string;
2724}
2725interface ScriptVersion {
2726 id?: string;
2727 tag?: string;
2728 message?: string;
2729}
2730declare abstract class TailEvent extends ExtendableEvent {
2731 readonly events: TraceItem[];
2732 readonly traces: TraceItem[];
2733}
2734interface TraceItem {
2735 readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemConnectEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null;
2736 readonly eventTimestamp: number | null;
2737 readonly logs: TraceLog[];
2738 readonly exceptions: TraceException[];
2739 readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[];
2740 readonly scriptName: string | null;
2741 readonly entrypoint?: string;
2742 readonly scriptVersion?: ScriptVersion;
2743 readonly dispatchNamespace?: string;
2744 readonly scriptTags?: string[];
2745 readonly tailAttributes?: Record<string, boolean | number | string>;
2746 readonly preview?: TracePreviewInfo;
2747 readonly durableObjectId?: string;
2748 readonly outcome: string;
2749 readonly executionModel: string;
2750 readonly truncated: boolean;
2751 readonly cpuTime: number;
2752 readonly wallTime: number;
2753}
2754interface TraceItemAlarmEventInfo {
2755 readonly scheduledTime: Date;
2756}
2757interface TraceItemConnectEventInfo {
2758}
2759interface TraceItemCustomEventInfo {
2760}
2761interface TraceItemScheduledEventInfo {
2762 readonly scheduledTime: number;
2763 readonly cron: string;
2764}
2765interface TraceItemQueueEventInfo {
2766 readonly queue: string;
2767 readonly batchSize: number;
2768}
2769interface TraceItemEmailEventInfo {
2770 readonly mailFrom: string;
2771 readonly rcptTo: string;
2772 readonly rawSize: number;
2773}
2774interface TraceItemTailEventInfo {
2775 readonly consumedEvents: TraceItemTailEventInfoTailItem[];
2776}
2777interface TraceItemTailEventInfoTailItem {
2778 readonly scriptName: string | null;
2779}
2780interface TraceItemFetchEventInfo {
2781 readonly response?: TraceItemFetchEventInfoResponse;
2782 readonly request: TraceItemFetchEventInfoRequest;
2783}
2784interface TraceItemFetchEventInfoRequest {
2785 readonly cf?: any;
2786 readonly headers: Record<string, string>;
2787 readonly method: string;
2788 readonly url: string;
2789 getUnredacted(): TraceItemFetchEventInfoRequest;
2790}
2791interface TraceItemFetchEventInfoResponse {
2792 readonly status: number;
2793}
2794interface TraceItemJsRpcEventInfo {
2795 readonly rpcMethod: string;
2796}
2797interface TraceItemHibernatableWebSocketEventInfo {
2798 readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError;
2799}
2800interface TraceItemHibernatableWebSocketEventInfoMessage {
2801 readonly webSocketEventType: string;
2802}
2803interface TraceItemHibernatableWebSocketEventInfoClose {
2804 readonly webSocketEventType: string;
2805 readonly code: number;
2806 readonly wasClean: boolean;
2807}
2808interface TraceItemHibernatableWebSocketEventInfoError {
2809 readonly webSocketEventType: string;
2810}
2811interface TraceLog {
2812 readonly timestamp: number;
2813 readonly level: string;
2814 readonly message: any;
2815 readonly errorInfo?: (TraceLogErrorInfo | null)[];
2816}
2817interface TraceLogErrorInfo {
2818 name: string;
2819 message: string;
2820 stack?: string;
2821}
2822interface TraceException {
2823 readonly timestamp: number;
2824 readonly message: string;
2825 readonly name: string;
2826 readonly stack?: string;
2827}
2828interface TraceDiagnosticChannelEvent {
2829 readonly timestamp: number;
2830 readonly channel: string;
2831 readonly message: any;
2832}
2833interface TraceMetrics {
2834 readonly cpuTime: number;
2835 readonly wallTime: number;
2836}
2837interface UnsafeTraceMetrics {
2838 fromTrace(item: TraceItem): TraceMetrics;
2839}
2840/**
2841 * The **`URL`** interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
2842 *
2843 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL)
2844 */
2845declare class URL {
2846 constructor(url: string | URL, base?: string | URL);
2847 /**
2848 * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL.
2849 *
2850 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin)
2851 */
2852 get origin(): string;
2853 /**
2854 * The **`href`** property of the URL interface is a string containing the whole URL.
2855 *
2856 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href)
2857 */
2858 get href(): string;
2859 /**
2860 * The **`href`** property of the URL interface is a string containing the whole URL.
2861 *
2862 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href)
2863 */
2864 set href(value: string);
2865 /**
2866 * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".
2867 *
2868 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol)
2869 */
2870 get protocol(): string;
2871 /**
2872 * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".
2873 *
2874 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol)
2875 */
2876 set protocol(value: string);
2877 /**
2878 * The **`username`** property of the URL interface is a string containing the username component of the URL. If the URL does not have a username, this property contains an empty string, "".
2879 *
2880 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username)
2881 */
2882 get username(): string;
2883 /**
2884 * The **`username`** property of the URL interface is a string containing the username component of the URL. If the URL does not have a username, this property contains an empty string, "".
2885 *
2886 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username)
2887 */
2888 set username(value: string);
2889 /**
2890 * The **`password`** property of the URL interface is a string containing the password component of the URL. If the URL does not have a password, this property contains an empty string, "".
2891 *
2892 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password)
2893 */
2894 get password(): string;
2895 /**
2896 * The **`password`** property of the URL interface is a string containing the password component of the URL. If the URL does not have a password, this property contains an empty string, "".
2897 *
2898 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password)
2899 */
2900 set password(value: string);
2901 /**
2902 * The **`host`** property of the URL interface is a string containing the host, which is the hostname, and then, if the port of the URL is nonempty, a ":", followed by the port of the URL. If the URL does not have a hostname, this property contains an empty string, "".
2903 *
2904 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host)
2905 */
2906 get host(): string;
2907 /**
2908 * The **`host`** property of the URL interface is a string containing the host, which is the hostname, and then, if the port of the URL is nonempty, a ":", followed by the port of the URL. If the URL does not have a hostname, this property contains an empty string, "".
2909 *
2910 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host)
2911 */
2912 set host(value: string);
2913 /**
2914 * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. If the URL does not have a hostname, this property contains an empty string, "". IPv4 and IPv6 addresses are normalized, such as stripping leading zeros, and domain names are converted to IDN.
2915 *
2916 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname)
2917 */
2918 get hostname(): string;
2919 /**
2920 * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. If the URL does not have a hostname, this property contains an empty string, "". IPv4 and IPv6 addresses are normalized, such as stripping leading zeros, and domain names are converted to IDN.
2921 *
2922 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname)
2923 */
2924 set hostname(value: string);
2925 /**
2926 * The **`port`** property of the URL interface is a string containing the port number of the URL. If the port is the default for the protocol (80 for ws: and http:, 443 for wss: and https:, and 21 for ftp:), this property contains an empty string, "".
2927 *
2928 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port)
2929 */
2930 get port(): string;
2931 /**
2932 * The **`port`** property of the URL interface is a string containing the port number of the URL. If the port is the default for the protocol (80 for ws: and http:, 443 for wss: and https:, and 21 for ftp:), this property contains an empty string, "".
2933 *
2934 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port)
2935 */
2936 set port(value: string);
2937 /**
2938 * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
2939 *
2940 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname)
2941 */
2942 get pathname(): string;
2943 /**
2944 * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
2945 *
2946 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname)
2947 */
2948 set pathname(value: string);
2949 /**
2950 * The **`search`** property of the URL interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the URL. If the URL does not have a search query, this property contains an empty string, "".
2951 *
2952 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search)
2953 */
2954 get search(): string;
2955 /**
2956 * The **`search`** property of the URL interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the URL. If the URL does not have a search query, this property contains an empty string, "".
2957 *
2958 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search)
2959 */
2960 set search(value: string);
2961 /**
2962 * The **`hash`** property of the URL interface is a string containing a "#" followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this property contains an empty string, "".
2963 *
2964 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash)
2965 */
2966 get hash(): string;
2967 /**
2968 * The **`hash`** property of the URL interface is a string containing a "#" followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this property contains an empty string, "".
2969 *
2970 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash)
2971 */
2972 set hash(value: string);
2973 /**
2974 * The **`searchParams`** read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
2975 *
2976 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams)
2977 */
2978 get searchParams(): URLSearchParams;
2979 /**
2980 * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as URL.toString().
2981 *
2982 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON)
2983 */
2984 toJSON(): string;
2985 /*function toString() { [native code] }*/
2986 toString(): string;
2987 /**
2988 * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid.
2989 *
2990 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static)
2991 */
2992 static canParse(url: string, base?: string): boolean;
2993 /**
2994 * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters.
2995 *
2996 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static)
2997 */
2998 static parse(url: string, base?: string): URL | null;
2999 /**
3000 * The **`createObjectURL()`** static method of the URL interface creates a string containing a blob URL pointing to the object given in the parameter.
3001 *
3002 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static)
3003 */
3004 static createObjectURL(object: File | Blob): string;
3005 /**
3006 * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling URL.createObjectURL().
3007 *
3008 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static)
3009 */
3010 static revokeObjectURL(object_url: string): void;
3011}
3012/**
3013 * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL.
3014 *
3015 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams)
3016 */
3017declare class URLSearchParams {
3018 constructor(init?: (Iterable<Iterable<string>> | Record<string, string> | string));
3019 /**
3020 * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries.
3021 *
3022 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size)
3023 */
3024 get size(): number;
3025 /**
3026 * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter.
3027 *
3028 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append)
3029 */
3030 append(name: string, value: string): void;
3031 /**
3032 * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters.
3033 *
3034 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete)
3035 */
3036 delete(name: string, value?: string): void;
3037 /**
3038 * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter.
3039 *
3040 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get)
3041 */
3042 get(name: string): string | null;
3043 /**
3044 * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array.
3045 *
3046 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll)
3047 */
3048 getAll(name: string): string[];
3049 /**
3050 * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters.
3051 *
3052 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has)
3053 */
3054 has(name: string, value?: string): boolean;
3055 /**
3056 * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it.
3057 *
3058 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set)
3059 */
3060 set(name: string, value: string): void;
3061 /**
3062 * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns undefined. Key/value pairs are sorted by the values of the UTF-16 code units of the keys. This method uses a stable sorting algorithm (i.e., the relative order between key/value pairs with equal keys will be preserved).
3063 *
3064 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort)
3065 */
3066 sort(): void;
3067 entries(): IterableIterator<[
3068 key: string,
3069 value: string
3070 ]>;
3071 keys(): IterableIterator<string>;
3072 values(): IterableIterator<string>;
3073 forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void;
3074 /*function toString() { [native code] }*/
3075 toString(): string;
3076 [Symbol.iterator](): IterableIterator<[
3077 key: string,
3078 value: string
3079 ]>;
3080}
3081/**
3082 * The **`URLPattern`** interface of the URL Pattern API matches URLs or parts of URLs against a pattern. The pattern can contain capturing groups that extract parts of the matched URL.
3083 *
3084 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern)
3085 */
3086declare class URLPattern {
3087 constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions);
3088 /**
3089 * The **`protocol`** read-only property of the URLPattern interface is a string containing the pattern used to match the protocol part of a URL.
3090 *
3091 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/protocol)
3092 */
3093 get protocol(): string;
3094 /**
3095 * The **`username`** read-only property of the URLPattern interface is a string containing the pattern used to match the username part of a URL.
3096 *
3097 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/username)
3098 */
3099 get username(): string;
3100 /**
3101 * The **`password`** read-only property of the URLPattern interface is a string containing the pattern used to match the password part of a URL.
3102 *
3103 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/password)
3104 */
3105 get password(): string;
3106 /**
3107 * The **`hostname`** read-only property of the URLPattern interface is a string containing the pattern used to match the hostname part of a URL.
3108 *
3109 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hostname)
3110 */
3111 get hostname(): string;
3112 /**
3113 * The **`port`** read-only property of the URLPattern interface is a string containing the pattern used to match the port part of a URL.
3114 *
3115 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/port)
3116 */
3117 get port(): string;
3118 /**
3119 * The **`pathname`** read-only property of the URLPattern interface is a string containing the pattern used to match the pathname part of a URL.
3120 *
3121 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/pathname)
3122 */
3123 get pathname(): string;
3124 /**
3125 * The **`search`** read-only property of the URLPattern interface is a string containing the pattern used to match the search part of a URL.
3126 *
3127 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/search)
3128 */
3129 get search(): string;
3130 /**
3131 * The **`hash`** read-only property of the URLPattern interface is a string containing the pattern used to match the fragment part of a URL.
3132 *
3133 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hash)
3134 */
3135 get hash(): string;
3136 /**
3137 * The **`hasRegExpGroups`** read-only property of the URLPattern interface is a boolean indicating whether or not any of the URLPattern components contain regular expression capturing groups.
3138 *
3139 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hasRegExpGroups)
3140 */
3141 get hasRegExpGroups(): boolean;
3142 /**
3143 * The **`test()`** method of the URLPattern interface takes a URL string or object of URL parts, and returns a boolean indicating if the given input matches the current pattern.
3144 *
3145 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/test)
3146 */
3147 test(input?: (string | URLPatternInit), baseURL?: string): boolean;
3148 /**
3149 * The **`exec()`** method of the URLPattern interface takes a URL or object of URL parts, and returns either an object containing the results of matching the URL to the pattern, or null if the URL does not match the pattern.
3150 *
3151 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/exec)
3152 */
3153 exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null;
3154}
3155interface URLPatternInit {
3156 protocol?: string;
3157 username?: string;
3158 password?: string;
3159 hostname?: string;
3160 port?: string;
3161 pathname?: string;
3162 search?: string;
3163 hash?: string;
3164 baseURL?: string;
3165}
3166interface URLPatternComponentResult {
3167 input: string;
3168 groups: Record<string, string>;
3169}
3170interface URLPatternResult {
3171 inputs: (string | URLPatternInit)[];
3172 protocol: URLPatternComponentResult;
3173 username: URLPatternComponentResult;
3174 password: URLPatternComponentResult;
3175 hostname: URLPatternComponentResult;
3176 port: URLPatternComponentResult;
3177 pathname: URLPatternComponentResult;
3178 search: URLPatternComponentResult;
3179 hash: URLPatternComponentResult;
3180}
3181interface URLPatternOptions {
3182 ignoreCase?: boolean;
3183}
3184/**
3185 * A **`CloseEvent`** is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute.
3186 *
3187 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent)
3188 */
3189declare class CloseEvent extends Event {
3190 constructor(type: string, initializer?: CloseEventInit);
3191 /**
3192 * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed.
3193 *
3194 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code)
3195 */
3196 readonly code: number;
3197 /**
3198 * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure.
3199 *
3200 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason)
3201 */
3202 readonly reason: string;
3203 /**
3204 * The **`wasClean`** read-only property of the CloseEvent interface returns true if the connection closed cleanly.
3205 *
3206 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean)
3207 */
3208 readonly wasClean: boolean;
3209}
3210interface CloseEventInit {
3211 bubbles?: boolean;
3212 cancelable?: boolean;
3213 composed?: boolean;
3214 code?: number;
3215 reason?: string;
3216 wasClean?: boolean;
3217}
3218type WebSocketEventMap = {
3219 close: CloseEvent;
3220 message: MessageEvent;
3221 open: Event;
3222 error: ErrorEvent;
3223};
3224/**
3225 * The **`WebSocket`** object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.
3226 *
3227 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)
3228 */
3229declare var WebSocket: {
3230 prototype: WebSocket;
3231 new (url: string, protocols?: (string[] | string)): WebSocket;
3232 readonly READY_STATE_CONNECTING: number;
3233 readonly CONNECTING: number;
3234 readonly READY_STATE_OPEN: number;
3235 readonly OPEN: number;
3236 readonly READY_STATE_CLOSING: number;
3237 readonly CLOSING: number;
3238 readonly READY_STATE_CLOSED: number;
3239 readonly CLOSED: number;
3240};
3241/**
3242 * The **`WebSocket`** object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.
3243 *
3244 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)
3245 */
3246interface WebSocket extends EventTarget<WebSocketEventMap> {
3247 accept(options?: WebSocketAcceptOptions): void;
3248 /**
3249 * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of bufferedAmount by the number of bytes needed to contain the data. If the data can't be sent (for example, because it needs to be buffered but the buffer is full), the socket is closed automatically. The browser will throw an exception if you call send() when the connection is in the CONNECTING state. If you call send() when the connection is in the CLOSING or CLOSED states, the browser will silently discard the data.
3250 *
3251 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send)
3252 */
3253 send(message: (ArrayBuffer | ArrayBufferView) | string): void;
3254 /**
3255 * The **`WebSocket.close()`** method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.
3256 *
3257 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close)
3258 */
3259 close(code?: number, reason?: string): void;
3260 serializeAttachment(attachment: any): void;
3261 deserializeAttachment(): any | null;
3262 /**
3263 * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection.
3264 *
3265 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState)
3266 */
3267 readyState: number;
3268 /**
3269 * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor.
3270 *
3271 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url)
3272 */
3273 url: string | null;
3274 /**
3275 * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object, or the empty string if no connection is established.
3276 *
3277 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol)
3278 */
3279 protocol: string | null;
3280 /**
3281 * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. This is currently only the empty string or a list of extensions as negotiated by the connection.
3282 *
3283 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions)
3284 */
3285 extensions: string | null;
3286 /**
3287 * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection.
3288 *
3289 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType)
3290 */
3291 binaryType: "blob" | "arraybuffer";
3292}
3293interface WebSocketAcceptOptions {
3294 /**
3295 * When set to `true`, receiving a server-initiated WebSocket Close frame will not
3296 * automatically send a reciprocal Close frame, leaving the connection in a half-open
3297 * state. This is useful for proxying scenarios where you need to coordinate closing
3298 * both sides independently. Defaults to `false` when the
3299 * `no_web_socket_half_open_by_default` compatibility flag is enabled.
3300 */
3301 allowHalfOpen?: boolean;
3302}
3303declare const WebSocketPair: {
3304 new (): {
3305 0: WebSocket;
3306 1: WebSocket;
3307 };
3308};
3309interface SqlStorage {
3310 exec<T extends Record<string, SqlStorageValue>>(query: string, ...bindings: any[]): SqlStorageCursor<T>;
3311 get databaseSize(): number;
3312 Cursor: typeof SqlStorageCursor;
3313 Statement: typeof SqlStorageStatement;
3314}
3315declare abstract class SqlStorageStatement {
3316}
3317type SqlStorageValue = ArrayBuffer | string | number | null;
3318declare abstract class SqlStorageCursor<T extends Record<string, SqlStorageValue>> {
3319 next(): {
3320 done?: false;
3321 value: T;
3322 } | {
3323 done: true;
3324 value?: never;
3325 };
3326 toArray(): T[];
3327 one(): T;
3328 raw<U extends SqlStorageValue[]>(): IterableIterator<U>;
3329 columnNames: string[];
3330 get rowsRead(): number;
3331 get rowsWritten(): number;
3332 [Symbol.iterator](): IterableIterator<T>;
3333}
3334interface Socket {
3335 get readable(): ReadableStream;
3336 get writable(): WritableStream;
3337 get closed(): Promise<void>;
3338 get opened(): Promise<SocketInfo>;
3339 get upgraded(): boolean;
3340 get secureTransport(): "on" | "off" | "starttls";
3341 close(): Promise<void>;
3342 startTls(options?: TlsOptions): Socket;
3343}
3344interface SocketOptions {
3345 secureTransport?: string;
3346 allowHalfOpen: boolean;
3347 highWaterMark?: (number | bigint);
3348}
3349interface SocketAddress {
3350 hostname: string;
3351 port: number;
3352}
3353interface TlsOptions {
3354 expectedServerHostname?: string;
3355}
3356interface SocketInfo {
3357 remoteAddress?: string;
3358 localAddress?: string;
3359}
3360/**
3361 * The **`EventSource`** interface is web content's interface to server-sent events.
3362 *
3363 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource)
3364 */
3365declare class EventSource extends EventTarget {
3366 constructor(url: string, init?: EventSourceEventSourceInit);
3367 /**
3368 * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed).
3369 *
3370 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
3371 */
3372 close(): void;
3373 /**
3374 * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source.
3375 *
3376 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
3377 */
3378 get url(): string;
3379 /**
3380 * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set.
3381 *
3382 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
3383 */
3384 get withCredentials(): boolean;
3385 /**
3386 * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection.
3387 *
3388 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
3389 */
3390 get readyState(): number;
3391 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
3392 get onopen(): any | null;
3393 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
3394 set onopen(value: any | null);
3395 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
3396 get onmessage(): any | null;
3397 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
3398 set onmessage(value: any | null);
3399 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
3400 get onerror(): any | null;
3401 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
3402 set onerror(value: any | null);
3403 static readonly CONNECTING: number;
3404 static readonly OPEN: number;
3405 static readonly CLOSED: number;
3406 static from(stream: ReadableStream): EventSource;
3407}
3408interface EventSourceEventSourceInit {
3409 withCredentials?: boolean;
3410 fetcher?: Fetcher;
3411}
3412interface ExecOutput {
3413 readonly stdout: ArrayBuffer;
3414 readonly stderr: ArrayBuffer;
3415 readonly exitCode: number;
3416}
3417interface ContainerExecOptions {
3418 cwd?: string;
3419 env?: Record<string, string>;
3420 user?: string;
3421 signal?: AbortSignal;
3422 pty?: boolean | ContainerExecPtyOptions;
3423 stdin?: ReadableStream | "pipe";
3424 stdout?: "pipe" | "ignore";
3425 stderr?: "pipe" | "ignore" | "combined";
3426}
3427interface ContainerExecPtyOptions {
3428 cols?: number;
3429 rows?: number;
3430}
3431interface ExecProcess {
3432 readonly stdin: WritableStream | null;
3433 readonly stdout: ReadableStream | null;
3434 readonly stderr: ReadableStream | null;
3435 readonly pid: number;
3436 readonly isPty: boolean;
3437 readonly exitCode: Promise<number>;
3438 output(): Promise<ExecOutput>;
3439 kill(signal?: number): void;
3440 resize(cols: number, rows: number): void;
3441}
3442interface Container {
3443 get running(): boolean;
3444 get images(): Record<string, string>;
3445 start(options?: ContainerStartupOptions): void;
3446 monitor(): Promise<void>;
3447 destroy(error?: any): Promise<void>;
3448 signal(signo: number): void;
3449 getTcpPort(port: number): Fetcher;
3450 setInactivityTimeout(durationMs: number | bigint): Promise<void>;
3451 interceptOutboundHttp(addr: string, binding: Fetcher): Promise<void>;
3452 interceptAllOutboundHttp(binding: Fetcher): Promise<void>;
3453 snapshotContainer(options: ContainerSnapshotOptions): Promise<ContainerSnapshot>;
3454 interceptOutboundHttps(addr: string, binding: Fetcher): Promise<void>;
3455 exec(cmd: string[], options?: ContainerExecOptions): Promise<ExecProcess>;
3456 inspect(): Promise<ContainerInfo | null>;
3457}
3458interface ContainerDirectorySnapshot {
3459 id: string;
3460 size: number;
3461 dir: string;
3462 name?: string;
3463}
3464type ContainerDirectorySnapshotRestoreParams = {
3465 snapshot: ContainerDirectorySnapshot;
3466 mountPoint?: string;
3467} | {
3468 snapshot?: undefined;
3469 mountPoint: string;
3470};
3471interface ContainerSnapshot {
3472 id: string;
3473 size: number;
3474 name?: string;
3475}
3476interface ContainerSnapshotRestoreParams {
3477 id: string;
3478}
3479interface ContainerSnapshotOptions {
3480 name?: string;
3481}
3482type ContainerStartupOptions = {
3483 entrypoint?: string[];
3484 enableInternet: boolean;
3485 env?: Record<string, string>;
3486 instance?: "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4" | ContainerStartResources;
3487 labels?: Record<string, string>;
3488 directorySnapshots?: ContainerDirectorySnapshotRestoreParams[];
3489} & ({
3490 image: string;
3491 containerSnapshot?: never;
3492} | {
3493 image?: never;
3494 containerSnapshot?: ContainerSnapshotRestoreParams;
3495});
3496interface ContainerInfo {
3497 labels: Record<string, string>;
3498 image: string;
3499}
3500interface ContainerStartResources {
3501 vcpu: number;
3502 memoryMib: number;
3503 diskMb: number;
3504}
3505/**
3506 * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other.
3507 *
3508 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort)
3509 */
3510declare abstract class MessagePort extends EventTarget {
3511 /**
3512 * The **`postMessage()`** method of the MessagePort interface sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts.
3513 *
3514 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage)
3515 */
3516 postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void;
3517 /**
3518 * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. This stops the flow of messages to that port.
3519 *
3520 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close)
3521 */
3522 close(): void;
3523 /**
3524 * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. This method is only needed when using EventTarget.addEventListener; it is implied when using onmessage.
3525 *
3526 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start)
3527 */
3528 start(): void;
3529 get onmessage(): any | null;
3530 set onmessage(value: any | null);
3531}
3532/**
3533 * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties.
3534 *
3535 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel)
3536 */
3537declare class MessageChannel {
3538 constructor();
3539 /**
3540 * The **`port1`** read-only property of the MessageChannel interface returns the first port of the message channel โ€” the port attached to the context that originated the channel.
3541 *
3542 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1)
3543 */
3544 readonly port1: MessagePort;
3545 /**
3546 * The **`port2`** read-only property of the MessageChannel interface returns the second port of the message channel โ€” the port attached to the context at the other end of the channel, which the message is initially sent to.
3547 *
3548 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2)
3549 */
3550 readonly port2: MessagePort;
3551}
3552interface MessagePortPostMessageOptions {
3553 transfer?: any[];
3554}
3555type LoopbackForExport<T extends (new (...args: any[]) => Rpc.EntrypointBranded) | ExportedHandler<any, any, any> | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub<InstanceType<T>> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass<InstanceType<T>> : T extends ExportedHandler<any, any, any> ? LoopbackServiceStub<undefined> : undefined;
3556type LoopbackServiceStub<T extends Rpc.WorkerEntrypointBranded | undefined = undefined> = Fetcher<T> & (T extends CloudflareWorkersModule.WorkerEntrypoint<any, infer Props> ? (opts: {
3557 props?: Props;
3558}) => Fetcher<T> : (opts: {
3559 props?: any;
3560}) => Fetcher<T>);
3561type LoopbackDurableObjectClass<T extends Rpc.DurableObjectBranded | undefined = undefined> = DurableObjectClass<T> & (T extends CloudflareWorkersModule.DurableObject<any, infer Props> ? (opts: {
3562 props?: Props;
3563}) => DurableObjectClass<T> : (opts: {
3564 props?: any;
3565}) => DurableObjectClass<T>);
3566interface LoopbackDurableObjectNamespace extends DurableObjectNamespace {
3567}
3568interface LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace {
3569}
3570interface SyncKvStorage {
3571 get<T = unknown>(key: string): T | undefined;
3572 list<T = unknown>(options?: SyncKvListOptions): Iterable<[
3573 string,
3574 T
3575 ]>;
3576 put<T>(key: string, value: T): void;
3577 delete(key: string): boolean;
3578}
3579interface SyncKvListOptions {
3580 start?: string;
3581 startAfter?: string;
3582 end?: string;
3583 prefix?: string;
3584 reverse?: boolean;
3585 limit?: number;
3586}
3587interface WorkerStub {
3588 getEntrypoint<T extends Rpc.WorkerEntrypointBranded | undefined>(name?: string, options?: WorkerStubEntrypointOptions): Fetcher<T>;
3589 getDurableObjectClass<T extends Rpc.DurableObjectBranded | undefined>(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass<T>;
3590}
3591interface WorkerStubEntrypointOptions {
3592 props?: any;
3593 limits?: workerdResourceLimits;
3594}
3595interface WorkerLoader {
3596 get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise<WorkerLoaderWorkerCode>): WorkerStub;
3597 load(code: WorkerLoaderWorkerCode): WorkerStub;
3598}
3599interface WorkerLoaderModule {
3600 js?: string;
3601 cjs?: string;
3602 text?: string;
3603 data?: ArrayBuffer;
3604 json?: any;
3605 py?: string;
3606 wasm?: ArrayBuffer | ArrayBufferView | WebAssembly.Module;
3607}
3608interface WorkerLoaderWorkerCode {
3609 compatibilityDate: string;
3610 compatibilityFlags?: string[];
3611 allowExperimental?: boolean;
3612 limits?: workerdResourceLimits;
3613 mainModule: string;
3614 modules: Record<string, string | WebAssembly.Module | WorkerLoaderModule>;
3615 env?: any;
3616 globalOutbound?: (Fetcher | null);
3617 tails?: Fetcher[];
3618 streamingTails?: Fetcher[];
3619}
3620interface workerdResourceLimits {
3621 cpuMs?: number;
3622 subRequests?: number;
3623}
3624/**
3625* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,
3626* as well as timing of subrequests and other operations.
3627*
3628* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)
3629*/
3630declare abstract class Performance {
3631 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */
3632 get timeOrigin(): number;
3633 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */
3634 now(): number;
3635 /**
3636 * The **`toJSON()`** method of the Performance interface is a serializer; it returns a JSON representation of the Performance object.
3637 *
3638 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON)
3639 */
3640 toJSON(): object;
3641}
3642interface Tracing {
3643 enterSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;
3644 startActiveSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;
3645 startSpan(name: string): Span;
3646 getActiveSpan(): Span | undefined;
3647 Span: typeof Span;
3648}
3649declare abstract class Span {
3650 get isTraced(): boolean;
3651 setAttribute(key: string, value: boolean | number | string): this;
3652 setAttributes(attributes: Record<string, boolean | number | string | undefined>): this;
3653 recordException(exception: string | {
3654 code: string | number;
3655 name?: string;
3656 message?: string;
3657 stack?: string;
3658 } | {
3659 code?: string | number;
3660 name: string;
3661 message?: string;
3662 stack?: string;
3663 } | {
3664 code?: string | number;
3665 name?: string;
3666 message: string;
3667 stack?: string;
3668 }): void;
3669 end(): void;
3670}
3671/**
3672 * Represents the identity of a user authenticated via Cloudflare Access.
3673 * This matches the result of calling /cdn-cgi/access/get-identity.
3674 *
3675 * The exact structure of the returned object depends on the identity provider
3676 * configuration for the Access application. The fields below represent commonly
3677 * available properties, but additional provider-specific fields may be present.
3678 */
3679interface CloudflareAccessIdentity extends Record<string, unknown> {
3680 /** The user's email address, if available from the identity provider. */
3681 email?: string;
3682 /** The user's display name. */
3683 name?: string;
3684 /** The user's unique identifier. */
3685 user_uuid?: string;
3686 /** The Cloudflare account ID. */
3687 account_id?: string;
3688 /** Login timestamp (Unix epoch seconds). */
3689 iat?: number;
3690 /** The user's IP address at authentication time. */
3691 ip?: string;
3692 /** Authentication methods used (e.g., "pwd"). */
3693 amr?: string[];
3694 /** Identity provider information. */
3695 idp?: {
3696 id: string;
3697 type: string;
3698 };
3699 /** Geographic information about where the user authenticated. */
3700 geo?: {
3701 country: string;
3702 };
3703 /** Group memberships from the identity provider. */
3704 groups?: Array<{
3705 id: string;
3706 name: string;
3707 email?: string;
3708 }>;
3709 /** Device posture check results, keyed by check ID. */
3710 devicePosture?: Record<string, unknown>;
3711 /** True if the user connected via Cloudflare WARP. */
3712 is_warp?: boolean;
3713 /** True if the user is authenticated via Cloudflare Gateway. */
3714 is_gateway?: boolean;
3715}
3716// ============================================================================
3717// Agent Memory
3718//
3719// Public type surface for user Workers binding to an Agent Memory namespace.
3720// ============================================================================
3721/** Memory type โ€” every memory is classified into exactly one. */
3722type AgentMemoryMemoryType = "fact" | "event" | "instruction" | "task";
3723/** Search intensity for recall. */
3724type AgentMemoryThinkingLevel = "low" | "medium" | "high";
3725/** Response verbosity for recall. */
3726type AgentMemoryResponseLength = "short" | "medium" | "long";
3727/** A conversation message passed to ingest(). */
3728interface AgentMemoryMessage {
3729 role: "system" | "user" | "assistant";
3730 content: string;
3731 /** Optional message timestamp. */
3732 timestamp?: Date;
3733}
3734/** Raw memory content passed to remember(). */
3735interface AgentMemoryIncomingMemory {
3736 /** Raw memory content. The service classifies and summarizes automatically. */
3737 content: string;
3738 /** Optional session identifier to associate with this memory. */
3739 sessionId?: string | null | undefined;
3740}
3741/** A stored memory returned from remember(), get(), and delete(). */
3742interface AgentMemoryMemory {
3743 /** Memory ID. */
3744 id: string;
3745 /** Memory type. */
3746 type: AgentMemoryMemoryType;
3747 /** Text summary. */
3748 summary: string;
3749 /** Memory text. */
3750 content: string;
3751 /** Session that created this memory. */
3752 sessionId: string | null;
3753 /** Memory creation time. */
3754 createdAt: Date;
3755 /** Memory last-update time. */
3756 updatedAt: Date;
3757}
3758/** Single entry in a list() response. Same shape as Memory minus full content. */
3759type AgentMemoryMemoryListEntry = Omit<AgentMemoryMemory, "content">;
3760/** A scored memory candidate in a recall result. */
3761interface AgentMemoryScoredCandidate {
3762 /** Candidate ID. */
3763 id: string;
3764 /** Text summary. */
3765 summary: string;
3766 /** Session that created this candidate, when known. */
3767 sessionId: string | null;
3768 /** Relevance score (higher is better). Comparable only within a single query. */
3769 score: number;
3770}
3771/** Options for the ingest() method. */
3772interface AgentMemoryIngestOptions {
3773 /** Session identifier to associate with memories created during ingestion. */
3774 sessionId?: string | null | undefined;
3775}
3776/** Options for the getSummary() method. */
3777interface AgentMemoryGetSummaryOptions {
3778 /** Session identifier to retrieve session summary for. */
3779 sessionId?: string | null | undefined;
3780}
3781/** Response from the getSummary() method. */
3782interface AgentMemoryGetSummaryResponse {
3783 /** Markdown summary. */
3784 summary: string;
3785}
3786/**
3787 * Options for the recall() method.
3788 *
3789 * `referenceDate` accepts a Date object, an ISO-8601 date string
3790 * (YYYY-MM-DD), or a full ISO-8601 datetime string. When provided, this
3791 * date is used as "today" for resolving relative time references
3792 * ("how many days ago", "last week") instead of the server's wall-clock time.
3793 */
3794interface AgentMemoryRecallOptions {
3795 /** Recall intensity: "low" (default), "medium", or "high". */
3796 thinkingLevel?: AgentMemoryThinkingLevel;
3797 /** Response verbosity: "short", "medium" (default), or "long". */
3798 responseLength?: AgentMemoryResponseLength;
3799 /** Temporal anchor for date arithmetic. */
3800 referenceDate?: Date | string;
3801}
3802/** Response from the recall() method. */
3803interface AgentMemoryRecallResult {
3804 /** Number of memories retrieved. */
3805 count: number;
3806 /** LLM-generated answer synthesizing the matching memories. */
3807 answer: string;
3808 /** Matching memories ranked by relevance. */
3809 candidates: AgentMemoryScoredCandidate[];
3810}
3811/**
3812 * Options for the list() method.
3813 *
3814 * `cursor` is the opaque continuation token returned by the previous page;
3815 * pass it back unchanged to fetch the next page. `sessionId` and `type`
3816 * are exact-match filters; combining them is allowed.
3817 */
3818interface AgentMemoryListMemoriesOptions {
3819 /** Maximum number of memories to return. Default 20, max 500. */
3820 limit?: number;
3821 /** Opaque cursor from a previous page. */
3822 cursor?: string;
3823 /** Exact-match session filter. */
3824 sessionId?: string;
3825 /** Exact-match memory-type filter. */
3826 type?: AgentMemoryMemoryType;
3827}
3828/** Response from the list() method. */
3829interface AgentMemoryListMemoriesResult {
3830 memories: AgentMemoryMemoryListEntry[];
3831 /** Continuation cursor; absent when this page exhausted the result set. */
3832 cursor?: string;
3833}
3834/**
3835 * A single Agent Memory profile, scoped to a profile name.
3836 *
3837 * Returned by {@link AgentMemoryNamespace.getProfile}.
3838 */
3839declare abstract class AgentMemoryProfile {
3840 /**
3841 * Retrieve a memory by ID.
3842 *
3843 * @param memoryId - ULID of the memory to retrieve.
3844 * @throws if the memory does not exist.
3845 */
3846 get(memoryId: string): Promise<AgentMemoryMemory>;
3847 /**
3848 * Delete a memory by ID.
3849 *
3850 * Removes the memory and any source messages linked by the memory's
3851 * source message IDs.
3852 *
3853 * @param memoryId - ULID of the memory to delete.
3854 * @throws if the memory does not exist.
3855 */
3856 delete(memoryId: string): Promise<AgentMemoryMemory>;
3857 /**
3858 * Store a memory in this profile. The content is automatically classified,
3859 * summarized, and indexed.
3860 *
3861 * @param memory - Raw memory content to persist.
3862 */
3863 remember(memory: AgentMemoryIncomingMemory): Promise<AgentMemoryMemory>;
3864 /**
3865 * Extract memories from a conversation.
3866 *
3867 * @param messages - Conversation messages to extract memories from.
3868 * @param options - Optional ingest options.
3869 */
3870 ingest(messages: Iterable<AgentMemoryMessage>, options?: AgentMemoryIngestOptions): Promise<void>;
3871 /**
3872 * Get a profile summary.
3873 *
3874 * @param options - Optional getSummary options.
3875 */
3876 getSummary(options?: AgentMemoryGetSummaryOptions): Promise<AgentMemoryGetSummaryResponse>;
3877 /**
3878 * Recall memories in this profile.
3879 *
3880 * @param query - Recall query matched against memory content and keywords.
3881 * @param options - Optional recall parameters.
3882 * @returns Matching memories with relevance scores and a synthesized answer.
3883 */
3884 recall(query: string, options?: AgentMemoryRecallOptions): Promise<AgentMemoryRecallResult>;
3885 /**
3886 * List active memories in this profile.
3887 *
3888 * Returns a paginated, filterable view of stored memories. Superseded
3889 * versions are excluded. Use the returned `cursor` (when present) to
3890 * fetch the next page.
3891 *
3892 * @param options - Optional pagination and filter options.
3893 */
3894 list(options?: AgentMemoryListMemoriesOptions): Promise<AgentMemoryListMemoriesResult>;
3895 /**
3896 * Soft-delete every memory and message in this profile that is tagged
3897 * with `sessionId`.
3898 *
3899 * Idempotent: deleting a sessionId that has no rows is a no-op.
3900 *
3901 * @param sessionId - Session to delete.
3902 */
3903 deleteSession(sessionId: string): Promise<void>;
3904}
3905/**
3906 * Namespace-level Agent Memory binding.
3907 *
3908 * Used as the type of an `env.MEMORY`-style binding backed by the Agent
3909 * Memory product.
3910 *
3911 * @example
3912 * ```ts
3913 * export default {
3914 * async fetch(_request: Request, env: Env): Promise<Response> {
3915 * const profile = await env.MEMORY.getProfile("wrangler-e2e");
3916 * const summary = await profile.getSummary();
3917 * return Response.json(summary);
3918 * },
3919 * };
3920 * ```
3921 */
3922declare abstract class AgentMemoryNamespace {
3923 /**
3924 * Get a memory profile by name. Profiles are isolated by namespace and
3925 * addressed by a compound key (namespaceId:profileName).
3926 *
3927 * @param profileName - Profile name (validated against naming rules).
3928 * @returns RPC target for interacting with the profile.
3929 */
3930 getProfile(profileName: string): Promise<AgentMemoryProfile>;
3931 /**
3932 * Soft-delete a profile and schedule deferred purge. Marks all
3933 * memories and messages as deleted.
3934 *
3935 * @param profileName - Name of the profile to delete.
3936 */
3937 deleteProfile(profileName: string): Promise<void>;
3938}
3939// ============ AI Search Error Interfaces ============
3940interface AiSearchInternalError extends Error {
3941}
3942interface AiSearchNotFoundError extends Error {
3943}
3944// ============ AI Search Common Types ============
3945/** A single message in a conversation-style search or chat request. */
3946type AiSearchMessage = {
3947 role: 'system' | 'developer' | 'user' | 'assistant' | 'tool';
3948 content: string | null;
3949};
3950/**
3951 * Common shape for `ai_search_options` used by both single-instance and multi-instance requests.
3952 * Contains retrieval, query rewrite, reranking, and cache sub-options.
3953 */
3954type AiSearchOptions = {
3955 retrieval?: {
3956 /** Which retrieval backend to use. Defaults to the instance's configured index_method. */
3957 retrieval_type?: 'vector' | 'keyword' | 'hybrid';
3958 /** Fusion method for combining vector + keyword results. */
3959 fusion_method?: 'max' | 'rrf';
3960 /** How keyword terms are combined: "and" = all terms must match, "or" = any term matches. */
3961 keyword_match_mode?: 'and' | 'or';
3962 /** Minimum similarity score (0-1) for a result to be included. Default 0.4. */
3963 match_threshold?: number;
3964 /** Maximum number of results to return (1-50). Default 10. */
3965 max_num_results?: number;
3966 /** Vectorize metadata filters applied to the search. */
3967 filters?: VectorizeVectorMetadataFilter;
3968 /** Number of surrounding chunks to include for context (0-3). Default 0. */
3969 context_expansion?: number;
3970 /** If true, return only item metadata without chunk text. */
3971 metadata_only?: boolean;
3972 /** If true (default), return empty results on retrieval failure instead of throwing. */
3973 return_on_failure?: boolean;
3974 /** Boost results by metadata field values. Max 3 entries. */
3975 boost_by?: Array<{
3976 field: string;
3977 direction?: 'asc' | 'desc' | 'exists' | 'not_exists';
3978 }>;
3979 [key: string]: unknown;
3980 };
3981 query_rewrite?: {
3982 enabled?: boolean;
3983 model?: string;
3984 rewrite_prompt?: string;
3985 [key: string]: unknown;
3986 };
3987 reranking?: {
3988 enabled?: boolean;
3989 model?: string;
3990 /** Match threshold (0-1, default 0.4) */
3991 match_threshold?: number;
3992 [key: string]: unknown;
3993 };
3994 cache?: {
3995 enabled?: boolean;
3996 cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';
3997 };
3998 [key: string]: unknown;
3999};
4000// ============ AI Search Request Types ============
4001/**
4002 * Request body for single-instance search.
4003 * Exactly one of `query` or `messages` must be provided.
4004 */
4005type AiSearchSearchRequest = {
4006 /** Simple query string. */
4007 query: string;
4008 messages?: never;
4009 ai_search_options?: AiSearchOptions;
4010} | {
4011 query?: never;
4012 /** Conversation-style input. At least one user message with non-empty content is required. */
4013 messages: AiSearchMessage[];
4014 ai_search_options?: AiSearchOptions;
4015};
4016type AiSearchChatCompletionsRequest = {
4017 messages: AiSearchMessage[];
4018 model?: string;
4019 stream?: boolean;
4020 ai_search_options?: AiSearchOptions;
4021 [key: string]: unknown;
4022};
4023// ============ AI Search Multi-Instance Types (Namespace-Scoped) ============
4024/** `ai_search_options` shape for multi-instance requests โ€” requires `instance_ids`. */
4025type AiSearchMultiSearchOptions = AiSearchOptions & {
4026 /** Instance IDs to search across (1-10). */
4027 instance_ids: string[];
4028};
4029/**
4030 * Request for searching across multiple instances within a namespace.
4031 * `ai_search_options` is required and must include `instance_ids`.
4032 * Exactly one of `query` or `messages` must be provided.
4033 */
4034type AiSearchMultiSearchRequest = {
4035 /** Simple query string. */
4036 query: string;
4037 messages?: never;
4038 ai_search_options: AiSearchMultiSearchOptions;
4039} | {
4040 query?: never;
4041 /** Conversation-style input. */
4042 messages: AiSearchMessage[];
4043 ai_search_options: AiSearchMultiSearchOptions;
4044};
4045/** A search result chunk tagged with the instance it originated from. */
4046type AiSearchMultiSearchChunk = AiSearchSearchResponse['chunks'][number] & {
4047 instance_id: string;
4048};
4049/** Describes a per-instance error during a multi-instance operation. */
4050type AiSearchMultiSearchError = {
4051 instance_id: string;
4052 message: string;
4053};
4054/** Response from a multi-instance search, with chunks tagged by instance and optional partial-failure errors. */
4055type AiSearchMultiSearchResponse = {
4056 search_query: string;
4057 chunks: AiSearchMultiSearchChunk[];
4058 errors?: AiSearchMultiSearchError[];
4059};
4060/** Request for chat completions across multiple instances within a namespace. `ai_search_options` is required and must include `instance_ids`. */
4061type AiSearchMultiChatCompletionsRequest = Omit<AiSearchChatCompletionsRequest, 'ai_search_options'> & {
4062 ai_search_options: AiSearchMultiSearchOptions;
4063};
4064/** Response from multi-instance chat completions, with chunks tagged by instance and optional partial-failure errors. */
4065type AiSearchMultiChatCompletionsResponse = Omit<AiSearchChatCompletionsResponse, 'chunks'> & {
4066 chunks: AiSearchMultiSearchChunk[];
4067 errors?: AiSearchMultiSearchError[];
4068};
4069// ============ AI Search Response Types ============
4070type AiSearchSearchResponse = {
4071 search_query: string;
4072 chunks: Array<{
4073 id: string;
4074 type: string;
4075 /** Match score (0-1) */
4076 score: number;
4077 text: string;
4078 item: {
4079 timestamp?: number;
4080 key: string;
4081 metadata?: Record<string, unknown>;
4082 };
4083 scoring_details?: {
4084 /** Keyword match score (0-1) */
4085 keyword_score?: number;
4086 /** Vector similarity score (0-1) */
4087 vector_score?: number;
4088 /** Keyword rank position */
4089 keyword_rank?: number;
4090 /** Vector rank position */
4091 vector_rank?: number;
4092 /** Reranking model score */
4093 reranking_score?: number;
4094 /** Fusion method used to combine results */
4095 fusion_method?: 'rrf' | 'max';
4096 [key: string]: unknown;
4097 };
4098 }>;
4099};
4100type AiSearchChatCompletionsResponse = {
4101 id?: string;
4102 object?: string;
4103 model?: string;
4104 choices: Array<{
4105 index?: number;
4106 message: {
4107 role: 'system' | 'developer' | 'user' | 'assistant' | 'tool';
4108 content: string | null;
4109 [key: string]: unknown;
4110 };
4111 [key: string]: unknown;
4112 }>;
4113 chunks: AiSearchSearchResponse['chunks'];
4114 [key: string]: unknown;
4115};
4116type AiSearchStatsResponse = {
4117 queued?: number;
4118 running?: number;
4119 completed?: number;
4120 error?: number;
4121 skipped?: number;
4122 outdated?: number;
4123 last_activity?: string;
4124 /** Storage engine statistics. */
4125 engine?: {
4126 vectorize?: {
4127 vectorsCount: number;
4128 dimensions: number;
4129 };
4130 r2?: {
4131 payloadSizeBytes: number;
4132 metadataSizeBytes: number;
4133 objectCount: number;
4134 };
4135 };
4136};
4137// ============ AI Search Instance Info Types ============
4138type AiSearchInstanceInfo = {
4139 id: string;
4140 type?: 'r2' | 'web-crawler' | string;
4141 source?: string;
4142 source_params?: unknown;
4143 paused?: boolean;
4144 status?: string;
4145 namespace?: string;
4146 created_at?: string;
4147 modified_at?: string;
4148 token_id?: string;
4149 ai_gateway_id?: string;
4150 rewrite_query?: boolean;
4151 reranking?: boolean;
4152 embedding_model?: string;
4153 ai_search_model?: string;
4154 rewrite_model?: string;
4155 reranking_model?: string;
4156 /** @deprecated Use index_method instead. */
4157 hybrid_search_enabled?: boolean;
4158 /** Controls which storage backends are active. */
4159 index_method?: {
4160 vector?: boolean;
4161 keyword?: boolean;
4162 };
4163 /** Fusion method for combining vector and keyword results. */
4164 fusion_method?: 'max' | 'rrf';
4165 indexing_options?: {
4166 keyword_tokenizer?: 'porter' | 'trigram';
4167 } | null;
4168 retrieval_options?: {
4169 keyword_match_mode?: 'and' | 'or';
4170 boost_by?: Array<{
4171 field: string;
4172 direction?: 'asc' | 'desc' | 'exists' | 'not_exists';
4173 }>;
4174 } | null;
4175 chunk?: boolean;
4176 chunk_size?: number;
4177 chunk_overlap?: number;
4178 score_threshold?: number;
4179 max_num_results?: number;
4180 cache?: boolean;
4181 cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';
4182 custom_metadata?: Array<{
4183 field_name: string;
4184 data_type: 'text' | 'number' | 'boolean' | 'datetime';
4185 }>;
4186 /** Sync interval in seconds. */
4187 sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400;
4188 metadata?: Record<string, unknown>;
4189 [key: string]: unknown;
4190};
4191/** Pagination, search, and ordering parameters for listing instances within a namespace. */
4192type AiSearchListInstancesParams = {
4193 page?: number;
4194 per_page?: number;
4195 /** Search instances by ID. */
4196 search?: string;
4197 /** Field to sort by. */
4198 order_by?: 'created_at';
4199 /** Sort direction. */
4200 order_by_direction?: 'asc' | 'desc';
4201};
4202type AiSearchListResponse = {
4203 result: AiSearchInstanceInfo[];
4204 result_info?: {
4205 count: number;
4206 page: number;
4207 per_page: number;
4208 total_count: number;
4209 };
4210};
4211// ============ AI Search Config Types ============
4212type AiSearchConfig = {
4213 /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */
4214 id: string;
4215 /** Instance type. Omit to create with built-in storage. */
4216 type?: 'r2' | 'web-crawler' | string;
4217 /** Source URL (required for web-crawler type). */
4218 source?: string;
4219 source_params?: unknown;
4220 /** Token ID (UUID format) */
4221 token_id?: string;
4222 ai_gateway_id?: string;
4223 /** Enable query rewriting (default false) */
4224 rewrite_query?: boolean;
4225 /** Enable reranking (default false) */
4226 reranking?: boolean;
4227 embedding_model?: string;
4228 ai_search_model?: string;
4229 rewrite_model?: string;
4230 reranking_model?: string;
4231 /** @deprecated Use index_method instead. */
4232 hybrid_search_enabled?: boolean;
4233 /** Controls which storage backends are used during indexing. Defaults to vector-only. */
4234 index_method?: {
4235 vector?: boolean;
4236 keyword?: boolean;
4237 };
4238 /** Fusion method for combining vector and keyword results. "rrf" = reciprocal rank fusion (default), "max" = maximum score. */
4239 fusion_method?: 'max' | 'rrf';
4240 indexing_options?: {
4241 keyword_tokenizer?: 'porter' | 'trigram';
4242 } | null;
4243 retrieval_options?: {
4244 keyword_match_mode?: 'and' | 'or';
4245 boost_by?: Array<{
4246 field: string;
4247 direction?: 'asc' | 'desc' | 'exists' | 'not_exists';
4248 }>;
4249 } | null;
4250 chunk?: boolean;
4251 chunk_size?: number;
4252 chunk_overlap?: number;
4253 /** Minimum similarity score (0-1) for a result to be included. */
4254 score_threshold?: number;
4255 max_num_results?: number;
4256 cache?: boolean;
4257 /** Similarity threshold for cache hits. Stricter = fewer cache hits but higher relevance. */
4258 cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';
4259 custom_metadata?: Array<{
4260 field_name: string;
4261 data_type: 'text' | 'number' | 'boolean' | 'datetime';
4262 }>;
4263 namespace?: string;
4264 /** Sync interval in seconds. 3600=1h, 7200=2h, 14400=4h, 21600=6h, 43200=12h, 86400=24h. */
4265 sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400;
4266 metadata?: Record<string, unknown>;
4267 [key: string]: unknown;
4268};
4269// ============ AI Search Item Types ============
4270type AiSearchItemInfo = {
4271 id: string;
4272 key: string;
4273 status: 'completed' | 'error' | 'skipped' | 'queued' | 'running' | 'outdated';
4274 next_action?: 'INDEX' | 'DELETE' | null;
4275 error?: string;
4276 checksum?: string;
4277 namespace?: string;
4278 chunks_count?: number | null;
4279 file_size?: number | null;
4280 source_id?: string | null;
4281 last_seen_at?: string;
4282 created_at?: string;
4283 metadata?: Record<string, unknown>;
4284 [key: string]: unknown;
4285};
4286type AiSearchItemContentResult = {
4287 body: ReadableStream;
4288 contentType: string;
4289 filename: string;
4290 size: number;
4291};
4292type AiSearchUploadItemOptions = {
4293 metadata?: Record<string, unknown>;
4294};
4295type AiSearchListItemsParams = {
4296 page?: number;
4297 per_page?: number;
4298 /** Search items by key name. */
4299 search?: string;
4300 /** Sort order for results. */
4301 sort_by?: 'status' | 'modified_at';
4302 /** Filter items by processing status. */
4303 status?: 'queued' | 'running' | 'completed' | 'error' | 'skipped' | 'outdated';
4304 /** Filter items by source (e.g. "builtin" or "web-crawler:https://example.com"). */
4305 source?: string;
4306 /** JSON-encoded Vectorize filter for metadata filtering. */
4307 metadata_filter?: string;
4308 /** Filter items by their unique ID. Returns at most one item. */
4309 item_id?: string;
4310 /**
4311 * Filter items by their exact key (object key / filename). Keys are unique
4312 * per source, so combine with `source` to disambiguate across data sources.
4313 */
4314 key?: string;
4315};
4316type AiSearchListItemsResponse = {
4317 result: AiSearchItemInfo[];
4318 result_info?: {
4319 count: number;
4320 page: number;
4321 per_page: number;
4322 total_count: number;
4323 };
4324};
4325// ============ AI Search Item Logs Types ============
4326type AiSearchItemLogsParams = {
4327 /** Maximum number of log entries to return (1-100, default 50). */
4328 limit?: number;
4329 /** Opaque cursor for pagination. Pass the `cursor` value from a previous response. */
4330 cursor?: string;
4331};
4332type AiSearchItemLog = {
4333 timestamp: string;
4334 action: string;
4335 message: string;
4336 fileKey?: string;
4337 chunkCount?: number;
4338 processingTimeMs?: number;
4339 errorType?: string;
4340};
4341/** Paginated response for item processing logs (cursor-based). */
4342type AiSearchItemLogsResponse = {
4343 result: AiSearchItemLog[];
4344 result_info: {
4345 count: number;
4346 per_page: number;
4347 cursor: string | null;
4348 truncated: boolean;
4349 };
4350};
4351// ============ AI Search Item Chunks Types ============
4352type AiSearchItemChunksParams = {
4353 /** Maximum number of chunks to return (1-100, default 20). */
4354 limit?: number;
4355 /** Offset into the chunks list (default 0). */
4356 offset?: number;
4357};
4358/** A single indexed chunk belonging to an item, including its text content and byte range. */
4359type AiSearchItemChunk = {
4360 id: string;
4361 text: string;
4362 start_byte: number;
4363 end_byte: number;
4364 item?: {
4365 timestamp?: number;
4366 key: string;
4367 metadata?: Record<string, unknown>;
4368 };
4369};
4370/** Paginated response for item chunks (offset-based). */
4371type AiSearchItemChunksResponse = {
4372 result: AiSearchItemChunk[];
4373 result_info: {
4374 count: number;
4375 total: number;
4376 limit: number;
4377 offset: number;
4378 };
4379};
4380// ============ AI Search Job Types ============
4381type AiSearchJobInfo = {
4382 id: string;
4383 source: 'user' | 'schedule';
4384 description?: string;
4385 last_seen_at?: string;
4386 started_at?: string;
4387 ended_at?: string;
4388 end_reason?: string;
4389};
4390type AiSearchJobLog = {
4391 id: number;
4392 message: string;
4393 message_type: number;
4394 created_at: number;
4395};
4396type AiSearchCreateJobParams = {
4397 description?: string;
4398};
4399type AiSearchListJobsParams = {
4400 page?: number;
4401 per_page?: number;
4402};
4403type AiSearchListJobsResponse = {
4404 result: AiSearchJobInfo[];
4405 result_info?: {
4406 count: number;
4407 page: number;
4408 per_page: number;
4409 total_count: number;
4410 };
4411};
4412type AiSearchJobLogsParams = {
4413 page?: number;
4414 per_page?: number;
4415};
4416type AiSearchJobLogsResponse = {
4417 result: AiSearchJobLog[];
4418 result_info?: {
4419 count: number;
4420 page: number;
4421 per_page: number;
4422 total_count: number;
4423 };
4424};
4425// ============ AI Search Sub-Service Classes ============
4426/**
4427 * Single item service for an AI Search instance.
4428 * Provides info, download, sync, logs, and chunks operations on a specific item.
4429 */
4430declare abstract class AiSearchItem {
4431 /** Get metadata about this item. */
4432 info(): Promise<AiSearchItemInfo>;
4433 /**
4434 * Download the item's content.
4435 * @returns Object with body stream, content type, filename, and size.
4436 */
4437 download(): Promise<AiSearchItemContentResult>;
4438 /**
4439 * Trigger re-indexing of this item.
4440 * @returns The updated item info.
4441 */
4442 sync(): Promise<AiSearchItemInfo>;
4443 /**
4444 * Retrieve processing logs for this item (cursor-based pagination).
4445 * @param params Optional pagination parameters (limit, cursor).
4446 * @returns Paginated log entries for this item.
4447 */
4448 logs(params?: AiSearchItemLogsParams): Promise<AiSearchItemLogsResponse>;
4449 /**
4450 * List indexed chunks for this item (offset-based pagination).
4451 * @param params Optional pagination parameters (limit, offset).
4452 * @returns Paginated chunk entries for this item.
4453 */
4454 chunks(params?: AiSearchItemChunksParams): Promise<AiSearchItemChunksResponse>;
4455}
4456/**
4457 * Items collection service for an AI Search instance.
4458 * Provides list, upload, and access to individual items.
4459 */
4460declare abstract class AiSearchItems {
4461 /** List items in this instance. */
4462 list(params?: AiSearchListItemsParams): Promise<AiSearchListItemsResponse>;
4463 /**
4464 * Upload a file as an item. Behaves as an upsert: if an item with the same
4465 * filename already exists, it is overwritten and re-indexed.
4466 * @param name Filename for the uploaded item.
4467 * @param content File content as a ReadableStream, Blob, or string.
4468 * @param options Optional metadata to attach to the item.
4469 * @returns The created item info.
4470 */
4471 upload(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions): Promise<AiSearchItemInfo>;
4472 /**
4473 * Upload a file and poll until processing completes.
4474 * Behaves as an upsert: if an item with the same filename already exists,
4475 * it is overwritten and re-indexed.
4476 * @param name Filename for the uploaded item.
4477 * @param content File content as a ReadableStream, Blob, or string.
4478 * @param options Optional metadata and polling configuration.
4479 * @returns The item info after processing completes (or timeout).
4480 */
4481 uploadAndPoll(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions & {
4482 /** Polling interval in milliseconds (default 1000). */
4483 pollIntervalMs?: number;
4484 /** Maximum time to wait in milliseconds (default 30000). */
4485 timeoutMs?: number;
4486 }): Promise<AiSearchItemInfo>;
4487 /**
4488 * Get an item by ID.
4489 * @param itemId The item identifier.
4490 * @returns Item service for info, download, sync, logs, and chunks operations.
4491 */
4492 get(itemId: string): AiSearchItem;
4493 /**
4494 * Delete an item from the instance.
4495 * @param itemId The item identifier.
4496 */
4497 delete(itemId: string): Promise<void>;
4498}
4499/**
4500 * Single job service for an AI Search instance.
4501 * Provides info, logs, and cancel operations for a specific job.
4502 */
4503declare abstract class AiSearchJob {
4504 /** Get metadata about this job. */
4505 info(): Promise<AiSearchJobInfo>;
4506 /** Get logs for this job. */
4507 logs(params?: AiSearchJobLogsParams): Promise<AiSearchJobLogsResponse>;
4508 /**
4509 * Cancel a running job.
4510 * @returns The updated job info.
4511 * @throws AiSearchNotFoundError if the job does not exist.
4512 */
4513 cancel(): Promise<AiSearchJobInfo>;
4514}
4515/**
4516 * Jobs collection service for an AI Search instance.
4517 * Provides list, create, and access to individual jobs.
4518 */
4519declare abstract class AiSearchJobs {
4520 /** List jobs for this instance. */
4521 list(params?: AiSearchListJobsParams): Promise<AiSearchListJobsResponse>;
4522 /**
4523 * Create a new indexing job.
4524 * @param params Optional job parameters.
4525 * @returns The created job info.
4526 */
4527 create(params?: AiSearchCreateJobParams): Promise<AiSearchJobInfo>;
4528 /**
4529 * Get a job by ID.
4530 * @param jobId The job identifier.
4531 * @returns Job service for info, logs, and cancel operations.
4532 */
4533 get(jobId: string): AiSearchJob;
4534}
4535// ============ AI Search Binding Classes ============
4536/**
4537 * Instance-level AI Search service.
4538 *
4539 * Used as:
4540 * - The return type of `AiSearchNamespace.get(name)` (namespace binding)
4541 * - The type of `env.BLOG_SEARCH` (single instance binding via `ai_search`)
4542 *
4543 * Provides search, chat, update, stats, items, and jobs operations.
4544 *
4545 * @example
4546 * ```ts
4547 * // Via namespace binding
4548 * const instance = env.AI_SEARCH.get("blog");
4549 * const results = await instance.search({
4550 * query: "How does caching work?",
4551 * });
4552 *
4553 * // Via single instance binding
4554 * const results = await env.BLOG_SEARCH.search({
4555 * messages: [{ role: "user", content: "How does caching work?" }],
4556 * });
4557 * ```
4558 */
4559declare abstract class AiSearchInstance {
4560 /**
4561 * Search the AI Search instance for relevant chunks.
4562 * @param params Search request with query or messages and optional AI search options.
4563 * @returns Search response with matching chunks and search query.
4564 */
4565 search(params: AiSearchSearchRequest): Promise<AiSearchSearchResponse>;
4566 /**
4567 * Generate chat completions with AI Search context (streaming).
4568 * @param params Chat completions request with stream: true.
4569 * @returns ReadableStream of server-sent events.
4570 */
4571 chatCompletions(params: AiSearchChatCompletionsRequest & {
4572 stream: true;
4573 }): Promise<ReadableStream>;
4574 /**
4575 * Generate chat completions with AI Search context.
4576 * @param params Chat completions request.
4577 * @returns Chat completion response with choices and RAG chunks.
4578 */
4579 chatCompletions(params: AiSearchChatCompletionsRequest): Promise<AiSearchChatCompletionsResponse>;
4580 /**
4581 * Update the instance configuration.
4582 * @param config Partial configuration to update.
4583 * @returns Updated instance info.
4584 */
4585 update(config: Partial<AiSearchConfig>): Promise<AiSearchInstanceInfo>;
4586 /** Get metadata about this instance. */
4587 info(): Promise<AiSearchInstanceInfo>;
4588 /**
4589 * Get instance statistics (item count, indexing status, etc.).
4590 * @returns Statistics with counts per status, last activity time, and engine details.
4591 */
4592 stats(): Promise<AiSearchStatsResponse>;
4593 /** Items collection โ€” list, upload, and manage items in this instance. */
4594 get items(): AiSearchItems;
4595 /** Jobs collection โ€” list, create, and inspect indexing jobs. */
4596 get jobs(): AiSearchJobs;
4597}
4598/**
4599 * Namespace-level AI Search service.
4600 *
4601 * Used as the type of `env.AI_SEARCH` (namespace binding via `ai_search_namespaces`).
4602 * Scoped to a single namespace. Provides dynamic instance access, creation, deletion,
4603 * and multi-instance search/chat operations.
4604 *
4605 * @example
4606 * ```ts
4607 * // Access an instance within the namespace
4608 * const blog = env.AI_SEARCH.get("blog");
4609 * const results = await blog.search({ query: "How does caching work?" });
4610 *
4611 * // List all instances in the namespace
4612 * const instances = await env.AI_SEARCH.list();
4613 *
4614 * // Create a new instance with built-in storage
4615 * const tenant = await env.AI_SEARCH.create({ id: "tenant-123" });
4616 *
4617 * // Upload items into the instance
4618 * await tenant.items.upload("doc.pdf", fileContent);
4619 *
4620 * // Search across multiple instances
4621 * const multi = await env.AI_SEARCH.search({
4622 * query: "caching",
4623 * ai_search_options: { instance_ids: ["blog", "docs"] },
4624 * });
4625 *
4626 * // Delete an instance
4627 * await env.AI_SEARCH.delete("tenant-123");
4628 * ```
4629 */
4630declare abstract class AiSearchNamespace {
4631 /**
4632 * Get an instance by name within the bound namespace.
4633 * @param name Instance name.
4634 * @returns Instance service for search, chat, update, stats, items, and jobs.
4635 */
4636 get(name: string): AiSearchInstance;
4637 /**
4638 * List instances in the bound namespace.
4639 * @param params Optional pagination, search, and ordering parameters.
4640 * @returns Array of instance metadata with pagination info.
4641 */
4642 list(params?: AiSearchListInstancesParams): Promise<AiSearchListResponse>;
4643 /**
4644 * Create a new instance within the bound namespace.
4645 * @param config Instance configuration. Only `id` is required โ€” omit `type` and `source` to create with built-in storage.
4646 * @returns Instance service for the newly created instance.
4647 *
4648 * @example
4649 * ```ts
4650 * // Create with built-in storage (upload items manually)
4651 * const instance = await env.AI_SEARCH.create({ id: "my-search" });
4652 *
4653 * // Create with web crawler source
4654 * const instance = await env.AI_SEARCH.create({
4655 * id: "docs-search",
4656 * type: "web-crawler",
4657 * source: "https://developers.cloudflare.com",
4658 * });
4659 * ```
4660 */
4661 create(config: AiSearchConfig): Promise<AiSearchInstance>;
4662 /**
4663 * Delete an instance from the bound namespace.
4664 * @param name Instance name to delete.
4665 */
4666 delete(name: string): Promise<void>;
4667 /**
4668 * Search across multiple instances within the bound namespace.
4669 * Fans out to the specified instance_ids and merges results.
4670 * @param params Search request with required `ai_search_options.instance_ids`.
4671 * @returns Search response with chunks tagged by instance_id and optional partial-failure errors.
4672 */
4673 search(params: AiSearchMultiSearchRequest): Promise<AiSearchMultiSearchResponse>;
4674 /**
4675 * Generate chat completions across multiple instances within the bound namespace (streaming).
4676 * Fans out to the specified instance_ids, merges context, and generates a response.
4677 * @param params Chat completions request with stream: true and required `ai_search_options.instance_ids`.
4678 * @returns ReadableStream of server-sent events.
4679 */
4680 chatCompletions(params: AiSearchMultiChatCompletionsRequest & {
4681 stream: true;
4682 }): Promise<ReadableStream>;
4683 /**
4684 * Generate chat completions across multiple instances within the bound namespace.
4685 * Fans out to the specified instance_ids, merges context, and generates a response.
4686 * @param params Chat completions request with required `ai_search_options.instance_ids`.
4687 * @returns Chat completion response with choices, chunks tagged by instance_id, and optional partial-failure errors.
4688 */
4689 chatCompletions(params: AiSearchMultiChatCompletionsRequest): Promise<AiSearchMultiChatCompletionsResponse>;
4690}
4691type AiImageClassificationInput = {
4692 image: number[];
4693};
4694type AiImageClassificationOutput = {
4695 score?: number;
4696 label?: string;
4697}[];
4698declare abstract class BaseAiImageClassification {
4699 inputs: AiImageClassificationInput;
4700 postProcessedOutputs: AiImageClassificationOutput;
4701}
4702type AiImageToTextInput = {
4703 image: number[];
4704 prompt?: string;
4705 max_tokens?: number;
4706 temperature?: number;
4707 top_p?: number;
4708 top_k?: number;
4709 seed?: number;
4710 repetition_penalty?: number;
4711 frequency_penalty?: number;
4712 presence_penalty?: number;
4713 raw?: boolean;
4714 messages?: RoleScopedChatInput[];
4715};
4716type AiImageToTextOutput = {
4717 description: string;
4718};
4719declare abstract class BaseAiImageToText {
4720 inputs: AiImageToTextInput;
4721 postProcessedOutputs: AiImageToTextOutput;
4722}
4723type AiImageTextToTextInput = {
4724 image: string;
4725 prompt?: string;
4726 max_tokens?: number;
4727 temperature?: number;
4728 ignore_eos?: boolean;
4729 top_p?: number;
4730 top_k?: number;
4731 seed?: number;
4732 repetition_penalty?: number;
4733 frequency_penalty?: number;
4734 presence_penalty?: number;
4735 raw?: boolean;
4736 messages?: RoleScopedChatInput[];
4737};
4738type AiImageTextToTextOutput = {
4739 description: string;
4740};
4741declare abstract class BaseAiImageTextToText {
4742 inputs: AiImageTextToTextInput;
4743 postProcessedOutputs: AiImageTextToTextOutput;
4744}
4745type AiMultimodalEmbeddingsInput = {
4746 image: string;
4747 text: string[];
4748};
4749type AiIMultimodalEmbeddingsOutput = {
4750 data: number[][];
4751 shape: number[];
4752};
4753declare abstract class BaseAiMultimodalEmbeddings {
4754 inputs: AiImageTextToTextInput;
4755 postProcessedOutputs: AiImageTextToTextOutput;
4756}
4757type AiObjectDetectionInput = {
4758 image: number[];
4759};
4760type AiObjectDetectionOutput = {
4761 score?: number;
4762 label?: string;
4763}[];
4764declare abstract class BaseAiObjectDetection {
4765 inputs: AiObjectDetectionInput;
4766 postProcessedOutputs: AiObjectDetectionOutput;
4767}
4768type AiSentenceSimilarityInput = {
4769 source: string;
4770 sentences: string[];
4771};
4772type AiSentenceSimilarityOutput = number[];
4773declare abstract class BaseAiSentenceSimilarity {
4774 inputs: AiSentenceSimilarityInput;
4775 postProcessedOutputs: AiSentenceSimilarityOutput;
4776}
4777type AiAutomaticSpeechRecognitionInput = {
4778 audio: number[];
4779};
4780type AiAutomaticSpeechRecognitionOutput = {
4781 text?: string;
4782 words?: {
4783 word: string;
4784 start: number;
4785 end: number;
4786 }[];
4787 vtt?: string;
4788};
4789declare abstract class BaseAiAutomaticSpeechRecognition {
4790 inputs: AiAutomaticSpeechRecognitionInput;
4791 postProcessedOutputs: AiAutomaticSpeechRecognitionOutput;
4792}
4793type AiSummarizationInput = {
4794 input_text: string;
4795 max_length?: number;
4796};
4797type AiSummarizationOutput = {
4798 summary: string;
4799};
4800declare abstract class BaseAiSummarization {
4801 inputs: AiSummarizationInput;
4802 postProcessedOutputs: AiSummarizationOutput;
4803}
4804type AiTextClassificationInput = {
4805 text: string;
4806};
4807type AiTextClassificationOutput = {
4808 score?: number;
4809 label?: string;
4810}[];
4811declare abstract class BaseAiTextClassification {
4812 inputs: AiTextClassificationInput;
4813 postProcessedOutputs: AiTextClassificationOutput;
4814}
4815type AiTextEmbeddingsInput = {
4816 text: string | string[];
4817};
4818type AiTextEmbeddingsOutput = {
4819 shape: number[];
4820 data: number[][];
4821};
4822declare abstract class BaseAiTextEmbeddings {
4823 inputs: AiTextEmbeddingsInput;
4824 postProcessedOutputs: AiTextEmbeddingsOutput;
4825}
4826type RoleScopedChatInput = {
4827 role: "user" | "assistant" | "system" | "tool" | (string & NonNullable<unknown>);
4828 content: string;
4829 name?: string;
4830};
4831type AiTextGenerationToolLegacyInput = {
4832 name: string;
4833 description: string;
4834 parameters?: {
4835 type: "object" | (string & NonNullable<unknown>);
4836 properties: {
4837 [key: string]: {
4838 type: string;
4839 description?: string;
4840 };
4841 };
4842 required: string[];
4843 };
4844};
4845type AiTextGenerationToolInput = {
4846 type: "function" | (string & NonNullable<unknown>);
4847 function: {
4848 name: string;
4849 description: string;
4850 parameters?: {
4851 type: "object" | (string & NonNullable<unknown>);
4852 properties: {
4853 [key: string]: {
4854 type: string;
4855 description?: string;
4856 };
4857 };
4858 required: string[];
4859 };
4860 };
4861};
4862type AiTextGenerationFunctionsInput = {
4863 name: string;
4864 code: string;
4865};
4866type AiTextGenerationResponseFormat = {
4867 type: string;
4868 json_schema?: any;
4869};
4870type AiTextGenerationInput = {
4871 prompt?: string;
4872 raw?: boolean;
4873 stream?: boolean;
4874 max_tokens?: number;
4875 temperature?: number;
4876 top_p?: number;
4877 top_k?: number;
4878 seed?: number;
4879 repetition_penalty?: number;
4880 frequency_penalty?: number;
4881 presence_penalty?: number;
4882 messages?: RoleScopedChatInput[];
4883 response_format?: AiTextGenerationResponseFormat;
4884 tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable<unknown>);
4885 functions?: AiTextGenerationFunctionsInput[];
4886};
4887type AiTextGenerationToolLegacyOutput = {
4888 name: string;
4889 arguments: unknown;
4890};
4891type AiTextGenerationToolOutput = {
4892 id: string;
4893 type: "function";
4894 function: {
4895 name: string;
4896 arguments: string;
4897 };
4898};
4899type UsageTags = {
4900 prompt_tokens: number;
4901 completion_tokens: number;
4902 total_tokens: number;
4903};
4904type AiTextGenerationOutput = {
4905 response?: string;
4906 tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[];
4907 usage?: UsageTags;
4908};
4909declare abstract class BaseAiTextGeneration {
4910 inputs: AiTextGenerationInput;
4911 postProcessedOutputs: AiTextGenerationOutput;
4912}
4913type AiTextToSpeechInput = {
4914 prompt: string;
4915 lang?: string;
4916};
4917type AiTextToSpeechOutput = Uint8Array | {
4918 audio: string;
4919};
4920declare abstract class BaseAiTextToSpeech {
4921 inputs: AiTextToSpeechInput;
4922 postProcessedOutputs: AiTextToSpeechOutput;
4923}
4924type AiTextToImageInput = {
4925 prompt: string;
4926 negative_prompt?: string;
4927 height?: number;
4928 width?: number;
4929 image?: number[];
4930 image_b64?: string;
4931 mask?: number[];
4932 num_steps?: number;
4933 strength?: number;
4934 guidance?: number;
4935 seed?: number;
4936};
4937type AiTextToImageOutput = ReadableStream<Uint8Array>;
4938declare abstract class BaseAiTextToImage {
4939 inputs: AiTextToImageInput;
4940 postProcessedOutputs: AiTextToImageOutput;
4941}
4942type AiTranslationInput = {
4943 text: string;
4944 target_lang: string;
4945 source_lang?: string;
4946};
4947type AiTranslationOutput = {
4948 translated_text?: string;
4949};
4950declare abstract class BaseAiTranslation {
4951 inputs: AiTranslationInput;
4952 postProcessedOutputs: AiTranslationOutput;
4953}
4954/**
4955 * Workers AI support for OpenAI's Chat Completions API
4956 */
4957type ChatCompletionContentPartText = {
4958 type: "text";
4959 text: string;
4960};
4961type ChatCompletionContentPartImage = {
4962 type: "image_url";
4963 image_url: {
4964 url: string;
4965 detail?: "auto" | "low" | "high";
4966 };
4967};
4968type ChatCompletionContentPartInputAudio = {
4969 type: "input_audio";
4970 input_audio: {
4971 /** Base64 encoded audio data. */
4972 data: string;
4973 format: "wav" | "mp3";
4974 };
4975};
4976type ChatCompletionContentPartFile = {
4977 type: "file";
4978 file: {
4979 /** Base64 encoded file data. */
4980 file_data?: string;
4981 /** The ID of an uploaded file. */
4982 file_id?: string;
4983 filename?: string;
4984 };
4985};
4986type ChatCompletionContentPartRefusal = {
4987 type: "refusal";
4988 refusal: string;
4989};
4990type ChatCompletionContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage | ChatCompletionContentPartInputAudio | ChatCompletionContentPartFile;
4991type FunctionDefinition = {
4992 name: string;
4993 description?: string;
4994 parameters?: Record<string, unknown>;
4995 strict?: boolean | null;
4996};
4997type ChatCompletionFunctionTool = {
4998 type: "function";
4999 function: FunctionDefinition;
5000};
5001type ChatCompletionCustomToolGrammarFormat = {
5002 type: "grammar";
5003 grammar: {
5004 definition: string;
5005 syntax: "lark" | "regex";
5006 };
5007};
5008type ChatCompletionCustomToolTextFormat = {
5009 type: "text";
5010};
5011type ChatCompletionCustomToolFormat = ChatCompletionCustomToolTextFormat | ChatCompletionCustomToolGrammarFormat;
5012type ChatCompletionCustomTool = {
5013 type: "custom";
5014 custom: {
5015 name: string;
5016 description?: string;
5017 format?: ChatCompletionCustomToolFormat;
5018 };
5019};
5020type ChatCompletionTool = ChatCompletionFunctionTool | ChatCompletionCustomTool;
5021type ChatCompletionMessageFunctionToolCall = {
5022 id: string;
5023 type: "function";
5024 function: {
5025 name: string;
5026 /** JSON-encoded arguments string. */
5027 arguments: string;
5028 };
5029};
5030type ChatCompletionMessageCustomToolCall = {
5031 id: string;
5032 type: "custom";
5033 custom: {
5034 name: string;
5035 input: string;
5036 };
5037};
5038type ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall;
5039type ChatCompletionToolChoiceFunction = {
5040 type: "function";
5041 function: {
5042 name: string;
5043 };
5044};
5045type ChatCompletionToolChoiceCustom = {
5046 type: "custom";
5047 custom: {
5048 name: string;
5049 };
5050};
5051type ChatCompletionToolChoiceAllowedTools = {
5052 type: "allowed_tools";
5053 allowed_tools: {
5054 mode: "auto" | "required";
5055 tools: Array<Record<string, unknown>>;
5056 };
5057};
5058type ChatCompletionToolChoiceOption = "none" | "auto" | "required" | ChatCompletionToolChoiceFunction | ChatCompletionToolChoiceCustom | ChatCompletionToolChoiceAllowedTools;
5059type DeveloperMessage = {
5060 role: "developer";
5061 content: string | Array<{
5062 type: "text";
5063 text: string;
5064 }>;
5065 name?: string;
5066};
5067type SystemMessage = {
5068 role: "system";
5069 content: string | Array<{
5070 type: "text";
5071 text: string;
5072 }>;
5073 name?: string;
5074};
5075/**
5076 * Permissive merged content part used inside UserMessage arrays.
5077 *
5078 * Cabidela has a limitation where anyOf/oneOf with enum-based discrimination
5079 * inside nested array items does not correctly match different branches for
5080 * different array elements, so the schema uses a single merged object.
5081 */
5082type UserMessageContentPart = {
5083 type: "text" | "image_url" | "input_audio" | "file";
5084 text?: string;
5085 image_url?: {
5086 url?: string;
5087 detail?: "auto" | "low" | "high";
5088 };
5089 input_audio?: {
5090 data?: string;
5091 format?: "wav" | "mp3";
5092 };
5093 file?: {
5094 file_data?: string;
5095 file_id?: string;
5096 filename?: string;
5097 };
5098};
5099type UserMessage = {
5100 role: "user";
5101 content: string | Array<UserMessageContentPart>;
5102 name?: string;
5103};
5104type AssistantMessageContentPart = {
5105 type: "text" | "refusal";
5106 text?: string;
5107 refusal?: string;
5108};
5109type AssistantMessage = {
5110 role: "assistant";
5111 content?: string | null | Array<AssistantMessageContentPart>;
5112 refusal?: string | null;
5113 name?: string;
5114 audio?: {
5115 id: string;
5116 };
5117 tool_calls?: Array<ChatCompletionMessageToolCall>;
5118 function_call?: {
5119 name: string;
5120 arguments: string;
5121 };
5122};
5123type ToolMessage = {
5124 role: "tool";
5125 content: string | Array<{
5126 type: "text";
5127 text: string;
5128 }>;
5129 tool_call_id: string;
5130};
5131type FunctionMessage = {
5132 role: "function";
5133 content: string;
5134 name: string;
5135};
5136type ChatCompletionMessageParam = DeveloperMessage | SystemMessage | UserMessage | AssistantMessage | ToolMessage | FunctionMessage;
5137type ChatCompletionsResponseFormatText = {
5138 type: "text";
5139};
5140type ChatCompletionsResponseFormatJSONObject = {
5141 type: "json_object";
5142};
5143type ResponseFormatJSONSchema = {
5144 type: "json_schema";
5145 json_schema: {
5146 name: string;
5147 description?: string;
5148 schema?: Record<string, unknown>;
5149 strict?: boolean | null;
5150 };
5151};
5152type ResponseFormat = ChatCompletionsResponseFormatText | ChatCompletionsResponseFormatJSONObject | ResponseFormatJSONSchema;
5153type ChatCompletionsStreamOptions = {
5154 include_usage?: boolean;
5155 include_obfuscation?: boolean;
5156};
5157type PredictionContent = {
5158 type: "content";
5159 content: string | Array<{
5160 type: "text";
5161 text: string;
5162 }>;
5163};
5164type AudioParams = {
5165 voice: string | {
5166 id: string;
5167 };
5168 format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16";
5169};
5170type WebSearchUserLocation = {
5171 type: "approximate";
5172 approximate: {
5173 city?: string;
5174 country?: string;
5175 region?: string;
5176 timezone?: string;
5177 };
5178};
5179type WebSearchOptions = {
5180 search_context_size?: "low" | "medium" | "high";
5181 user_location?: WebSearchUserLocation;
5182};
5183type ChatTemplateKwargs = {
5184 /** Whether to enable reasoning, enabled by default. */
5185 enable_thinking?: boolean;
5186 /** If false, preserves reasoning context between turns. */
5187 clear_thinking?: boolean;
5188};
5189/** Shared optional properties used by both Prompt and Messages input branches. */
5190type ChatCompletionsCommonOptions = {
5191 model?: string;
5192 audio?: AudioParams;
5193 frequency_penalty?: number | null;
5194 logit_bias?: Record<string, unknown> | null;
5195 logprobs?: boolean | null;
5196 top_logprobs?: number | null;
5197 max_tokens?: number | null;
5198 max_completion_tokens?: number | null;
5199 metadata?: Record<string, unknown> | null;
5200 modalities?: Array<"text" | "audio"> | null;
5201 n?: number | null;
5202 parallel_tool_calls?: boolean;
5203 prediction?: PredictionContent;
5204 presence_penalty?: number | null;
5205 reasoning_effort?: "low" | "medium" | "high" | null;
5206 chat_template_kwargs?: ChatTemplateKwargs;
5207 response_format?: ResponseFormat;
5208 seed?: number | null;
5209 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;
5210 stop?: string | Array<string> | null;
5211 store?: boolean | null;
5212 stream?: boolean | null;
5213 stream_options?: ChatCompletionsStreamOptions;
5214 temperature?: number | null;
5215 tool_choice?: ChatCompletionToolChoiceOption;
5216 tools?: Array<ChatCompletionTool>;
5217 top_p?: number | null;
5218 user?: string;
5219 web_search_options?: WebSearchOptions;
5220 function_call?: "none" | "auto" | {
5221 name: string;
5222 };
5223 functions?: Array<FunctionDefinition>;
5224};
5225type PromptTokensDetails = {
5226 cached_tokens?: number;
5227 audio_tokens?: number;
5228};
5229type CompletionTokensDetails = {
5230 reasoning_tokens?: number;
5231 audio_tokens?: number;
5232 accepted_prediction_tokens?: number;
5233 rejected_prediction_tokens?: number;
5234};
5235type CompletionUsage = {
5236 prompt_tokens: number;
5237 completion_tokens: number;
5238 total_tokens: number;
5239 prompt_tokens_details?: PromptTokensDetails;
5240 completion_tokens_details?: CompletionTokensDetails;
5241};
5242type ChatCompletionTopLogprob = {
5243 token: string;
5244 logprob: number;
5245 bytes: Array<number> | null;
5246};
5247type ChatCompletionTokenLogprob = {
5248 token: string;
5249 logprob: number;
5250 bytes: Array<number> | null;
5251 top_logprobs: Array<ChatCompletionTopLogprob>;
5252};
5253type ChatCompletionAudio = {
5254 id: string;
5255 /** Base64 encoded audio bytes. */
5256 data: string;
5257 expires_at: number;
5258 transcript: string;
5259};
5260type ChatCompletionUrlCitation = {
5261 type: "url_citation";
5262 url_citation: {
5263 url: string;
5264 title: string;
5265 start_index: number;
5266 end_index: number;
5267 };
5268};
5269type ChatCompletionResponseMessage = {
5270 role: "assistant";
5271 content: string | null;
5272 refusal: string | null;
5273 annotations?: Array<ChatCompletionUrlCitation>;
5274 audio?: ChatCompletionAudio;
5275 tool_calls?: Array<ChatCompletionMessageToolCall>;
5276 function_call?: {
5277 name: string;
5278 arguments: string;
5279 } | null;
5280};
5281type ChatCompletionLogprobs = {
5282 content: Array<ChatCompletionTokenLogprob> | null;
5283 refusal?: Array<ChatCompletionTokenLogprob> | null;
5284};
5285type ChatCompletionChoice = {
5286 index: number;
5287 message: ChatCompletionResponseMessage;
5288 finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call";
5289 logprobs: ChatCompletionLogprobs | null;
5290};
5291type ChatCompletionsMessagesInput = {
5292 messages: Array<ChatCompletionMessageParam>;
5293} & ChatCompletionsCommonOptions;
5294type ChatCompletionsOutput = {
5295 id: string;
5296 object: string;
5297 created: number;
5298 model: string;
5299 choices: Array<ChatCompletionChoice>;
5300 usage?: CompletionUsage;
5301 system_fingerprint?: string | null;
5302 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;
5303};
5304/**
5305 * Workers AI support for OpenAI's Responses API
5306 * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts
5307 *
5308 * It's a stripped down version from its source.
5309 * It currently supports basic function calling, json mode and accepts images as input.
5310 *
5311 * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools.
5312 * We plan to add those incrementally as model + platform capabilities evolve.
5313 */
5314type ResponsesInput = {
5315 background?: boolean | null;
5316 conversation?: string | ResponseConversationParam | null;
5317 include?: Array<ResponseIncludable> | null;
5318 input?: string | ResponseInput;
5319 instructions?: string | null;
5320 max_output_tokens?: number | null;
5321 parallel_tool_calls?: boolean | null;
5322 previous_response_id?: string | null;
5323 prompt_cache_key?: string;
5324 reasoning?: Reasoning | null;
5325 safety_identifier?: string;
5326 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;
5327 stream?: boolean | null;
5328 stream_options?: StreamOptions | null;
5329 temperature?: number | null;
5330 text?: ResponseTextConfig;
5331 tool_choice?: ToolChoiceOptions | ToolChoiceFunction;
5332 tools?: Array<Tool>;
5333 top_p?: number | null;
5334 truncation?: "auto" | "disabled" | null;
5335};
5336type ResponsesOutput = {
5337 id?: string;
5338 created_at?: number;
5339 output_text?: string;
5340 error?: ResponseError | null;
5341 incomplete_details?: ResponseIncompleteDetails | null;
5342 instructions?: string | Array<ResponseInputItem> | null;
5343 object?: "response";
5344 output?: Array<ResponseOutputItem>;
5345 parallel_tool_calls?: boolean;
5346 temperature?: number | null;
5347 tool_choice?: ToolChoiceOptions | ToolChoiceFunction;
5348 tools?: Array<Tool>;
5349 top_p?: number | null;
5350 max_output_tokens?: number | null;
5351 previous_response_id?: string | null;
5352 prompt?: ResponsePrompt | null;
5353 reasoning?: Reasoning | null;
5354 safety_identifier?: string;
5355 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;
5356 status?: ResponseStatus;
5357 text?: ResponseTextConfig;
5358 truncation?: "auto" | "disabled" | null;
5359 usage?: ResponseUsage;
5360};
5361type EasyInputMessage = {
5362 content: string | ResponseInputMessageContentList;
5363 role: "user" | "assistant" | "system" | "developer";
5364 type?: "message";
5365};
5366type ResponsesFunctionTool = {
5367 name: string;
5368 parameters: {
5369 [key: string]: unknown;
5370 } | null;
5371 strict: boolean | null;
5372 type: "function";
5373 description?: string | null;
5374};
5375type ResponseIncompleteDetails = {
5376 reason?: "max_output_tokens" | "content_filter";
5377};
5378type ResponsePrompt = {
5379 id: string;
5380 variables?: {
5381 [key: string]: string | ResponseInputText | ResponseInputImage;
5382 } | null;
5383 version?: string | null;
5384};
5385type Reasoning = {
5386 effort?: ReasoningEffort | null;
5387 generate_summary?: "auto" | "concise" | "detailed" | null;
5388 summary?: "auto" | "concise" | "detailed" | null;
5389};
5390type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText;
5391type ResponseContentReasoningText = {
5392 text: string;
5393 type: "reasoning_text";
5394};
5395type ResponseConversationParam = {
5396 id: string;
5397};
5398type ResponseCreatedEvent = {
5399 response: Response;
5400 sequence_number: number;
5401 type: "response.created";
5402};
5403type ResponseCustomToolCallOutput = {
5404 call_id: string;
5405 output: string | Array<ResponseInputText | ResponseInputImage>;
5406 type: "custom_tool_call_output";
5407 id?: string;
5408};
5409type ResponseError = {
5410 code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found";
5411 message: string;
5412};
5413type ResponseErrorEvent = {
5414 code: string | null;
5415 message: string;
5416 param: string | null;
5417 sequence_number: number;
5418 type: "error";
5419};
5420type ResponseFailedEvent = {
5421 response: Response;
5422 sequence_number: number;
5423 type: "response.failed";
5424};
5425type ResponseFormatText = {
5426 type: "text";
5427};
5428type ResponseFormatJSONObject = {
5429 type: "json_object";
5430};
5431type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject;
5432type ResponseFormatTextJSONSchemaConfig = {
5433 name: string;
5434 schema: {
5435 [key: string]: unknown;
5436 };
5437 type: "json_schema";
5438 description?: string;
5439 strict?: boolean | null;
5440};
5441type ResponseFunctionCallArgumentsDeltaEvent = {
5442 delta: string;
5443 item_id: string;
5444 output_index: number;
5445 sequence_number: number;
5446 type: "response.function_call_arguments.delta";
5447};
5448type ResponseFunctionCallArgumentsDoneEvent = {
5449 arguments: string;
5450 item_id: string;
5451 name: string;
5452 output_index: number;
5453 sequence_number: number;
5454 type: "response.function_call_arguments.done";
5455};
5456type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent;
5457type ResponseFunctionCallOutputItemList = Array<ResponseFunctionCallOutputItem>;
5458type ResponseFunctionToolCall = {
5459 arguments: string;
5460 call_id: string;
5461 name: string;
5462 type: "function_call";
5463 id?: string;
5464 status?: "in_progress" | "completed" | "incomplete";
5465};
5466interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall {
5467 id: string;
5468}
5469type ResponseFunctionToolCallOutputItem = {
5470 id: string;
5471 call_id: string;
5472 output: string | Array<ResponseInputText | ResponseInputImage>;
5473 type: "function_call_output";
5474 status?: "in_progress" | "completed" | "incomplete";
5475};
5476type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs";
5477type ResponseIncompleteEvent = {
5478 response: Response;
5479 sequence_number: number;
5480 type: "response.incomplete";
5481};
5482type ResponseInput = Array<ResponseInputItem>;
5483type ResponseInputContent = ResponseInputText | ResponseInputImage;
5484type ResponseInputImage = {
5485 detail: "low" | "high" | "auto";
5486 type: "input_image";
5487 /**
5488 * Base64 encoded image
5489 */
5490 image_url?: string | null;
5491};
5492type ResponseInputImageContent = {
5493 type: "input_image";
5494 detail?: "low" | "high" | "auto" | null;
5495 /**
5496 * Base64 encoded image
5497 */
5498 image_url?: string | null;
5499};
5500type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem;
5501type ResponseInputItemFunctionCallOutput = {
5502 call_id: string;
5503 output: string | ResponseFunctionCallOutputItemList;
5504 type: "function_call_output";
5505 id?: string | null;
5506 status?: "in_progress" | "completed" | "incomplete" | null;
5507};
5508type ResponseInputItemMessage = {
5509 content: ResponseInputMessageContentList;
5510 role: "user" | "system" | "developer";
5511 status?: "in_progress" | "completed" | "incomplete";
5512 type?: "message";
5513};
5514type ResponseInputMessageContentList = Array<ResponseInputContent>;
5515type ResponseInputMessageItem = {
5516 id: string;
5517 content: ResponseInputMessageContentList;
5518 role: "user" | "system" | "developer";
5519 status?: "in_progress" | "completed" | "incomplete";
5520 type?: "message";
5521};
5522type ResponseInputText = {
5523 text: string;
5524 type: "input_text";
5525};
5526type ResponseInputTextContent = {
5527 text: string;
5528 type: "input_text";
5529};
5530type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem;
5531type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem;
5532type ResponseOutputItemAddedEvent = {
5533 item: ResponseOutputItem;
5534 output_index: number;
5535 sequence_number: number;
5536 type: "response.output_item.added";
5537};
5538type ResponseOutputItemDoneEvent = {
5539 item: ResponseOutputItem;
5540 output_index: number;
5541 sequence_number: number;
5542 type: "response.output_item.done";
5543};
5544type ResponseOutputMessage = {
5545 id: string;
5546 content: Array<ResponseOutputText | ResponseOutputRefusal>;
5547 role: "assistant";
5548 status: "in_progress" | "completed" | "incomplete";
5549 type: "message";
5550};
5551type ResponseOutputRefusal = {
5552 refusal: string;
5553 type: "refusal";
5554};
5555type ResponseOutputText = {
5556 text: string;
5557 type: "output_text";
5558 logprobs?: Array<Logprob>;
5559};
5560type ResponseReasoningItem = {
5561 id: string;
5562 summary: Array<ResponseReasoningSummaryItem>;
5563 type: "reasoning";
5564 content?: Array<ResponseReasoningContentItem>;
5565 encrypted_content?: string | null;
5566 status?: "in_progress" | "completed" | "incomplete";
5567};
5568type ResponseReasoningSummaryItem = {
5569 text: string;
5570 type: "summary_text";
5571};
5572type ResponseReasoningContentItem = {
5573 text: string;
5574 type: "reasoning_text";
5575};
5576type ResponseReasoningTextDeltaEvent = {
5577 content_index: number;
5578 delta: string;
5579 item_id: string;
5580 output_index: number;
5581 sequence_number: number;
5582 type: "response.reasoning_text.delta";
5583};
5584type ResponseReasoningTextDoneEvent = {
5585 content_index: number;
5586 item_id: string;
5587 output_index: number;
5588 sequence_number: number;
5589 text: string;
5590 type: "response.reasoning_text.done";
5591};
5592type ResponseRefusalDeltaEvent = {
5593 content_index: number;
5594 delta: string;
5595 item_id: string;
5596 output_index: number;
5597 sequence_number: number;
5598 type: "response.refusal.delta";
5599};
5600type ResponseRefusalDoneEvent = {
5601 content_index: number;
5602 item_id: string;
5603 output_index: number;
5604 refusal: string;
5605 sequence_number: number;
5606 type: "response.refusal.done";
5607};
5608type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete";
5609type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent;
5610type ResponseCompletedEvent = {
5611 response: Response;
5612 sequence_number: number;
5613 type: "response.completed";
5614};
5615type ResponseTextConfig = {
5616 format?: ResponseFormatTextConfig;
5617 verbosity?: "low" | "medium" | "high" | null;
5618};
5619type ResponseTextDeltaEvent = {
5620 content_index: number;
5621 delta: string;
5622 item_id: string;
5623 logprobs: Array<Logprob>;
5624 output_index: number;
5625 sequence_number: number;
5626 type: "response.output_text.delta";
5627};
5628type ResponseTextDoneEvent = {
5629 content_index: number;
5630 item_id: string;
5631 logprobs: Array<Logprob>;
5632 output_index: number;
5633 sequence_number: number;
5634 text: string;
5635 type: "response.output_text.done";
5636};
5637type Logprob = {
5638 token: string;
5639 logprob: number;
5640 top_logprobs?: Array<TopLogprob>;
5641};
5642type TopLogprob = {
5643 token?: string;
5644 logprob?: number;
5645};
5646type ResponseUsage = {
5647 input_tokens: number;
5648 output_tokens: number;
5649 total_tokens: number;
5650};
5651type Tool = ResponsesFunctionTool;
5652type ToolChoiceFunction = {
5653 name: string;
5654 type: "function";
5655};
5656type ToolChoiceOptions = "none";
5657type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null;
5658type StreamOptions = {
5659 include_obfuscation?: boolean;
5660};
5661/** Marks keys from T that aren't in U as optional never */
5662type Without<T, U> = {
5663 [P in Exclude<keyof T, keyof U>]?: never;
5664};
5665/** Either T or U, but not both (mutually exclusive) */
5666type XOR<T, U> = (T & Without<U, T>) | (U & Without<T, U>);
5667type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = {
5668 text: string | string[];
5669 /**
5670 * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.
5671 */
5672 pooling?: "mean" | "cls";
5673} | {
5674 /**
5675 * Batch of the embeddings requests to run using async-queue
5676 */
5677 requests: {
5678 text: string | string[];
5679 /**
5680 * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.
5681 */
5682 pooling?: "mean" | "cls";
5683 }[];
5684};
5685type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = {
5686 shape?: number[];
5687 /**
5688 * Embeddings of the requested text values
5689 */
5690 data?: number[][];
5691 /**
5692 * The pooling method used in the embedding process.
5693 */
5694 pooling?: "mean" | "cls";
5695} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse;
5696interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse {
5697 /**
5698 * The async request id that can be used to obtain the results.
5699 */
5700 request_id?: string;
5701}
5702declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 {
5703 inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input;
5704 postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output;
5705}
5706type Ai_Cf_Openai_Whisper_Input = string | {
5707 /**
5708 * An array of integers that represent the audio data constrained to 8-bit unsigned integer values
5709 */
5710 audio: number[];
5711};
5712interface Ai_Cf_Openai_Whisper_Output {
5713 /**
5714 * The transcription
5715 */
5716 text: string;
5717 word_count?: number;
5718 words?: {
5719 word?: string;
5720 /**
5721 * The second this word begins in the recording
5722 */
5723 start?: number;
5724 /**
5725 * The ending second when the word completes
5726 */
5727 end?: number;
5728 }[];
5729 vtt?: string;
5730}
5731declare abstract class Base_Ai_Cf_Openai_Whisper {
5732 inputs: Ai_Cf_Openai_Whisper_Input;
5733 postProcessedOutputs: Ai_Cf_Openai_Whisper_Output;
5734}
5735type Ai_Cf_Meta_M2M100_1_2B_Input = {
5736 /**
5737 * The text to be translated
5738 */
5739 text: string;
5740 /**
5741 * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified
5742 */
5743 source_lang?: string;
5744 /**
5745 * The language code to translate the text into (e.g., 'es' for Spanish)
5746 */
5747 target_lang: string;
5748} | {
5749 /**
5750 * Batch of the embeddings requests to run using async-queue
5751 */
5752 requests: {
5753 /**
5754 * The text to be translated
5755 */
5756 text: string;
5757 /**
5758 * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified
5759 */
5760 source_lang?: string;
5761 /**
5762 * The language code to translate the text into (e.g., 'es' for Spanish)
5763 */
5764 target_lang: string;
5765 }[];
5766};
5767type Ai_Cf_Meta_M2M100_1_2B_Output = {
5768 /**
5769 * The translated text in the target language
5770 */
5771 translated_text?: string;
5772} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse;
5773interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse {
5774 /**
5775 * The async request id that can be used to obtain the results.
5776 */
5777 request_id?: string;
5778}
5779declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B {
5780 inputs: Ai_Cf_Meta_M2M100_1_2B_Input;
5781 postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output;
5782}
5783type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = {
5784 text: string | string[];
5785 /**
5786 * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.
5787 */
5788 pooling?: "mean" | "cls";
5789} | {
5790 /**
5791 * Batch of the embeddings requests to run using async-queue
5792 */
5793 requests: {
5794 text: string | string[];
5795 /**
5796 * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.
5797 */
5798 pooling?: "mean" | "cls";
5799 }[];
5800};
5801type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = {
5802 shape?: number[];
5803 /**
5804 * Embeddings of the requested text values
5805 */
5806 data?: number[][];
5807 /**
5808 * The pooling method used in the embedding process.
5809 */
5810 pooling?: "mean" | "cls";
5811} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse;
5812interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse {
5813 /**
5814 * The async request id that can be used to obtain the results.
5815 */
5816 request_id?: string;
5817}
5818declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 {
5819 inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input;
5820 postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output;
5821}
5822type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = {
5823 text: string | string[];
5824 /**
5825 * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.
5826 */
5827 pooling?: "mean" | "cls";
5828} | {
5829 /**
5830 * Batch of the embeddings requests to run using async-queue
5831 */
5832 requests: {
5833 text: string | string[];
5834 /**
5835 * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.
5836 */
5837 pooling?: "mean" | "cls";
5838 }[];
5839};
5840type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = {
5841 shape?: number[];
5842 /**
5843 * Embeddings of the requested text values
5844 */
5845 data?: number[][];
5846 /**
5847 * The pooling method used in the embedding process.
5848 */
5849 pooling?: "mean" | "cls";
5850} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse;
5851interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse {
5852 /**
5853 * The async request id that can be used to obtain the results.
5854 */
5855 request_id?: string;
5856}
5857declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 {
5858 inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input;
5859 postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output;
5860}
5861type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | {
5862 /**
5863 * The input text prompt for the model to generate a response.
5864 */
5865 prompt?: string;
5866 /**
5867 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
5868 */
5869 raw?: boolean;
5870 /**
5871 * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
5872 */
5873 top_p?: number;
5874 /**
5875 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
5876 */
5877 top_k?: number;
5878 /**
5879 * Random seed for reproducibility of the generation.
5880 */
5881 seed?: number;
5882 /**
5883 * Penalty for repeated tokens; higher values discourage repetition.
5884 */
5885 repetition_penalty?: number;
5886 /**
5887 * Decreases the likelihood of the model repeating the same lines verbatim.
5888 */
5889 frequency_penalty?: number;
5890 /**
5891 * Increases the likelihood of the model introducing new topics.
5892 */
5893 presence_penalty?: number;
5894 image: number[] | (string & NonNullable<unknown>);
5895 /**
5896 * The maximum number of tokens to generate in the response.
5897 */
5898 max_tokens?: number;
5899};
5900interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output {
5901 description?: string;
5902}
5903declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M {
5904 inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input;
5905 postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output;
5906}
5907type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | {
5908 /**
5909 * An array of integers that represent the audio data constrained to 8-bit unsigned integer values
5910 */
5911 audio: number[];
5912};
5913interface Ai_Cf_Openai_Whisper_Tiny_En_Output {
5914 /**
5915 * The transcription
5916 */
5917 text: string;
5918 word_count?: number;
5919 words?: {
5920 word?: string;
5921 /**
5922 * The second this word begins in the recording
5923 */
5924 start?: number;
5925 /**
5926 * The ending second when the word completes
5927 */
5928 end?: number;
5929 }[];
5930 vtt?: string;
5931}
5932declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En {
5933 inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input;
5934 postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output;
5935}
5936interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input {
5937 audio: string | {
5938 body?: object;
5939 contentType?: string;
5940 };
5941 /**
5942 * Supported tasks are 'translate' or 'transcribe'.
5943 */
5944 task?: string;
5945 /**
5946 * The language of the audio being transcribed or translated.
5947 */
5948 language?: string;
5949 /**
5950 * Preprocess the audio with a voice activity detection model.
5951 */
5952 vad_filter?: boolean;
5953 /**
5954 * A text prompt to help provide context to the model on the contents of the audio.
5955 */
5956 initial_prompt?: string;
5957 /**
5958 * The prefix appended to the beginning of the output of the transcription and can guide the transcription result.
5959 */
5960 prefix?: string;
5961 /**
5962 * The number of beams to use in beam search decoding. Higher values may improve accuracy at the cost of speed.
5963 */
5964 beam_size?: number;
5965 /**
5966 * Whether to condition on previous text during transcription. Setting to false may help prevent hallucination loops.
5967 */
5968 condition_on_previous_text?: boolean;
5969 /**
5970 * Threshold for detecting no-speech segments. Segments with no-speech probability above this value are skipped.
5971 */
5972 no_speech_threshold?: number;
5973 /**
5974 * Threshold for filtering out segments with high compression ratio, which often indicate repetitive or hallucinated text.
5975 */
5976 compression_ratio_threshold?: number;
5977 /**
5978 * Threshold for filtering out segments with low average log probability, indicating low confidence.
5979 */
5980 log_prob_threshold?: number;
5981 /**
5982 * Optional threshold (in seconds) to skip silent periods that may cause hallucinations.
5983 */
5984 hallucination_silence_threshold?: number;
5985}
5986interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output {
5987 transcription_info?: {
5988 /**
5989 * The language of the audio being transcribed or translated.
5990 */
5991 language?: string;
5992 /**
5993 * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1.
5994 */
5995 language_probability?: number;
5996 /**
5997 * The total duration of the original audio file, in seconds.
5998 */
5999 duration?: number;
6000 /**
6001 * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds.
6002 */
6003 duration_after_vad?: number;
6004 };
6005 /**
6006 * The complete transcription of the audio.
6007 */
6008 text: string;
6009 /**
6010 * The total number of words in the transcription.
6011 */
6012 word_count?: number;
6013 segments?: {
6014 /**
6015 * The starting time of the segment within the audio, in seconds.
6016 */
6017 start?: number;
6018 /**
6019 * The ending time of the segment within the audio, in seconds.
6020 */
6021 end?: number;
6022 /**
6023 * The transcription of the segment.
6024 */
6025 text?: string;
6026 /**
6027 * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs.
6028 */
6029 temperature?: number;
6030 /**
6031 * The average log probability of the predictions for the words in this segment, indicating overall confidence.
6032 */
6033 avg_logprob?: number;
6034 /**
6035 * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process.
6036 */
6037 compression_ratio?: number;
6038 /**
6039 * The probability that the segment contains no speech, represented as a decimal between 0 and 1.
6040 */
6041 no_speech_prob?: number;
6042 words?: {
6043 /**
6044 * The individual word transcribed from the audio.
6045 */
6046 word?: string;
6047 /**
6048 * The starting time of the word within the audio, in seconds.
6049 */
6050 start?: number;
6051 /**
6052 * The ending time of the word within the audio, in seconds.
6053 */
6054 end?: number;
6055 }[];
6056 }[];
6057 /**
6058 * The transcription in WebVTT format, which includes timing and text information for use in subtitles.
6059 */
6060 vtt?: string;
6061}
6062declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo {
6063 inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input;
6064 postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output;
6065}
6066type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | {
6067 /**
6068 * Batch of the embeddings requests to run using async-queue
6069 */
6070 requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[];
6071};
6072interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts {
6073 /**
6074 * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts
6075 */
6076 query?: string;
6077 /**
6078 * List of provided contexts. Note that the index in this array is important, as the response will refer to it.
6079 */
6080 contexts: {
6081 /**
6082 * One of the provided context content
6083 */
6084 text?: string;
6085 }[];
6086 /**
6087 * When provided with too long context should the model error out or truncate the context to fit?
6088 */
6089 truncate_inputs?: boolean;
6090}
6091interface Ai_Cf_Baai_Bge_M3_Input_Embedding {
6092 text: string | string[];
6093 /**
6094 * When provided with too long context should the model error out or truncate the context to fit?
6095 */
6096 truncate_inputs?: boolean;
6097}
6098interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 {
6099 /**
6100 * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts
6101 */
6102 query?: string;
6103 /**
6104 * List of provided contexts. Note that the index in this array is important, as the response will refer to it.
6105 */
6106 contexts: {
6107 /**
6108 * One of the provided context content
6109 */
6110 text?: string;
6111 }[];
6112 /**
6113 * When provided with too long context should the model error out or truncate the context to fit?
6114 */
6115 truncate_inputs?: boolean;
6116}
6117interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 {
6118 text: string | string[];
6119 /**
6120 * When provided with too long context should the model error out or truncate the context to fit?
6121 */
6122 truncate_inputs?: boolean;
6123}
6124type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Output_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Output_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse;
6125interface Ai_Cf_Baai_Bge_M3_Output_Query {
6126 response?: {
6127 /**
6128 * Index of the context in the request
6129 */
6130 id?: number;
6131 /**
6132 * Score of the context under the index.
6133 */
6134 score?: number;
6135 }[];
6136}
6137interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts {
6138 response?: number[][];
6139 shape?: number[];
6140 /**
6141 * The pooling method used in the embedding process.
6142 */
6143 pooling?: "mean" | "cls";
6144}
6145interface Ai_Cf_Baai_Bge_M3_Output_Embedding {
6146 shape?: number[];
6147 /**
6148 * Embeddings of the requested text values
6149 */
6150 data?: number[][];
6151 /**
6152 * The pooling method used in the embedding process.
6153 */
6154 pooling?: "mean" | "cls";
6155}
6156interface Ai_Cf_Baai_Bge_M3_AsyncResponse {
6157 /**
6158 * The async request id that can be used to obtain the results.
6159 */
6160 request_id?: string;
6161}
6162declare abstract class Base_Ai_Cf_Baai_Bge_M3 {
6163 inputs: Ai_Cf_Baai_Bge_M3_Input;
6164 postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output;
6165}
6166interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input {
6167 /**
6168 * A text description of the image you want to generate.
6169 */
6170 prompt: string;
6171 /**
6172 * The number of diffusion steps; higher values can improve quality but take longer.
6173 */
6174 steps?: number;
6175}
6176interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output {
6177 /**
6178 * The generated image in Base64 format.
6179 */
6180 image?: string;
6181}
6182declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell {
6183 inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input;
6184 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output;
6185}
6186type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages;
6187interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt {
6188 /**
6189 * The input text prompt for the model to generate a response.
6190 */
6191 prompt: string;
6192 image?: number[] | (string & NonNullable<unknown>);
6193 /**
6194 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
6195 */
6196 raw?: boolean;
6197 /**
6198 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6199 */
6200 stream?: boolean;
6201 /**
6202 * The maximum number of tokens to generate in the response.
6203 */
6204 max_tokens?: number;
6205 /**
6206 * Controls the randomness of the output; higher values produce more random results.
6207 */
6208 temperature?: number;
6209 /**
6210 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
6211 */
6212 top_p?: number;
6213 /**
6214 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
6215 */
6216 top_k?: number;
6217 /**
6218 * Random seed for reproducibility of the generation.
6219 */
6220 seed?: number;
6221 /**
6222 * Penalty for repeated tokens; higher values discourage repetition.
6223 */
6224 repetition_penalty?: number;
6225 /**
6226 * Decreases the likelihood of the model repeating the same lines verbatim.
6227 */
6228 frequency_penalty?: number;
6229 /**
6230 * Increases the likelihood of the model introducing new topics.
6231 */
6232 presence_penalty?: number;
6233 /**
6234 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
6235 */
6236 lora?: string;
6237}
6238interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages {
6239 /**
6240 * An array of message objects representing the conversation history.
6241 */
6242 messages: {
6243 /**
6244 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
6245 */
6246 role?: string;
6247 /**
6248 * The tool call id. If you don't know what to put here you can fall back to 000000001
6249 */
6250 tool_call_id?: string;
6251 content?: string | {
6252 /**
6253 * Type of the content provided
6254 */
6255 type?: string;
6256 text?: string;
6257 image_url?: {
6258 /**
6259 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
6260 */
6261 url?: string;
6262 };
6263 }[] | {
6264 /**
6265 * Type of the content provided
6266 */
6267 type?: string;
6268 text?: string;
6269 image_url?: {
6270 /**
6271 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
6272 */
6273 url?: string;
6274 };
6275 };
6276 }[];
6277 image?: number[] | (string & NonNullable<unknown>);
6278 functions?: {
6279 name: string;
6280 code: string;
6281 }[];
6282 /**
6283 * A list of tools available for the assistant to use.
6284 */
6285 tools?: ({
6286 /**
6287 * The name of the tool. More descriptive the better.
6288 */
6289 name: string;
6290 /**
6291 * A brief description of what the tool does.
6292 */
6293 description: string;
6294 /**
6295 * Schema defining the parameters accepted by the tool.
6296 */
6297 parameters: {
6298 /**
6299 * The type of the parameters object (usually 'object').
6300 */
6301 type: string;
6302 /**
6303 * List of required parameter names.
6304 */
6305 required?: string[];
6306 /**
6307 * Definitions of each parameter.
6308 */
6309 properties: {
6310 [k: string]: {
6311 /**
6312 * The data type of the parameter.
6313 */
6314 type: string;
6315 /**
6316 * A description of the expected parameter.
6317 */
6318 description: string;
6319 };
6320 };
6321 };
6322 } | {
6323 /**
6324 * Specifies the type of tool (e.g., 'function').
6325 */
6326 type: string;
6327 /**
6328 * Details of the function tool.
6329 */
6330 function: {
6331 /**
6332 * The name of the function.
6333 */
6334 name: string;
6335 /**
6336 * A brief description of what the function does.
6337 */
6338 description: string;
6339 /**
6340 * Schema defining the parameters accepted by the function.
6341 */
6342 parameters: {
6343 /**
6344 * The type of the parameters object (usually 'object').
6345 */
6346 type: string;
6347 /**
6348 * List of required parameter names.
6349 */
6350 required?: string[];
6351 /**
6352 * Definitions of each parameter.
6353 */
6354 properties: {
6355 [k: string]: {
6356 /**
6357 * The data type of the parameter.
6358 */
6359 type: string;
6360 /**
6361 * A description of the expected parameter.
6362 */
6363 description: string;
6364 };
6365 };
6366 };
6367 };
6368 })[];
6369 /**
6370 * If true, the response will be streamed back incrementally.
6371 */
6372 stream?: boolean;
6373 /**
6374 * The maximum number of tokens to generate in the response.
6375 */
6376 max_tokens?: number;
6377 /**
6378 * Controls the randomness of the output; higher values produce more random results.
6379 */
6380 temperature?: number;
6381 /**
6382 * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
6383 */
6384 top_p?: number;
6385 /**
6386 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
6387 */
6388 top_k?: number;
6389 /**
6390 * Random seed for reproducibility of the generation.
6391 */
6392 seed?: number;
6393 /**
6394 * Penalty for repeated tokens; higher values discourage repetition.
6395 */
6396 repetition_penalty?: number;
6397 /**
6398 * Decreases the likelihood of the model repeating the same lines verbatim.
6399 */
6400 frequency_penalty?: number;
6401 /**
6402 * Increases the likelihood of the model introducing new topics.
6403 */
6404 presence_penalty?: number;
6405}
6406type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = {
6407 /**
6408 * The generated text response from the model
6409 */
6410 response?: string;
6411 /**
6412 * An array of tool calls requests made during the response generation
6413 */
6414 tool_calls?: {
6415 /**
6416 * The arguments passed to be passed to the tool call request
6417 */
6418 arguments?: object;
6419 /**
6420 * The name of the tool to be called
6421 */
6422 name?: string;
6423 }[];
6424};
6425declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct {
6426 inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input;
6427 postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output;
6428}
6429type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch;
6430interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt {
6431 /**
6432 * The input text prompt for the model to generate a response.
6433 */
6434 prompt: string;
6435 /**
6436 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
6437 */
6438 lora?: string;
6439 response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode;
6440 /**
6441 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
6442 */
6443 raw?: boolean;
6444 /**
6445 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6446 */
6447 stream?: boolean;
6448 /**
6449 * The maximum number of tokens to generate in the response.
6450 */
6451 max_tokens?: number;
6452 /**
6453 * Controls the randomness of the output; higher values produce more random results.
6454 */
6455 temperature?: number;
6456 /**
6457 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
6458 */
6459 top_p?: number;
6460 /**
6461 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
6462 */
6463 top_k?: number;
6464 /**
6465 * Random seed for reproducibility of the generation.
6466 */
6467 seed?: number;
6468 /**
6469 * Penalty for repeated tokens; higher values discourage repetition.
6470 */
6471 repetition_penalty?: number;
6472 /**
6473 * Decreases the likelihood of the model repeating the same lines verbatim.
6474 */
6475 frequency_penalty?: number;
6476 /**
6477 * Increases the likelihood of the model introducing new topics.
6478 */
6479 presence_penalty?: number;
6480}
6481interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode {
6482 type?: "json_object" | "json_schema";
6483 json_schema?: unknown;
6484}
6485interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages {
6486 /**
6487 * An array of message objects representing the conversation history.
6488 */
6489 messages: {
6490 /**
6491 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
6492 */
6493 role: string;
6494 content: string | {
6495 /**
6496 * Type of the content (text)
6497 */
6498 type?: string;
6499 /**
6500 * Text content
6501 */
6502 text?: string;
6503 }[];
6504 }[];
6505 functions?: {
6506 name: string;
6507 code: string;
6508 }[];
6509 /**
6510 * A list of tools available for the assistant to use.
6511 */
6512 tools?: ({
6513 /**
6514 * The name of the tool. More descriptive the better.
6515 */
6516 name: string;
6517 /**
6518 * A brief description of what the tool does.
6519 */
6520 description: string;
6521 /**
6522 * Schema defining the parameters accepted by the tool.
6523 */
6524 parameters: {
6525 /**
6526 * The type of the parameters object (usually 'object').
6527 */
6528 type: string;
6529 /**
6530 * List of required parameter names.
6531 */
6532 required?: string[];
6533 /**
6534 * Definitions of each parameter.
6535 */
6536 properties: {
6537 [k: string]: {
6538 /**
6539 * The data type of the parameter.
6540 */
6541 type: string;
6542 /**
6543 * A description of the expected parameter.
6544 */
6545 description: string;
6546 };
6547 };
6548 };
6549 } | {
6550 /**
6551 * Specifies the type of tool (e.g., 'function').
6552 */
6553 type: string;
6554 /**
6555 * Details of the function tool.
6556 */
6557 function: {
6558 /**
6559 * The name of the function.
6560 */
6561 name: string;
6562 /**
6563 * A brief description of what the function does.
6564 */
6565 description: string;
6566 /**
6567 * Schema defining the parameters accepted by the function.
6568 */
6569 parameters: {
6570 /**
6571 * The type of the parameters object (usually 'object').
6572 */
6573 type: string;
6574 /**
6575 * List of required parameter names.
6576 */
6577 required?: string[];
6578 /**
6579 * Definitions of each parameter.
6580 */
6581 properties: {
6582 [k: string]: {
6583 /**
6584 * The data type of the parameter.
6585 */
6586 type: string;
6587 /**
6588 * A description of the expected parameter.
6589 */
6590 description: string;
6591 };
6592 };
6593 };
6594 };
6595 })[];
6596 response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1;
6597 /**
6598 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
6599 */
6600 raw?: boolean;
6601 /**
6602 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6603 */
6604 stream?: boolean;
6605 /**
6606 * The maximum number of tokens to generate in the response.
6607 */
6608 max_tokens?: number;
6609 /**
6610 * Controls the randomness of the output; higher values produce more random results.
6611 */
6612 temperature?: number;
6613 /**
6614 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
6615 */
6616 top_p?: number;
6617 /**
6618 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
6619 */
6620 top_k?: number;
6621 /**
6622 * Random seed for reproducibility of the generation.
6623 */
6624 seed?: number;
6625 /**
6626 * Penalty for repeated tokens; higher values discourage repetition.
6627 */
6628 repetition_penalty?: number;
6629 /**
6630 * Decreases the likelihood of the model repeating the same lines verbatim.
6631 */
6632 frequency_penalty?: number;
6633 /**
6634 * Increases the likelihood of the model introducing new topics.
6635 */
6636 presence_penalty?: number;
6637}
6638interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 {
6639 type?: "json_object" | "json_schema";
6640 json_schema?: unknown;
6641}
6642interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch {
6643 requests?: {
6644 /**
6645 * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique.
6646 */
6647 external_reference?: string;
6648 /**
6649 * Prompt for the text generation model
6650 */
6651 prompt?: string;
6652 /**
6653 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6654 */
6655 stream?: boolean;
6656 /**
6657 * The maximum number of tokens to generate in the response.
6658 */
6659 max_tokens?: number;
6660 /**
6661 * Controls the randomness of the output; higher values produce more random results.
6662 */
6663 temperature?: number;
6664 /**
6665 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
6666 */
6667 top_p?: number;
6668 /**
6669 * Random seed for reproducibility of the generation.
6670 */
6671 seed?: number;
6672 /**
6673 * Penalty for repeated tokens; higher values discourage repetition.
6674 */
6675 repetition_penalty?: number;
6676 /**
6677 * Decreases the likelihood of the model repeating the same lines verbatim.
6678 */
6679 frequency_penalty?: number;
6680 /**
6681 * Increases the likelihood of the model introducing new topics.
6682 */
6683 presence_penalty?: number;
6684 response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2;
6685 }[];
6686}
6687interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 {
6688 type?: "json_object" | "json_schema";
6689 json_schema?: unknown;
6690}
6691type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = {
6692 /**
6693 * The generated text response from the model
6694 */
6695 response: string;
6696 /**
6697 * Usage statistics for the inference request
6698 */
6699 usage?: {
6700 /**
6701 * Total number of tokens in input
6702 */
6703 prompt_tokens?: number;
6704 /**
6705 * Total number of tokens in output
6706 */
6707 completion_tokens?: number;
6708 /**
6709 * Total number of input and output tokens
6710 */
6711 total_tokens?: number;
6712 };
6713 /**
6714 * An array of tool calls requests made during the response generation
6715 */
6716 tool_calls?: {
6717 /**
6718 * The arguments passed to be passed to the tool call request
6719 */
6720 arguments?: object;
6721 /**
6722 * The name of the tool to be called
6723 */
6724 name?: string;
6725 }[];
6726} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse;
6727interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse {
6728 /**
6729 * The async request id that can be used to obtain the results.
6730 */
6731 request_id?: string;
6732}
6733declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast {
6734 inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input;
6735 postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output;
6736}
6737interface Ai_Cf_Meta_Llama_Guard_3_8B_Input {
6738 /**
6739 * An array of message objects representing the conversation history.
6740 */
6741 messages: {
6742 /**
6743 * The role of the message sender must alternate between 'user' and 'assistant'.
6744 */
6745 role: "user" | "assistant";
6746 /**
6747 * The content of the message as a string.
6748 */
6749 content: string;
6750 }[];
6751 /**
6752 * The maximum number of tokens to generate in the response.
6753 */
6754 max_tokens?: number;
6755 /**
6756 * Controls the randomness of the output; higher values produce more random results.
6757 */
6758 temperature?: number;
6759 /**
6760 * Dictate the output format of the generated response.
6761 */
6762 response_format?: {
6763 /**
6764 * Set to json_object to process and output generated text as JSON.
6765 */
6766 type?: string;
6767 };
6768}
6769interface Ai_Cf_Meta_Llama_Guard_3_8B_Output {
6770 response?: string | {
6771 /**
6772 * Whether the conversation is safe or not.
6773 */
6774 safe?: boolean;
6775 /**
6776 * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe.
6777 */
6778 categories?: string[];
6779 };
6780 /**
6781 * Usage statistics for the inference request
6782 */
6783 usage?: {
6784 /**
6785 * Total number of tokens in input
6786 */
6787 prompt_tokens?: number;
6788 /**
6789 * Total number of tokens in output
6790 */
6791 completion_tokens?: number;
6792 /**
6793 * Total number of input and output tokens
6794 */
6795 total_tokens?: number;
6796 };
6797}
6798declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B {
6799 inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input;
6800 postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output;
6801}
6802interface Ai_Cf_Baai_Bge_Reranker_Base_Input {
6803 /**
6804 * A query you wish to perform against the provided contexts.
6805 */
6806 /**
6807 * Number of returned results starting with the best score.
6808 */
6809 top_k?: number;
6810 /**
6811 * List of provided contexts. Note that the index in this array is important, as the response will refer to it.
6812 */
6813 contexts: {
6814 /**
6815 * One of the provided context content
6816 */
6817 text?: string;
6818 }[];
6819}
6820interface Ai_Cf_Baai_Bge_Reranker_Base_Output {
6821 response?: {
6822 /**
6823 * Index of the context in the request
6824 */
6825 id?: number;
6826 /**
6827 * Score of the context under the index.
6828 */
6829 score?: number;
6830 }[];
6831}
6832declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base {
6833 inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input;
6834 postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output;
6835}
6836type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages;
6837interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt {
6838 /**
6839 * The input text prompt for the model to generate a response.
6840 */
6841 prompt: string;
6842 /**
6843 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
6844 */
6845 lora?: string;
6846 response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode;
6847 /**
6848 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
6849 */
6850 raw?: boolean;
6851 /**
6852 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6853 */
6854 stream?: boolean;
6855 /**
6856 * The maximum number of tokens to generate in the response.
6857 */
6858 max_tokens?: number;
6859 /**
6860 * Controls the randomness of the output; higher values produce more random results.
6861 */
6862 temperature?: number;
6863 /**
6864 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
6865 */
6866 top_p?: number;
6867 /**
6868 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
6869 */
6870 top_k?: number;
6871 /**
6872 * Random seed for reproducibility of the generation.
6873 */
6874 seed?: number;
6875 /**
6876 * Penalty for repeated tokens; higher values discourage repetition.
6877 */
6878 repetition_penalty?: number;
6879 /**
6880 * Decreases the likelihood of the model repeating the same lines verbatim.
6881 */
6882 frequency_penalty?: number;
6883 /**
6884 * Increases the likelihood of the model introducing new topics.
6885 */
6886 presence_penalty?: number;
6887}
6888interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode {
6889 type?: "json_object" | "json_schema";
6890 json_schema?: unknown;
6891}
6892interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages {
6893 /**
6894 * An array of message objects representing the conversation history.
6895 */
6896 messages: {
6897 /**
6898 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
6899 */
6900 role: string;
6901 /**
6902 * The content of the message as a string.
6903 */
6904 content: string;
6905 }[];
6906 functions?: {
6907 name: string;
6908 code: string;
6909 }[];
6910 /**
6911 * A list of tools available for the assistant to use.
6912 */
6913 tools?: ({
6914 /**
6915 * The name of the tool. More descriptive the better.
6916 */
6917 name: string;
6918 /**
6919 * A brief description of what the tool does.
6920 */
6921 description: string;
6922 /**
6923 * Schema defining the parameters accepted by the tool.
6924 */
6925 parameters: {
6926 /**
6927 * The type of the parameters object (usually 'object').
6928 */
6929 type: string;
6930 /**
6931 * List of required parameter names.
6932 */
6933 required?: string[];
6934 /**
6935 * Definitions of each parameter.
6936 */
6937 properties: {
6938 [k: string]: {
6939 /**
6940 * The data type of the parameter.
6941 */
6942 type: string;
6943 /**
6944 * A description of the expected parameter.
6945 */
6946 description: string;
6947 };
6948 };
6949 };
6950 } | {
6951 /**
6952 * Specifies the type of tool (e.g., 'function').
6953 */
6954 type: string;
6955 /**
6956 * Details of the function tool.
6957 */
6958 function: {
6959 /**
6960 * The name of the function.
6961 */
6962 name: string;
6963 /**
6964 * A brief description of what the function does.
6965 */
6966 description: string;
6967 /**
6968 * Schema defining the parameters accepted by the function.
6969 */
6970 parameters: {
6971 /**
6972 * The type of the parameters object (usually 'object').
6973 */
6974 type: string;
6975 /**
6976 * List of required parameter names.
6977 */
6978 required?: string[];
6979 /**
6980 * Definitions of each parameter.
6981 */
6982 properties: {
6983 [k: string]: {
6984 /**
6985 * The data type of the parameter.
6986 */
6987 type: string;
6988 /**
6989 * A description of the expected parameter.
6990 */
6991 description: string;
6992 };
6993 };
6994 };
6995 };
6996 })[];
6997 response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1;
6998 /**
6999 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7000 */
7001 raw?: boolean;
7002 /**
7003 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7004 */
7005 stream?: boolean;
7006 /**
7007 * The maximum number of tokens to generate in the response.
7008 */
7009 max_tokens?: number;
7010 /**
7011 * Controls the randomness of the output; higher values produce more random results.
7012 */
7013 temperature?: number;
7014 /**
7015 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
7016 */
7017 top_p?: number;
7018 /**
7019 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
7020 */
7021 top_k?: number;
7022 /**
7023 * Random seed for reproducibility of the generation.
7024 */
7025 seed?: number;
7026 /**
7027 * Penalty for repeated tokens; higher values discourage repetition.
7028 */
7029 repetition_penalty?: number;
7030 /**
7031 * Decreases the likelihood of the model repeating the same lines verbatim.
7032 */
7033 frequency_penalty?: number;
7034 /**
7035 * Increases the likelihood of the model introducing new topics.
7036 */
7037 presence_penalty?: number;
7038}
7039interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 {
7040 type?: "json_object" | "json_schema";
7041 json_schema?: unknown;
7042}
7043type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = {
7044 /**
7045 * The generated text response from the model
7046 */
7047 response: string;
7048 /**
7049 * Usage statistics for the inference request
7050 */
7051 usage?: {
7052 /**
7053 * Total number of tokens in input
7054 */
7055 prompt_tokens?: number;
7056 /**
7057 * Total number of tokens in output
7058 */
7059 completion_tokens?: number;
7060 /**
7061 * Total number of input and output tokens
7062 */
7063 total_tokens?: number;
7064 };
7065 /**
7066 * An array of tool calls requests made during the response generation
7067 */
7068 tool_calls?: {
7069 /**
7070 * The arguments passed to be passed to the tool call request
7071 */
7072 arguments?: object;
7073 /**
7074 * The name of the tool to be called
7075 */
7076 name?: string;
7077 }[];
7078};
7079declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct {
7080 inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input;
7081 postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output;
7082}
7083type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages;
7084interface Ai_Cf_Qwen_Qwq_32B_Prompt {
7085 /**
7086 * The input text prompt for the model to generate a response.
7087 */
7088 prompt: string;
7089 /**
7090 * JSON schema that should be fulfilled for the response.
7091 */
7092 guided_json?: object;
7093 /**
7094 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7095 */
7096 raw?: boolean;
7097 /**
7098 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7099 */
7100 stream?: boolean;
7101 /**
7102 * The maximum number of tokens to generate in the response.
7103 */
7104 max_tokens?: number;
7105 /**
7106 * Controls the randomness of the output; higher values produce more random results.
7107 */
7108 temperature?: number;
7109 /**
7110 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
7111 */
7112 top_p?: number;
7113 /**
7114 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
7115 */
7116 top_k?: number;
7117 /**
7118 * Random seed for reproducibility of the generation.
7119 */
7120 seed?: number;
7121 /**
7122 * Penalty for repeated tokens; higher values discourage repetition.
7123 */
7124 repetition_penalty?: number;
7125 /**
7126 * Decreases the likelihood of the model repeating the same lines verbatim.
7127 */
7128 frequency_penalty?: number;
7129 /**
7130 * Increases the likelihood of the model introducing new topics.
7131 */
7132 presence_penalty?: number;
7133}
7134interface Ai_Cf_Qwen_Qwq_32B_Messages {
7135 /**
7136 * An array of message objects representing the conversation history.
7137 */
7138 messages: {
7139 /**
7140 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
7141 */
7142 role?: string;
7143 /**
7144 * The tool call id. If you don't know what to put here you can fall back to 000000001
7145 */
7146 tool_call_id?: string;
7147 content?: string | {
7148 /**
7149 * Type of the content provided
7150 */
7151 type?: string;
7152 text?: string;
7153 image_url?: {
7154 /**
7155 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7156 */
7157 url?: string;
7158 };
7159 }[] | {
7160 /**
7161 * Type of the content provided
7162 */
7163 type?: string;
7164 text?: string;
7165 image_url?: {
7166 /**
7167 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7168 */
7169 url?: string;
7170 };
7171 };
7172 }[];
7173 functions?: {
7174 name: string;
7175 code: string;
7176 }[];
7177 /**
7178 * A list of tools available for the assistant to use.
7179 */
7180 tools?: ({
7181 /**
7182 * The name of the tool. More descriptive the better.
7183 */
7184 name: string;
7185 /**
7186 * A brief description of what the tool does.
7187 */
7188 description: string;
7189 /**
7190 * Schema defining the parameters accepted by the tool.
7191 */
7192 parameters: {
7193 /**
7194 * The type of the parameters object (usually 'object').
7195 */
7196 type: string;
7197 /**
7198 * List of required parameter names.
7199 */
7200 required?: string[];
7201 /**
7202 * Definitions of each parameter.
7203 */
7204 properties: {
7205 [k: string]: {
7206 /**
7207 * The data type of the parameter.
7208 */
7209 type: string;
7210 /**
7211 * A description of the expected parameter.
7212 */
7213 description: string;
7214 };
7215 };
7216 };
7217 } | {
7218 /**
7219 * Specifies the type of tool (e.g., 'function').
7220 */
7221 type: string;
7222 /**
7223 * Details of the function tool.
7224 */
7225 function: {
7226 /**
7227 * The name of the function.
7228 */
7229 name: string;
7230 /**
7231 * A brief description of what the function does.
7232 */
7233 description: string;
7234 /**
7235 * Schema defining the parameters accepted by the function.
7236 */
7237 parameters: {
7238 /**
7239 * The type of the parameters object (usually 'object').
7240 */
7241 type: string;
7242 /**
7243 * List of required parameter names.
7244 */
7245 required?: string[];
7246 /**
7247 * Definitions of each parameter.
7248 */
7249 properties: {
7250 [k: string]: {
7251 /**
7252 * The data type of the parameter.
7253 */
7254 type: string;
7255 /**
7256 * A description of the expected parameter.
7257 */
7258 description: string;
7259 };
7260 };
7261 };
7262 };
7263 })[];
7264 /**
7265 * JSON schema that should be fufilled for the response.
7266 */
7267 guided_json?: object;
7268 /**
7269 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7270 */
7271 raw?: boolean;
7272 /**
7273 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7274 */
7275 stream?: boolean;
7276 /**
7277 * The maximum number of tokens to generate in the response.
7278 */
7279 max_tokens?: number;
7280 /**
7281 * Controls the randomness of the output; higher values produce more random results.
7282 */
7283 temperature?: number;
7284 /**
7285 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
7286 */
7287 top_p?: number;
7288 /**
7289 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
7290 */
7291 top_k?: number;
7292 /**
7293 * Random seed for reproducibility of the generation.
7294 */
7295 seed?: number;
7296 /**
7297 * Penalty for repeated tokens; higher values discourage repetition.
7298 */
7299 repetition_penalty?: number;
7300 /**
7301 * Decreases the likelihood of the model repeating the same lines verbatim.
7302 */
7303 frequency_penalty?: number;
7304 /**
7305 * Increases the likelihood of the model introducing new topics.
7306 */
7307 presence_penalty?: number;
7308}
7309type Ai_Cf_Qwen_Qwq_32B_Output = {
7310 /**
7311 * The generated text response from the model
7312 */
7313 response: string;
7314 /**
7315 * Usage statistics for the inference request
7316 */
7317 usage?: {
7318 /**
7319 * Total number of tokens in input
7320 */
7321 prompt_tokens?: number;
7322 /**
7323 * Total number of tokens in output
7324 */
7325 completion_tokens?: number;
7326 /**
7327 * Total number of input and output tokens
7328 */
7329 total_tokens?: number;
7330 };
7331 /**
7332 * An array of tool calls requests made during the response generation
7333 */
7334 tool_calls?: {
7335 /**
7336 * The arguments passed to be passed to the tool call request
7337 */
7338 arguments?: object;
7339 /**
7340 * The name of the tool to be called
7341 */
7342 name?: string;
7343 }[];
7344};
7345declare abstract class Base_Ai_Cf_Qwen_Qwq_32B {
7346 inputs: Ai_Cf_Qwen_Qwq_32B_Input;
7347 postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output;
7348}
7349type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages;
7350interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt {
7351 /**
7352 * The input text prompt for the model to generate a response.
7353 */
7354 prompt: string;
7355 /**
7356 * JSON schema that should be fulfilled for the response.
7357 */
7358 guided_json?: object;
7359 /**
7360 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7361 */
7362 raw?: boolean;
7363 /**
7364 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7365 */
7366 stream?: boolean;
7367 /**
7368 * The maximum number of tokens to generate in the response.
7369 */
7370 max_tokens?: number;
7371 /**
7372 * Controls the randomness of the output; higher values produce more random results.
7373 */
7374 temperature?: number;
7375 /**
7376 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
7377 */
7378 top_p?: number;
7379 /**
7380 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
7381 */
7382 top_k?: number;
7383 /**
7384 * Random seed for reproducibility of the generation.
7385 */
7386 seed?: number;
7387 /**
7388 * Penalty for repeated tokens; higher values discourage repetition.
7389 */
7390 repetition_penalty?: number;
7391 /**
7392 * Decreases the likelihood of the model repeating the same lines verbatim.
7393 */
7394 frequency_penalty?: number;
7395 /**
7396 * Increases the likelihood of the model introducing new topics.
7397 */
7398 presence_penalty?: number;
7399}
7400interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages {
7401 /**
7402 * An array of message objects representing the conversation history.
7403 */
7404 messages: {
7405 /**
7406 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
7407 */
7408 role?: string;
7409 /**
7410 * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001
7411 */
7412 tool_call_id?: string;
7413 content?: string | {
7414 /**
7415 * Type of the content provided
7416 */
7417 type?: string;
7418 text?: string;
7419 image_url?: {
7420 /**
7421 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7422 */
7423 url?: string;
7424 };
7425 }[] | {
7426 /**
7427 * Type of the content provided
7428 */
7429 type?: string;
7430 text?: string;
7431 image_url?: {
7432 /**
7433 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7434 */
7435 url?: string;
7436 };
7437 };
7438 }[];
7439 functions?: {
7440 name: string;
7441 code: string;
7442 }[];
7443 /**
7444 * A list of tools available for the assistant to use.
7445 */
7446 tools?: ({
7447 /**
7448 * The name of the tool. More descriptive the better.
7449 */
7450 name: string;
7451 /**
7452 * A brief description of what the tool does.
7453 */
7454 description: string;
7455 /**
7456 * Schema defining the parameters accepted by the tool.
7457 */
7458 parameters: {
7459 /**
7460 * The type of the parameters object (usually 'object').
7461 */
7462 type: string;
7463 /**
7464 * List of required parameter names.
7465 */
7466 required?: string[];
7467 /**
7468 * Definitions of each parameter.
7469 */
7470 properties: {
7471 [k: string]: {
7472 /**
7473 * The data type of the parameter.
7474 */
7475 type: string;
7476 /**
7477 * A description of the expected parameter.
7478 */
7479 description: string;
7480 };
7481 };
7482 };
7483 } | {
7484 /**
7485 * Specifies the type of tool (e.g., 'function').
7486 */
7487 type: string;
7488 /**
7489 * Details of the function tool.
7490 */
7491 function: {
7492 /**
7493 * The name of the function.
7494 */
7495 name: string;
7496 /**
7497 * A brief description of what the function does.
7498 */
7499 description: string;
7500 /**
7501 * Schema defining the parameters accepted by the function.
7502 */
7503 parameters: {
7504 /**
7505 * The type of the parameters object (usually 'object').
7506 */
7507 type: string;
7508 /**
7509 * List of required parameter names.
7510 */
7511 required?: string[];
7512 /**
7513 * Definitions of each parameter.
7514 */
7515 properties: {
7516 [k: string]: {
7517 /**
7518 * The data type of the parameter.
7519 */
7520 type: string;
7521 /**
7522 * A description of the expected parameter.
7523 */
7524 description: string;
7525 };
7526 };
7527 };
7528 };
7529 })[];
7530 /**
7531 * JSON schema that should be fufilled for the response.
7532 */
7533 guided_json?: object;
7534 /**
7535 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7536 */
7537 raw?: boolean;
7538 /**
7539 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7540 */
7541 stream?: boolean;
7542 /**
7543 * The maximum number of tokens to generate in the response.
7544 */
7545 max_tokens?: number;
7546 /**
7547 * Controls the randomness of the output; higher values produce more random results.
7548 */
7549 temperature?: number;
7550 /**
7551 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
7552 */
7553 top_p?: number;
7554 /**
7555 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
7556 */
7557 top_k?: number;
7558 /**
7559 * Random seed for reproducibility of the generation.
7560 */
7561 seed?: number;
7562 /**
7563 * Penalty for repeated tokens; higher values discourage repetition.
7564 */
7565 repetition_penalty?: number;
7566 /**
7567 * Decreases the likelihood of the model repeating the same lines verbatim.
7568 */
7569 frequency_penalty?: number;
7570 /**
7571 * Increases the likelihood of the model introducing new topics.
7572 */
7573 presence_penalty?: number;
7574}
7575type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = {
7576 /**
7577 * The generated text response from the model
7578 */
7579 response: string;
7580 /**
7581 * Usage statistics for the inference request
7582 */
7583 usage?: {
7584 /**
7585 * Total number of tokens in input
7586 */
7587 prompt_tokens?: number;
7588 /**
7589 * Total number of tokens in output
7590 */
7591 completion_tokens?: number;
7592 /**
7593 * Total number of input and output tokens
7594 */
7595 total_tokens?: number;
7596 };
7597 /**
7598 * An array of tool calls requests made during the response generation
7599 */
7600 tool_calls?: {
7601 /**
7602 * The arguments passed to be passed to the tool call request
7603 */
7604 arguments?: object;
7605 /**
7606 * The name of the tool to be called
7607 */
7608 name?: string;
7609 }[];
7610};
7611declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct {
7612 inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input;
7613 postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output;
7614}
7615type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages;
7616interface Ai_Cf_Google_Gemma_3_12B_It_Prompt {
7617 /**
7618 * The input text prompt for the model to generate a response.
7619 */
7620 prompt: string;
7621 /**
7622 * JSON schema that should be fufilled for the response.
7623 */
7624 guided_json?: object;
7625 /**
7626 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7627 */
7628 raw?: boolean;
7629 /**
7630 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7631 */
7632 stream?: boolean;
7633 /**
7634 * The maximum number of tokens to generate in the response.
7635 */
7636 max_tokens?: number;
7637 /**
7638 * Controls the randomness of the output; higher values produce more random results.
7639 */
7640 temperature?: number;
7641 /**
7642 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
7643 */
7644 top_p?: number;
7645 /**
7646 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
7647 */
7648 top_k?: number;
7649 /**
7650 * Random seed for reproducibility of the generation.
7651 */
7652 seed?: number;
7653 /**
7654 * Penalty for repeated tokens; higher values discourage repetition.
7655 */
7656 repetition_penalty?: number;
7657 /**
7658 * Decreases the likelihood of the model repeating the same lines verbatim.
7659 */
7660 frequency_penalty?: number;
7661 /**
7662 * Increases the likelihood of the model introducing new topics.
7663 */
7664 presence_penalty?: number;
7665}
7666interface Ai_Cf_Google_Gemma_3_12B_It_Messages {
7667 /**
7668 * An array of message objects representing the conversation history.
7669 */
7670 messages: {
7671 /**
7672 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
7673 */
7674 role?: string;
7675 content?: string | {
7676 /**
7677 * Type of the content provided
7678 */
7679 type?: string;
7680 text?: string;
7681 image_url?: {
7682 /**
7683 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7684 */
7685 url?: string;
7686 };
7687 }[];
7688 }[];
7689 functions?: {
7690 name: string;
7691 code: string;
7692 }[];
7693 /**
7694 * A list of tools available for the assistant to use.
7695 */
7696 tools?: ({
7697 /**
7698 * The name of the tool. More descriptive the better.
7699 */
7700 name: string;
7701 /**
7702 * A brief description of what the tool does.
7703 */
7704 description: string;
7705 /**
7706 * Schema defining the parameters accepted by the tool.
7707 */
7708 parameters: {
7709 /**
7710 * The type of the parameters object (usually 'object').
7711 */
7712 type: string;
7713 /**
7714 * List of required parameter names.
7715 */
7716 required?: string[];
7717 /**
7718 * Definitions of each parameter.
7719 */
7720 properties: {
7721 [k: string]: {
7722 /**
7723 * The data type of the parameter.
7724 */
7725 type: string;
7726 /**
7727 * A description of the expected parameter.
7728 */
7729 description: string;
7730 };
7731 };
7732 };
7733 } | {
7734 /**
7735 * Specifies the type of tool (e.g., 'function').
7736 */
7737 type: string;
7738 /**
7739 * Details of the function tool.
7740 */
7741 function: {
7742 /**
7743 * The name of the function.
7744 */
7745 name: string;
7746 /**
7747 * A brief description of what the function does.
7748 */
7749 description: string;
7750 /**
7751 * Schema defining the parameters accepted by the function.
7752 */
7753 parameters: {
7754 /**
7755 * The type of the parameters object (usually 'object').
7756 */
7757 type: string;
7758 /**
7759 * List of required parameter names.
7760 */
7761 required?: string[];
7762 /**
7763 * Definitions of each parameter.
7764 */
7765 properties: {
7766 [k: string]: {
7767 /**
7768 * The data type of the parameter.
7769 */
7770 type: string;
7771 /**
7772 * A description of the expected parameter.
7773 */
7774 description: string;
7775 };
7776 };
7777 };
7778 };
7779 })[];
7780 /**
7781 * JSON schema that should be fufilled for the response.
7782 */
7783 guided_json?: object;
7784 /**
7785 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7786 */
7787 raw?: boolean;
7788 /**
7789 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7790 */
7791 stream?: boolean;
7792 /**
7793 * The maximum number of tokens to generate in the response.
7794 */
7795 max_tokens?: number;
7796 /**
7797 * Controls the randomness of the output; higher values produce more random results.
7798 */
7799 temperature?: number;
7800 /**
7801 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
7802 */
7803 top_p?: number;
7804 /**
7805 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
7806 */
7807 top_k?: number;
7808 /**
7809 * Random seed for reproducibility of the generation.
7810 */
7811 seed?: number;
7812 /**
7813 * Penalty for repeated tokens; higher values discourage repetition.
7814 */
7815 repetition_penalty?: number;
7816 /**
7817 * Decreases the likelihood of the model repeating the same lines verbatim.
7818 */
7819 frequency_penalty?: number;
7820 /**
7821 * Increases the likelihood of the model introducing new topics.
7822 */
7823 presence_penalty?: number;
7824}
7825type Ai_Cf_Google_Gemma_3_12B_It_Output = {
7826 /**
7827 * The generated text response from the model
7828 */
7829 response: string;
7830 /**
7831 * Usage statistics for the inference request
7832 */
7833 usage?: {
7834 /**
7835 * Total number of tokens in input
7836 */
7837 prompt_tokens?: number;
7838 /**
7839 * Total number of tokens in output
7840 */
7841 completion_tokens?: number;
7842 /**
7843 * Total number of input and output tokens
7844 */
7845 total_tokens?: number;
7846 };
7847 /**
7848 * An array of tool calls requests made during the response generation
7849 */
7850 tool_calls?: {
7851 /**
7852 * The arguments passed to be passed to the tool call request
7853 */
7854 arguments?: object;
7855 /**
7856 * The name of the tool to be called
7857 */
7858 name?: string;
7859 }[];
7860};
7861declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It {
7862 inputs: Ai_Cf_Google_Gemma_3_12B_It_Input;
7863 postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output;
7864}
7865type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch;
7866interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt {
7867 /**
7868 * The input text prompt for the model to generate a response.
7869 */
7870 prompt: string;
7871 /**
7872 * JSON schema that should be fulfilled for the response.
7873 */
7874 guided_json?: object;
7875 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;
7876 /**
7877 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7878 */
7879 raw?: boolean;
7880 /**
7881 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7882 */
7883 stream?: boolean;
7884 /**
7885 * The maximum number of tokens to generate in the response.
7886 */
7887 max_tokens?: number;
7888 /**
7889 * Controls the randomness of the output; higher values produce more random results.
7890 */
7891 temperature?: number;
7892 /**
7893 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
7894 */
7895 top_p?: number;
7896 /**
7897 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
7898 */
7899 top_k?: number;
7900 /**
7901 * Random seed for reproducibility of the generation.
7902 */
7903 seed?: number;
7904 /**
7905 * Penalty for repeated tokens; higher values discourage repetition.
7906 */
7907 repetition_penalty?: number;
7908 /**
7909 * Decreases the likelihood of the model repeating the same lines verbatim.
7910 */
7911 frequency_penalty?: number;
7912 /**
7913 * Increases the likelihood of the model introducing new topics.
7914 */
7915 presence_penalty?: number;
7916}
7917interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode {
7918 type?: "json_object" | "json_schema";
7919 json_schema?: unknown;
7920}
7921interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages {
7922 /**
7923 * An array of message objects representing the conversation history.
7924 */
7925 messages: {
7926 /**
7927 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
7928 */
7929 role?: string;
7930 /**
7931 * The tool call id. If you don't know what to put here you can fall back to 000000001
7932 */
7933 tool_call_id?: string;
7934 content?: string | {
7935 /**
7936 * Type of the content provided
7937 */
7938 type?: string;
7939 text?: string;
7940 image_url?: {
7941 /**
7942 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7943 */
7944 url?: string;
7945 };
7946 }[] | {
7947 /**
7948 * Type of the content provided
7949 */
7950 type?: string;
7951 text?: string;
7952 image_url?: {
7953 /**
7954 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7955 */
7956 url?: string;
7957 };
7958 };
7959 }[];
7960 functions?: {
7961 name: string;
7962 code: string;
7963 }[];
7964 /**
7965 * A list of tools available for the assistant to use.
7966 */
7967 tools?: ({
7968 /**
7969 * The name of the tool. More descriptive the better.
7970 */
7971 name: string;
7972 /**
7973 * A brief description of what the tool does.
7974 */
7975 description: string;
7976 /**
7977 * Schema defining the parameters accepted by the tool.
7978 */
7979 parameters: {
7980 /**
7981 * The type of the parameters object (usually 'object').
7982 */
7983 type: string;
7984 /**
7985 * List of required parameter names.
7986 */
7987 required?: string[];
7988 /**
7989 * Definitions of each parameter.
7990 */
7991 properties: {
7992 [k: string]: {
7993 /**
7994 * The data type of the parameter.
7995 */
7996 type: string;
7997 /**
7998 * A description of the expected parameter.
7999 */
8000 description: string;
8001 };
8002 };
8003 };
8004 } | {
8005 /**
8006 * Specifies the type of tool (e.g., 'function').
8007 */
8008 type: string;
8009 /**
8010 * Details of the function tool.
8011 */
8012 function: {
8013 /**
8014 * The name of the function.
8015 */
8016 name: string;
8017 /**
8018 * A brief description of what the function does.
8019 */
8020 description: string;
8021 /**
8022 * Schema defining the parameters accepted by the function.
8023 */
8024 parameters: {
8025 /**
8026 * The type of the parameters object (usually 'object').
8027 */
8028 type: string;
8029 /**
8030 * List of required parameter names.
8031 */
8032 required?: string[];
8033 /**
8034 * Definitions of each parameter.
8035 */
8036 properties: {
8037 [k: string]: {
8038 /**
8039 * The data type of the parameter.
8040 */
8041 type: string;
8042 /**
8043 * A description of the expected parameter.
8044 */
8045 description: string;
8046 };
8047 };
8048 };
8049 };
8050 })[];
8051 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;
8052 /**
8053 * JSON schema that should be fufilled for the response.
8054 */
8055 guided_json?: object;
8056 /**
8057 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8058 */
8059 raw?: boolean;
8060 /**
8061 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8062 */
8063 stream?: boolean;
8064 /**
8065 * The maximum number of tokens to generate in the response.
8066 */
8067 max_tokens?: number;
8068 /**
8069 * Controls the randomness of the output; higher values produce more random results.
8070 */
8071 temperature?: number;
8072 /**
8073 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
8074 */
8075 top_p?: number;
8076 /**
8077 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
8078 */
8079 top_k?: number;
8080 /**
8081 * Random seed for reproducibility of the generation.
8082 */
8083 seed?: number;
8084 /**
8085 * Penalty for repeated tokens; higher values discourage repetition.
8086 */
8087 repetition_penalty?: number;
8088 /**
8089 * Decreases the likelihood of the model repeating the same lines verbatim.
8090 */
8091 frequency_penalty?: number;
8092 /**
8093 * Increases the likelihood of the model introducing new topics.
8094 */
8095 presence_penalty?: number;
8096}
8097interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch {
8098 requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[];
8099}
8100interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner {
8101 /**
8102 * The input text prompt for the model to generate a response.
8103 */
8104 prompt: string;
8105 /**
8106 * JSON schema that should be fulfilled for the response.
8107 */
8108 guided_json?: object;
8109 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;
8110 /**
8111 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8112 */
8113 raw?: boolean;
8114 /**
8115 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8116 */
8117 stream?: boolean;
8118 /**
8119 * The maximum number of tokens to generate in the response.
8120 */
8121 max_tokens?: number;
8122 /**
8123 * Controls the randomness of the output; higher values produce more random results.
8124 */
8125 temperature?: number;
8126 /**
8127 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
8128 */
8129 top_p?: number;
8130 /**
8131 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
8132 */
8133 top_k?: number;
8134 /**
8135 * Random seed for reproducibility of the generation.
8136 */
8137 seed?: number;
8138 /**
8139 * Penalty for repeated tokens; higher values discourage repetition.
8140 */
8141 repetition_penalty?: number;
8142 /**
8143 * Decreases the likelihood of the model repeating the same lines verbatim.
8144 */
8145 frequency_penalty?: number;
8146 /**
8147 * Increases the likelihood of the model introducing new topics.
8148 */
8149 presence_penalty?: number;
8150}
8151interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner {
8152 /**
8153 * An array of message objects representing the conversation history.
8154 */
8155 messages: {
8156 /**
8157 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
8158 */
8159 role?: string;
8160 /**
8161 * The tool call id. If you don't know what to put here you can fall back to 000000001
8162 */
8163 tool_call_id?: string;
8164 content?: string | {
8165 /**
8166 * Type of the content provided
8167 */
8168 type?: string;
8169 text?: string;
8170 image_url?: {
8171 /**
8172 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
8173 */
8174 url?: string;
8175 };
8176 }[] | {
8177 /**
8178 * Type of the content provided
8179 */
8180 type?: string;
8181 text?: string;
8182 image_url?: {
8183 /**
8184 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
8185 */
8186 url?: string;
8187 };
8188 };
8189 }[];
8190 functions?: {
8191 name: string;
8192 code: string;
8193 }[];
8194 /**
8195 * A list of tools available for the assistant to use.
8196 */
8197 tools?: ({
8198 /**
8199 * The name of the tool. More descriptive the better.
8200 */
8201 name: string;
8202 /**
8203 * A brief description of what the tool does.
8204 */
8205 description: string;
8206 /**
8207 * Schema defining the parameters accepted by the tool.
8208 */
8209 parameters: {
8210 /**
8211 * The type of the parameters object (usually 'object').
8212 */
8213 type: string;
8214 /**
8215 * List of required parameter names.
8216 */
8217 required?: string[];
8218 /**
8219 * Definitions of each parameter.
8220 */
8221 properties: {
8222 [k: string]: {
8223 /**
8224 * The data type of the parameter.
8225 */
8226 type: string;
8227 /**
8228 * A description of the expected parameter.
8229 */
8230 description: string;
8231 };
8232 };
8233 };
8234 } | {
8235 /**
8236 * Specifies the type of tool (e.g., 'function').
8237 */
8238 type: string;
8239 /**
8240 * Details of the function tool.
8241 */
8242 function: {
8243 /**
8244 * The name of the function.
8245 */
8246 name: string;
8247 /**
8248 * A brief description of what the function does.
8249 */
8250 description: string;
8251 /**
8252 * Schema defining the parameters accepted by the function.
8253 */
8254 parameters: {
8255 /**
8256 * The type of the parameters object (usually 'object').
8257 */
8258 type: string;
8259 /**
8260 * List of required parameter names.
8261 */
8262 required?: string[];
8263 /**
8264 * Definitions of each parameter.
8265 */
8266 properties: {
8267 [k: string]: {
8268 /**
8269 * The data type of the parameter.
8270 */
8271 type: string;
8272 /**
8273 * A description of the expected parameter.
8274 */
8275 description: string;
8276 };
8277 };
8278 };
8279 };
8280 })[];
8281 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;
8282 /**
8283 * JSON schema that should be fufilled for the response.
8284 */
8285 guided_json?: object;
8286 /**
8287 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8288 */
8289 raw?: boolean;
8290 /**
8291 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8292 */
8293 stream?: boolean;
8294 /**
8295 * The maximum number of tokens to generate in the response.
8296 */
8297 max_tokens?: number;
8298 /**
8299 * Controls the randomness of the output; higher values produce more random results.
8300 */
8301 temperature?: number;
8302 /**
8303 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
8304 */
8305 top_p?: number;
8306 /**
8307 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
8308 */
8309 top_k?: number;
8310 /**
8311 * Random seed for reproducibility of the generation.
8312 */
8313 seed?: number;
8314 /**
8315 * Penalty for repeated tokens; higher values discourage repetition.
8316 */
8317 repetition_penalty?: number;
8318 /**
8319 * Decreases the likelihood of the model repeating the same lines verbatim.
8320 */
8321 frequency_penalty?: number;
8322 /**
8323 * Increases the likelihood of the model introducing new topics.
8324 */
8325 presence_penalty?: number;
8326}
8327type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = {
8328 /**
8329 * The generated text response from the model
8330 */
8331 response: string;
8332 /**
8333 * Usage statistics for the inference request
8334 */
8335 usage?: {
8336 /**
8337 * Total number of tokens in input
8338 */
8339 prompt_tokens?: number;
8340 /**
8341 * Total number of tokens in output
8342 */
8343 completion_tokens?: number;
8344 /**
8345 * Total number of input and output tokens
8346 */
8347 total_tokens?: number;
8348 };
8349 /**
8350 * An array of tool calls requests made during the response generation
8351 */
8352 tool_calls?: {
8353 /**
8354 * The tool call id.
8355 */
8356 id?: string;
8357 /**
8358 * Specifies the type of tool (e.g., 'function').
8359 */
8360 type?: string;
8361 /**
8362 * Details of the function tool.
8363 */
8364 function?: {
8365 /**
8366 * The name of the tool to be called
8367 */
8368 name?: string;
8369 /**
8370 * The arguments passed to be passed to the tool call request
8371 */
8372 arguments?: object;
8373 };
8374 }[];
8375};
8376declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct {
8377 inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input;
8378 postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output;
8379}
8380type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch;
8381interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt {
8382 /**
8383 * The input text prompt for the model to generate a response.
8384 */
8385 prompt: string;
8386 /**
8387 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
8388 */
8389 lora?: string;
8390 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode;
8391 /**
8392 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8393 */
8394 raw?: boolean;
8395 /**
8396 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8397 */
8398 stream?: boolean;
8399 /**
8400 * The maximum number of tokens to generate in the response.
8401 */
8402 max_tokens?: number;
8403 /**
8404 * Controls the randomness of the output; higher values produce more random results.
8405 */
8406 temperature?: number;
8407 /**
8408 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
8409 */
8410 top_p?: number;
8411 /**
8412 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
8413 */
8414 top_k?: number;
8415 /**
8416 * Random seed for reproducibility of the generation.
8417 */
8418 seed?: number;
8419 /**
8420 * Penalty for repeated tokens; higher values discourage repetition.
8421 */
8422 repetition_penalty?: number;
8423 /**
8424 * Decreases the likelihood of the model repeating the same lines verbatim.
8425 */
8426 frequency_penalty?: number;
8427 /**
8428 * Increases the likelihood of the model introducing new topics.
8429 */
8430 presence_penalty?: number;
8431}
8432interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode {
8433 type?: "json_object" | "json_schema";
8434 json_schema?: unknown;
8435}
8436interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages {
8437 /**
8438 * An array of message objects representing the conversation history.
8439 */
8440 messages: {
8441 /**
8442 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
8443 */
8444 role: string;
8445 content: string | {
8446 /**
8447 * Type of the content (text)
8448 */
8449 type?: string;
8450 /**
8451 * Text content
8452 */
8453 text?: string;
8454 }[];
8455 }[];
8456 functions?: {
8457 name: string;
8458 code: string;
8459 }[];
8460 /**
8461 * A list of tools available for the assistant to use.
8462 */
8463 tools?: ({
8464 /**
8465 * The name of the tool. More descriptive the better.
8466 */
8467 name: string;
8468 /**
8469 * A brief description of what the tool does.
8470 */
8471 description: string;
8472 /**
8473 * Schema defining the parameters accepted by the tool.
8474 */
8475 parameters: {
8476 /**
8477 * The type of the parameters object (usually 'object').
8478 */
8479 type: string;
8480 /**
8481 * List of required parameter names.
8482 */
8483 required?: string[];
8484 /**
8485 * Definitions of each parameter.
8486 */
8487 properties: {
8488 [k: string]: {
8489 /**
8490 * The data type of the parameter.
8491 */
8492 type: string;
8493 /**
8494 * A description of the expected parameter.
8495 */
8496 description: string;
8497 };
8498 };
8499 };
8500 } | {
8501 /**
8502 * Specifies the type of tool (e.g., 'function').
8503 */
8504 type: string;
8505 /**
8506 * Details of the function tool.
8507 */
8508 function: {
8509 /**
8510 * The name of the function.
8511 */
8512 name: string;
8513 /**
8514 * A brief description of what the function does.
8515 */
8516 description: string;
8517 /**
8518 * Schema defining the parameters accepted by the function.
8519 */
8520 parameters: {
8521 /**
8522 * The type of the parameters object (usually 'object').
8523 */
8524 type: string;
8525 /**
8526 * List of required parameter names.
8527 */
8528 required?: string[];
8529 /**
8530 * Definitions of each parameter.
8531 */
8532 properties: {
8533 [k: string]: {
8534 /**
8535 * The data type of the parameter.
8536 */
8537 type: string;
8538 /**
8539 * A description of the expected parameter.
8540 */
8541 description: string;
8542 };
8543 };
8544 };
8545 };
8546 })[];
8547 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1;
8548 /**
8549 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8550 */
8551 raw?: boolean;
8552 /**
8553 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8554 */
8555 stream?: boolean;
8556 /**
8557 * The maximum number of tokens to generate in the response.
8558 */
8559 max_tokens?: number;
8560 /**
8561 * Controls the randomness of the output; higher values produce more random results.
8562 */
8563 temperature?: number;
8564 /**
8565 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
8566 */
8567 top_p?: number;
8568 /**
8569 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
8570 */
8571 top_k?: number;
8572 /**
8573 * Random seed for reproducibility of the generation.
8574 */
8575 seed?: number;
8576 /**
8577 * Penalty for repeated tokens; higher values discourage repetition.
8578 */
8579 repetition_penalty?: number;
8580 /**
8581 * Decreases the likelihood of the model repeating the same lines verbatim.
8582 */
8583 frequency_penalty?: number;
8584 /**
8585 * Increases the likelihood of the model introducing new topics.
8586 */
8587 presence_penalty?: number;
8588}
8589interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 {
8590 type?: "json_object" | "json_schema";
8591 json_schema?: unknown;
8592}
8593interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch {
8594 requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[];
8595}
8596interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 {
8597 /**
8598 * The input text prompt for the model to generate a response.
8599 */
8600 prompt: string;
8601 /**
8602 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
8603 */
8604 lora?: string;
8605 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2;
8606 /**
8607 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8608 */
8609 raw?: boolean;
8610 /**
8611 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8612 */
8613 stream?: boolean;
8614 /**
8615 * The maximum number of tokens to generate in the response.
8616 */
8617 max_tokens?: number;
8618 /**
8619 * Controls the randomness of the output; higher values produce more random results.
8620 */
8621 temperature?: number;
8622 /**
8623 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
8624 */
8625 top_p?: number;
8626 /**
8627 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
8628 */
8629 top_k?: number;
8630 /**
8631 * Random seed for reproducibility of the generation.
8632 */
8633 seed?: number;
8634 /**
8635 * Penalty for repeated tokens; higher values discourage repetition.
8636 */
8637 repetition_penalty?: number;
8638 /**
8639 * Decreases the likelihood of the model repeating the same lines verbatim.
8640 */
8641 frequency_penalty?: number;
8642 /**
8643 * Increases the likelihood of the model introducing new topics.
8644 */
8645 presence_penalty?: number;
8646}
8647interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 {
8648 type?: "json_object" | "json_schema";
8649 json_schema?: unknown;
8650}
8651interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 {
8652 /**
8653 * An array of message objects representing the conversation history.
8654 */
8655 messages: {
8656 /**
8657 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
8658 */
8659 role: string;
8660 content: string | {
8661 /**
8662 * Type of the content (text)
8663 */
8664 type?: string;
8665 /**
8666 * Text content
8667 */
8668 text?: string;
8669 }[];
8670 }[];
8671 functions?: {
8672 name: string;
8673 code: string;
8674 }[];
8675 /**
8676 * A list of tools available for the assistant to use.
8677 */
8678 tools?: ({
8679 /**
8680 * The name of the tool. More descriptive the better.
8681 */
8682 name: string;
8683 /**
8684 * A brief description of what the tool does.
8685 */
8686 description: string;
8687 /**
8688 * Schema defining the parameters accepted by the tool.
8689 */
8690 parameters: {
8691 /**
8692 * The type of the parameters object (usually 'object').
8693 */
8694 type: string;
8695 /**
8696 * List of required parameter names.
8697 */
8698 required?: string[];
8699 /**
8700 * Definitions of each parameter.
8701 */
8702 properties: {
8703 [k: string]: {
8704 /**
8705 * The data type of the parameter.
8706 */
8707 type: string;
8708 /**
8709 * A description of the expected parameter.
8710 */
8711 description: string;
8712 };
8713 };
8714 };
8715 } | {
8716 /**
8717 * Specifies the type of tool (e.g., 'function').
8718 */
8719 type: string;
8720 /**
8721 * Details of the function tool.
8722 */
8723 function: {
8724 /**
8725 * The name of the function.
8726 */
8727 name: string;
8728 /**
8729 * A brief description of what the function does.
8730 */
8731 description: string;
8732 /**
8733 * Schema defining the parameters accepted by the function.
8734 */
8735 parameters: {
8736 /**
8737 * The type of the parameters object (usually 'object').
8738 */
8739 type: string;
8740 /**
8741 * List of required parameter names.
8742 */
8743 required?: string[];
8744 /**
8745 * Definitions of each parameter.
8746 */
8747 properties: {
8748 [k: string]: {
8749 /**
8750 * The data type of the parameter.
8751 */
8752 type: string;
8753 /**
8754 * A description of the expected parameter.
8755 */
8756 description: string;
8757 };
8758 };
8759 };
8760 };
8761 })[];
8762 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3;
8763 /**
8764 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8765 */
8766 raw?: boolean;
8767 /**
8768 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8769 */
8770 stream?: boolean;
8771 /**
8772 * The maximum number of tokens to generate in the response.
8773 */
8774 max_tokens?: number;
8775 /**
8776 * Controls the randomness of the output; higher values produce more random results.
8777 */
8778 temperature?: number;
8779 /**
8780 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
8781 */
8782 top_p?: number;
8783 /**
8784 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
8785 */
8786 top_k?: number;
8787 /**
8788 * Random seed for reproducibility of the generation.
8789 */
8790 seed?: number;
8791 /**
8792 * Penalty for repeated tokens; higher values discourage repetition.
8793 */
8794 repetition_penalty?: number;
8795 /**
8796 * Decreases the likelihood of the model repeating the same lines verbatim.
8797 */
8798 frequency_penalty?: number;
8799 /**
8800 * Increases the likelihood of the model introducing new topics.
8801 */
8802 presence_penalty?: number;
8803}
8804interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 {
8805 type?: "json_object" | "json_schema";
8806 json_schema?: unknown;
8807}
8808type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse;
8809interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response {
8810 /**
8811 * Unique identifier for the completion
8812 */
8813 id?: string;
8814 /**
8815 * Object type identifier
8816 */
8817 object?: "chat.completion";
8818 /**
8819 * Unix timestamp of when the completion was created
8820 */
8821 created?: number;
8822 /**
8823 * Model used for the completion
8824 */
8825 model?: string;
8826 /**
8827 * List of completion choices
8828 */
8829 choices?: {
8830 /**
8831 * Index of the choice in the list
8832 */
8833 index?: number;
8834 /**
8835 * The message generated by the model
8836 */
8837 message?: {
8838 /**
8839 * Role of the message author
8840 */
8841 role: string;
8842 /**
8843 * The content of the message
8844 */
8845 content: string;
8846 /**
8847 * Internal reasoning content (if available)
8848 */
8849 reasoning_content?: string;
8850 /**
8851 * Tool calls made by the assistant
8852 */
8853 tool_calls?: {
8854 /**
8855 * Unique identifier for the tool call
8856 */
8857 id: string;
8858 /**
8859 * Type of tool call
8860 */
8861 type: "function";
8862 function: {
8863 /**
8864 * Name of the function to call
8865 */
8866 name: string;
8867 /**
8868 * JSON string of arguments for the function
8869 */
8870 arguments: string;
8871 };
8872 }[];
8873 };
8874 /**
8875 * Reason why the model stopped generating
8876 */
8877 finish_reason?: string;
8878 /**
8879 * Stop reason (may be null)
8880 */
8881 stop_reason?: string | null;
8882 /**
8883 * Log probabilities (if requested)
8884 */
8885 logprobs?: {} | null;
8886 }[];
8887 /**
8888 * Usage statistics for the inference request
8889 */
8890 usage?: {
8891 /**
8892 * Total number of tokens in input
8893 */
8894 prompt_tokens?: number;
8895 /**
8896 * Total number of tokens in output
8897 */
8898 completion_tokens?: number;
8899 /**
8900 * Total number of input and output tokens
8901 */
8902 total_tokens?: number;
8903 };
8904 /**
8905 * Log probabilities for the prompt (if requested)
8906 */
8907 prompt_logprobs?: {} | null;
8908}
8909interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response {
8910 /**
8911 * Unique identifier for the completion
8912 */
8913 id?: string;
8914 /**
8915 * Object type identifier
8916 */
8917 object?: "text_completion";
8918 /**
8919 * Unix timestamp of when the completion was created
8920 */
8921 created?: number;
8922 /**
8923 * Model used for the completion
8924 */
8925 model?: string;
8926 /**
8927 * List of completion choices
8928 */
8929 choices?: {
8930 /**
8931 * Index of the choice in the list
8932 */
8933 index: number;
8934 /**
8935 * The generated text completion
8936 */
8937 text: string;
8938 /**
8939 * Reason why the model stopped generating
8940 */
8941 finish_reason: string;
8942 /**
8943 * Stop reason (may be null)
8944 */
8945 stop_reason?: string | null;
8946 /**
8947 * Log probabilities (if requested)
8948 */
8949 logprobs?: {} | null;
8950 /**
8951 * Log probabilities for the prompt (if requested)
8952 */
8953 prompt_logprobs?: {} | null;
8954 }[];
8955 /**
8956 * Usage statistics for the inference request
8957 */
8958 usage?: {
8959 /**
8960 * Total number of tokens in input
8961 */
8962 prompt_tokens?: number;
8963 /**
8964 * Total number of tokens in output
8965 */
8966 completion_tokens?: number;
8967 /**
8968 * Total number of input and output tokens
8969 */
8970 total_tokens?: number;
8971 };
8972}
8973interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse {
8974 /**
8975 * The async request id that can be used to obtain the results.
8976 */
8977 request_id?: string;
8978}
8979declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 {
8980 inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input;
8981 postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output;
8982}
8983interface Ai_Cf_Deepgram_Nova_3_Input {
8984 audio: {
8985 body: object;
8986 contentType: string;
8987 };
8988 /**
8989 * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param.
8990 */
8991 custom_topic_mode?: "extended" | "strict";
8992 /**
8993 * Custom topics you want the model to detect within your input audio or text if present Submit up to 100
8994 */
8995 custom_topic?: string;
8996 /**
8997 * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param
8998 */
8999 custom_intent_mode?: "extended" | "strict";
9000 /**
9001 * Custom intents you want the model to detect within your input audio if present
9002 */
9003 custom_intent?: string;
9004 /**
9005 * Identifies and extracts key entities from content in submitted audio
9006 */
9007 detect_entities?: boolean;
9008 /**
9009 * Identifies the dominant language spoken in submitted audio
9010 */
9011 detect_language?: boolean;
9012 /**
9013 * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0
9014 */
9015 diarize?: boolean;
9016 /**
9017 * Identify and extract key entities from content in submitted audio
9018 */
9019 dictation?: boolean;
9020 /**
9021 * Specify the expected encoding of your submitted audio
9022 */
9023 encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729";
9024 /**
9025 * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing
9026 */
9027 extra?: string;
9028 /**
9029 * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um'
9030 */
9031 filler_words?: boolean;
9032 /**
9033 * Key term prompting can boost or suppress specialized terminology and brands.
9034 */
9035 keyterm?: string;
9036 /**
9037 * Keywords can boost or suppress specialized terminology and brands.
9038 */
9039 keywords?: string;
9040 /**
9041 * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available.
9042 */
9043 language?: string;
9044 /**
9045 * Spoken measurements will be converted to their corresponding abbreviations.
9046 */
9047 measurements?: boolean;
9048 /**
9049 * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip.
9050 */
9051 mip_opt_out?: boolean;
9052 /**
9053 * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio
9054 */
9055 mode?: "general" | "medical" | "finance";
9056 /**
9057 * Transcribe each audio channel independently.
9058 */
9059 multichannel?: boolean;
9060 /**
9061 * Numerals converts numbers from written format to numerical format.
9062 */
9063 numerals?: boolean;
9064 /**
9065 * Splits audio into paragraphs to improve transcript readability.
9066 */
9067 paragraphs?: boolean;
9068 /**
9069 * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely.
9070 */
9071 profanity_filter?: boolean;
9072 /**
9073 * Add punctuation and capitalization to the transcript.
9074 */
9075 punctuate?: boolean;
9076 /**
9077 * Redaction removes sensitive information from your transcripts.
9078 */
9079 redact?: string;
9080 /**
9081 * Search for terms or phrases in submitted audio and replaces them.
9082 */
9083 replace?: string;
9084 /**
9085 * Search for terms or phrases in submitted audio.
9086 */
9087 search?: string;
9088 /**
9089 * Recognizes the sentiment throughout a transcript or text.
9090 */
9091 sentiment?: boolean;
9092 /**
9093 * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability.
9094 */
9095 smart_format?: boolean;
9096 /**
9097 * Detect topics throughout a transcript or text.
9098 */
9099 topics?: boolean;
9100 /**
9101 * Segments speech into meaningful semantic units.
9102 */
9103 utterances?: boolean;
9104 /**
9105 * Seconds to wait before detecting a pause between words in submitted audio.
9106 */
9107 utt_split?: number;
9108 /**
9109 * The number of channels in the submitted audio
9110 */
9111 channels?: number;
9112 /**
9113 * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets.
9114 */
9115 interim_results?: boolean;
9116 /**
9117 * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing
9118 */
9119 endpointing?: string;
9120 /**
9121 * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets.
9122 */
9123 vad_events?: boolean;
9124 /**
9125 * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets.
9126 */
9127 utterance_end_ms?: boolean;
9128}
9129interface Ai_Cf_Deepgram_Nova_3_Output {
9130 results?: {
9131 channels?: {
9132 alternatives?: {
9133 confidence?: number;
9134 transcript?: string;
9135 words?: {
9136 confidence?: number;
9137 end?: number;
9138 start?: number;
9139 word?: string;
9140 }[];
9141 }[];
9142 }[];
9143 summary?: {
9144 result?: string;
9145 short?: string;
9146 };
9147 sentiments?: {
9148 segments?: {
9149 text?: string;
9150 start_word?: number;
9151 end_word?: number;
9152 sentiment?: string;
9153 sentiment_score?: number;
9154 }[];
9155 average?: {
9156 sentiment?: string;
9157 sentiment_score?: number;
9158 };
9159 };
9160 };
9161}
9162declare abstract class Base_Ai_Cf_Deepgram_Nova_3 {
9163 inputs: Ai_Cf_Deepgram_Nova_3_Input;
9164 postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output;
9165}
9166interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input {
9167 queries?: string | string[];
9168 /**
9169 * Optional instruction for the task
9170 */
9171 instruction?: string;
9172 documents?: string | string[];
9173 text?: string | string[];
9174}
9175interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output {
9176 data?: number[][];
9177 shape?: number[];
9178}
9179declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B {
9180 inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input;
9181 postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output;
9182}
9183type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = {
9184 /**
9185 * readable stream with audio data and content-type specified for that data
9186 */
9187 audio: {
9188 body: object;
9189 contentType: string;
9190 };
9191 /**
9192 * type of data PCM data that's sent to the inference server as raw array
9193 */
9194 dtype?: "uint8" | "float32" | "float64";
9195} | {
9196 /**
9197 * base64 encoded audio data
9198 */
9199 audio: string;
9200 /**
9201 * type of data PCM data that's sent to the inference server as raw array
9202 */
9203 dtype?: "uint8" | "float32" | "float64";
9204};
9205interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output {
9206 /**
9207 * if true, end-of-turn was detected
9208 */
9209 is_complete?: boolean;
9210 /**
9211 * probability of the end-of-turn detection
9212 */
9213 probability?: number;
9214}
9215declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 {
9216 inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input;
9217 postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output;
9218}
9219declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B {
9220 inputs: XOR<ResponsesInput, ChatCompletionsMessagesInput>;
9221 postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;
9222}
9223declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B {
9224 inputs: XOR<ResponsesInput, ChatCompletionsMessagesInput>;
9225 postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;
9226}
9227interface Ai_Cf_Leonardo_Phoenix_1_0_Input {
9228 /**
9229 * A text description of the image you want to generate.
9230 */
9231 prompt: string;
9232 /**
9233 * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt
9234 */
9235 guidance?: number;
9236 /**
9237 * Random seed for reproducibility of the image generation
9238 */
9239 seed?: number;
9240 /**
9241 * The height of the generated image in pixels
9242 */
9243 height?: number;
9244 /**
9245 * The width of the generated image in pixels
9246 */
9247 width?: number;
9248 /**
9249 * The number of diffusion steps; higher values can improve quality but take longer
9250 */
9251 num_steps?: number;
9252 /**
9253 * Specify what to exclude from the generated images
9254 */
9255 negative_prompt?: string;
9256}
9257/**
9258 * The generated image in JPEG format
9259 */
9260type Ai_Cf_Leonardo_Phoenix_1_0_Output = string;
9261declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 {
9262 inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input;
9263 postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output;
9264}
9265interface Ai_Cf_Leonardo_Lucid_Origin_Input {
9266 /**
9267 * A text description of the image you want to generate.
9268 */
9269 prompt: string;
9270 /**
9271 * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt
9272 */
9273 guidance?: number;
9274 /**
9275 * Random seed for reproducibility of the image generation
9276 */
9277 seed?: number;
9278 /**
9279 * The height of the generated image in pixels
9280 */
9281 height?: number;
9282 /**
9283 * The width of the generated image in pixels
9284 */
9285 width?: number;
9286 /**
9287 * The number of diffusion steps; higher values can improve quality but take longer
9288 */
9289 num_steps?: number;
9290 /**
9291 * The number of diffusion steps; higher values can improve quality but take longer
9292 */
9293 steps?: number;
9294}
9295interface Ai_Cf_Leonardo_Lucid_Origin_Output {
9296 /**
9297 * The generated image in Base64 format.
9298 */
9299 image?: string;
9300}
9301declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin {
9302 inputs: Ai_Cf_Leonardo_Lucid_Origin_Input;
9303 postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output;
9304}
9305interface Ai_Cf_Deepgram_Aura_1_Input {
9306 /**
9307 * Speaker used to produce the audio.
9308 */
9309 speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella";
9310 /**
9311 * Encoding of the output audio.
9312 */
9313 encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";
9314 /**
9315 * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..
9316 */
9317 container?: "none" | "wav" | "ogg";
9318 /**
9319 * The text content to be converted to speech
9320 */
9321 text: string;
9322 /**
9323 * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable
9324 */
9325 sample_rate?: number;
9326 /**
9327 * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.
9328 */
9329 bit_rate?: number;
9330}
9331/**
9332 * The generated audio in MP3 format
9333 */
9334type Ai_Cf_Deepgram_Aura_1_Output = string;
9335declare abstract class Base_Ai_Cf_Deepgram_Aura_1 {
9336 inputs: Ai_Cf_Deepgram_Aura_1_Input;
9337 postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output;
9338}
9339interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input {
9340 /**
9341 * Input text to translate. Can be a single string or a list of strings.
9342 */
9343 text: string | string[];
9344 /**
9345 * Target langauge to translate to
9346 */
9347 target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva";
9348}
9349interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output {
9350 /**
9351 * Translated texts
9352 */
9353 translations: string[];
9354}
9355declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B {
9356 inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input;
9357 postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output;
9358}
9359type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch;
9360interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt {
9361 /**
9362 * The input text prompt for the model to generate a response.
9363 */
9364 prompt: string;
9365 /**
9366 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
9367 */
9368 lora?: string;
9369 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode;
9370 /**
9371 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
9372 */
9373 raw?: boolean;
9374 /**
9375 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
9376 */
9377 stream?: boolean;
9378 /**
9379 * The maximum number of tokens to generate in the response.
9380 */
9381 max_tokens?: number;
9382 /**
9383 * Controls the randomness of the output; higher values produce more random results.
9384 */
9385 temperature?: number;
9386 /**
9387 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
9388 */
9389 top_p?: number;
9390 /**
9391 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
9392 */
9393 top_k?: number;
9394 /**
9395 * Random seed for reproducibility of the generation.
9396 */
9397 seed?: number;
9398 /**
9399 * Penalty for repeated tokens; higher values discourage repetition.
9400 */
9401 repetition_penalty?: number;
9402 /**
9403 * Decreases the likelihood of the model repeating the same lines verbatim.
9404 */
9405 frequency_penalty?: number;
9406 /**
9407 * Increases the likelihood of the model introducing new topics.
9408 */
9409 presence_penalty?: number;
9410}
9411interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode {
9412 type?: "json_object" | "json_schema";
9413 json_schema?: unknown;
9414}
9415interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages {
9416 /**
9417 * An array of message objects representing the conversation history.
9418 */
9419 messages: {
9420 /**
9421 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
9422 */
9423 role: string;
9424 content: string | {
9425 /**
9426 * Type of the content (text)
9427 */
9428 type?: string;
9429 /**
9430 * Text content
9431 */
9432 text?: string;
9433 }[];
9434 }[];
9435 functions?: {
9436 name: string;
9437 code: string;
9438 }[];
9439 /**
9440 * A list of tools available for the assistant to use.
9441 */
9442 tools?: ({
9443 /**
9444 * The name of the tool. More descriptive the better.
9445 */
9446 name: string;
9447 /**
9448 * A brief description of what the tool does.
9449 */
9450 description: string;
9451 /**
9452 * Schema defining the parameters accepted by the tool.
9453 */
9454 parameters: {
9455 /**
9456 * The type of the parameters object (usually 'object').
9457 */
9458 type: string;
9459 /**
9460 * List of required parameter names.
9461 */
9462 required?: string[];
9463 /**
9464 * Definitions of each parameter.
9465 */
9466 properties: {
9467 [k: string]: {
9468 /**
9469 * The data type of the parameter.
9470 */
9471 type: string;
9472 /**
9473 * A description of the expected parameter.
9474 */
9475 description: string;
9476 };
9477 };
9478 };
9479 } | {
9480 /**
9481 * Specifies the type of tool (e.g., 'function').
9482 */
9483 type: string;
9484 /**
9485 * Details of the function tool.
9486 */
9487 function: {
9488 /**
9489 * The name of the function.
9490 */
9491 name: string;
9492 /**
9493 * A brief description of what the function does.
9494 */
9495 description: string;
9496 /**
9497 * Schema defining the parameters accepted by the function.
9498 */
9499 parameters: {
9500 /**
9501 * The type of the parameters object (usually 'object').
9502 */
9503 type: string;
9504 /**
9505 * List of required parameter names.
9506 */
9507 required?: string[];
9508 /**
9509 * Definitions of each parameter.
9510 */
9511 properties: {
9512 [k: string]: {
9513 /**
9514 * The data type of the parameter.
9515 */
9516 type: string;
9517 /**
9518 * A description of the expected parameter.
9519 */
9520 description: string;
9521 };
9522 };
9523 };
9524 };
9525 })[];
9526 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1;
9527 /**
9528 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
9529 */
9530 raw?: boolean;
9531 /**
9532 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
9533 */
9534 stream?: boolean;
9535 /**
9536 * The maximum number of tokens to generate in the response.
9537 */
9538 max_tokens?: number;
9539 /**
9540 * Controls the randomness of the output; higher values produce more random results.
9541 */
9542 temperature?: number;
9543 /**
9544 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
9545 */
9546 top_p?: number;
9547 /**
9548 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
9549 */
9550 top_k?: number;
9551 /**
9552 * Random seed for reproducibility of the generation.
9553 */
9554 seed?: number;
9555 /**
9556 * Penalty for repeated tokens; higher values discourage repetition.
9557 */
9558 repetition_penalty?: number;
9559 /**
9560 * Decreases the likelihood of the model repeating the same lines verbatim.
9561 */
9562 frequency_penalty?: number;
9563 /**
9564 * Increases the likelihood of the model introducing new topics.
9565 */
9566 presence_penalty?: number;
9567}
9568interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 {
9569 type?: "json_object" | "json_schema";
9570 json_schema?: unknown;
9571}
9572interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch {
9573 requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[];
9574}
9575interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 {
9576 /**
9577 * The input text prompt for the model to generate a response.
9578 */
9579 prompt: string;
9580 /**
9581 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
9582 */
9583 lora?: string;
9584 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2;
9585 /**
9586 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
9587 */
9588 raw?: boolean;
9589 /**
9590 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
9591 */
9592 stream?: boolean;
9593 /**
9594 * The maximum number of tokens to generate in the response.
9595 */
9596 max_tokens?: number;
9597 /**
9598 * Controls the randomness of the output; higher values produce more random results.
9599 */
9600 temperature?: number;
9601 /**
9602 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
9603 */
9604 top_p?: number;
9605 /**
9606 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
9607 */
9608 top_k?: number;
9609 /**
9610 * Random seed for reproducibility of the generation.
9611 */
9612 seed?: number;
9613 /**
9614 * Penalty for repeated tokens; higher values discourage repetition.
9615 */
9616 repetition_penalty?: number;
9617 /**
9618 * Decreases the likelihood of the model repeating the same lines verbatim.
9619 */
9620 frequency_penalty?: number;
9621 /**
9622 * Increases the likelihood of the model introducing new topics.
9623 */
9624 presence_penalty?: number;
9625}
9626interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 {
9627 type?: "json_object" | "json_schema";
9628 json_schema?: unknown;
9629}
9630interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 {
9631 /**
9632 * An array of message objects representing the conversation history.
9633 */
9634 messages: {
9635 /**
9636 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
9637 */
9638 role: string;
9639 content: string | {
9640 /**
9641 * Type of the content (text)
9642 */
9643 type?: string;
9644 /**
9645 * Text content
9646 */
9647 text?: string;
9648 }[];
9649 }[];
9650 functions?: {
9651 name: string;
9652 code: string;
9653 }[];
9654 /**
9655 * A list of tools available for the assistant to use.
9656 */
9657 tools?: ({
9658 /**
9659 * The name of the tool. More descriptive the better.
9660 */
9661 name: string;
9662 /**
9663 * A brief description of what the tool does.
9664 */
9665 description: string;
9666 /**
9667 * Schema defining the parameters accepted by the tool.
9668 */
9669 parameters: {
9670 /**
9671 * The type of the parameters object (usually 'object').
9672 */
9673 type: string;
9674 /**
9675 * List of required parameter names.
9676 */
9677 required?: string[];
9678 /**
9679 * Definitions of each parameter.
9680 */
9681 properties: {
9682 [k: string]: {
9683 /**
9684 * The data type of the parameter.
9685 */
9686 type: string;
9687 /**
9688 * A description of the expected parameter.
9689 */
9690 description: string;
9691 };
9692 };
9693 };
9694 } | {
9695 /**
9696 * Specifies the type of tool (e.g., 'function').
9697 */
9698 type: string;
9699 /**
9700 * Details of the function tool.
9701 */
9702 function: {
9703 /**
9704 * The name of the function.
9705 */
9706 name: string;
9707 /**
9708 * A brief description of what the function does.
9709 */
9710 description: string;
9711 /**
9712 * Schema defining the parameters accepted by the function.
9713 */
9714 parameters: {
9715 /**
9716 * The type of the parameters object (usually 'object').
9717 */
9718 type: string;
9719 /**
9720 * List of required parameter names.
9721 */
9722 required?: string[];
9723 /**
9724 * Definitions of each parameter.
9725 */
9726 properties: {
9727 [k: string]: {
9728 /**
9729 * The data type of the parameter.
9730 */
9731 type: string;
9732 /**
9733 * A description of the expected parameter.
9734 */
9735 description: string;
9736 };
9737 };
9738 };
9739 };
9740 })[];
9741 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3;
9742 /**
9743 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
9744 */
9745 raw?: boolean;
9746 /**
9747 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
9748 */
9749 stream?: boolean;
9750 /**
9751 * The maximum number of tokens to generate in the response.
9752 */
9753 max_tokens?: number;
9754 /**
9755 * Controls the randomness of the output; higher values produce more random results.
9756 */
9757 temperature?: number;
9758 /**
9759 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.
9760 */
9761 top_p?: number;
9762 /**
9763 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.
9764 */
9765 top_k?: number;
9766 /**
9767 * Random seed for reproducibility of the generation.
9768 */
9769 seed?: number;
9770 /**
9771 * Penalty for repeated tokens; higher values discourage repetition.
9772 */
9773 repetition_penalty?: number;
9774 /**
9775 * Decreases the likelihood of the model repeating the same lines verbatim.
9776 */
9777 frequency_penalty?: number;
9778 /**
9779 * Increases the likelihood of the model introducing new topics.
9780 */
9781 presence_penalty?: number;
9782}
9783interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 {
9784 type?: "json_object" | "json_schema";
9785 json_schema?: unknown;
9786}
9787type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse;
9788interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response {
9789 /**
9790 * Unique identifier for the completion
9791 */
9792 id?: string;
9793 /**
9794 * Object type identifier
9795 */
9796 object?: "chat.completion";
9797 /**
9798 * Unix timestamp of when the completion was created
9799 */
9800 created?: number;
9801 /**
9802 * Model used for the completion
9803 */
9804 model?: string;
9805 /**
9806 * List of completion choices
9807 */
9808 choices?: {
9809 /**
9810 * Index of the choice in the list
9811 */
9812 index?: number;
9813 /**
9814 * The message generated by the model
9815 */
9816 message?: {
9817 /**
9818 * Role of the message author
9819 */
9820 role: string;
9821 /**
9822 * The content of the message
9823 */
9824 content: string;
9825 /**
9826 * Internal reasoning content (if available)
9827 */
9828 reasoning_content?: string;
9829 /**
9830 * Tool calls made by the assistant
9831 */
9832 tool_calls?: {
9833 /**
9834 * Unique identifier for the tool call
9835 */
9836 id: string;
9837 /**
9838 * Type of tool call
9839 */
9840 type: "function";
9841 function: {
9842 /**
9843 * Name of the function to call
9844 */
9845 name: string;
9846 /**
9847 * JSON string of arguments for the function
9848 */
9849 arguments: string;
9850 };
9851 }[];
9852 };
9853 /**
9854 * Reason why the model stopped generating
9855 */
9856 finish_reason?: string;
9857 /**
9858 * Stop reason (may be null)
9859 */
9860 stop_reason?: string | null;
9861 /**
9862 * Log probabilities (if requested)
9863 */
9864 logprobs?: {} | null;
9865 }[];
9866 /**
9867 * Usage statistics for the inference request
9868 */
9869 usage?: {
9870 /**
9871 * Total number of tokens in input
9872 */
9873 prompt_tokens?: number;
9874 /**
9875 * Total number of tokens in output
9876 */
9877 completion_tokens?: number;
9878 /**
9879 * Total number of input and output tokens
9880 */
9881 total_tokens?: number;
9882 };
9883 /**
9884 * Log probabilities for the prompt (if requested)
9885 */
9886 prompt_logprobs?: {} | null;
9887}
9888interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response {
9889 /**
9890 * Unique identifier for the completion
9891 */
9892 id?: string;
9893 /**
9894 * Object type identifier
9895 */
9896 object?: "text_completion";
9897 /**
9898 * Unix timestamp of when the completion was created
9899 */
9900 created?: number;
9901 /**
9902 * Model used for the completion
9903 */
9904 model?: string;
9905 /**
9906 * List of completion choices
9907 */
9908 choices?: {
9909 /**
9910 * Index of the choice in the list
9911 */
9912 index: number;
9913 /**
9914 * The generated text completion
9915 */
9916 text: string;
9917 /**
9918 * Reason why the model stopped generating
9919 */
9920 finish_reason: string;
9921 /**
9922 * Stop reason (may be null)
9923 */
9924 stop_reason?: string | null;
9925 /**
9926 * Log probabilities (if requested)
9927 */
9928 logprobs?: {} | null;
9929 /**
9930 * Log probabilities for the prompt (if requested)
9931 */
9932 prompt_logprobs?: {} | null;
9933 }[];
9934 /**
9935 * Usage statistics for the inference request
9936 */
9937 usage?: {
9938 /**
9939 * Total number of tokens in input
9940 */
9941 prompt_tokens?: number;
9942 /**
9943 * Total number of tokens in output
9944 */
9945 completion_tokens?: number;
9946 /**
9947 * Total number of input and output tokens
9948 */
9949 total_tokens?: number;
9950 };
9951}
9952interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse {
9953 /**
9954 * The async request id that can be used to obtain the results.
9955 */
9956 request_id?: string;
9957}
9958declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It {
9959 inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input;
9960 postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output;
9961}
9962interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input {
9963 /**
9964 * Input text to embed. Can be a single string or a list of strings.
9965 */
9966 text: string | string[];
9967}
9968interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output {
9969 /**
9970 * Embedding vectors, where each vector is a list of floats.
9971 */
9972 data: number[][];
9973 /**
9974 * Shape of the embedding data as [number_of_embeddings, embedding_dimension].
9975 *
9976 * @minItems 2
9977 * @maxItems 2
9978 */
9979 shape: [
9980 number,
9981 number
9982 ];
9983}
9984declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B {
9985 inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input;
9986 postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output;
9987}
9988interface Ai_Cf_Deepgram_Flux_Input {
9989 /**
9990 * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM.
9991 */
9992 encoding: "linear16";
9993 /**
9994 * Sample rate of the audio stream in Hz.
9995 */
9996 sample_rate: string;
9997 /**
9998 * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9.
9999 */
10000 eager_eot_threshold?: string;
10001 /**
10002 * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9.
10003 */
10004 eot_threshold?: string;
10005 /**
10006 * A turn will be finished when this much time has passed after speech, regardless of EOT confidence.
10007 */
10008 eot_timeout_ms?: string;
10009 /**
10010 * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms.
10011 */
10012 keyterm?: string;
10013 /**
10014 * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip
10015 */
10016 mip_opt_out?: "true" | "false";
10017 /**
10018 * Label your requests for the purpose of identification during usage reporting
10019 */
10020 tag?: string;
10021}
10022/**
10023 * Output will be returned as websocket messages.
10024 */
10025interface Ai_Cf_Deepgram_Flux_Output {
10026 /**
10027 * The unique identifier of the request (uuid)
10028 */
10029 request_id?: string;
10030 /**
10031 * Starts at 0 and increments for each message the server sends to the client.
10032 */
10033 sequence_id?: number;
10034 /**
10035 * The type of event being reported.
10036 */
10037 event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn";
10038 /**
10039 * The index of the current turn
10040 */
10041 turn_index?: number;
10042 /**
10043 * Start time in seconds of the audio range that was transcribed
10044 */
10045 audio_window_start?: number;
10046 /**
10047 * End time in seconds of the audio range that was transcribed
10048 */
10049 audio_window_end?: number;
10050 /**
10051 * Text that was said over the course of the current turn
10052 */
10053 transcript?: string;
10054 /**
10055 * The words in the transcript
10056 */
10057 words?: {
10058 /**
10059 * The individual punctuated, properly-cased word from the transcript
10060 */
10061 word: string;
10062 /**
10063 * Confidence that this word was transcribed correctly
10064 */
10065 confidence: number;
10066 }[];
10067 /**
10068 * Confidence that no more speech is coming in this turn
10069 */
10070 end_of_turn_confidence?: number;
10071}
10072declare abstract class Base_Ai_Cf_Deepgram_Flux {
10073 inputs: Ai_Cf_Deepgram_Flux_Input;
10074 postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output;
10075}
10076interface Ai_Cf_Deepgram_Aura_2_En_Input {
10077 /**
10078 * Speaker used to produce the audio.
10079 */
10080 speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus";
10081 /**
10082 * Encoding of the output audio.
10083 */
10084 encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";
10085 /**
10086 * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..
10087 */
10088 container?: "none" | "wav" | "ogg";
10089 /**
10090 * The text content to be converted to speech
10091 */
10092 text: string;
10093 /**
10094 * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable
10095 */
10096 sample_rate?: number;
10097 /**
10098 * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.
10099 */
10100 bit_rate?: number;
10101}
10102/**
10103 * The generated audio in MP3 format
10104 */
10105type Ai_Cf_Deepgram_Aura_2_En_Output = string;
10106declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En {
10107 inputs: Ai_Cf_Deepgram_Aura_2_En_Input;
10108 postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output;
10109}
10110interface Ai_Cf_Deepgram_Aura_2_Es_Input {
10111 /**
10112 * Speaker used to produce the audio.
10113 */
10114 speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier";
10115 /**
10116 * Encoding of the output audio.
10117 */
10118 encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";
10119 /**
10120 * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..
10121 */
10122 container?: "none" | "wav" | "ogg";
10123 /**
10124 * The text content to be converted to speech
10125 */
10126 text: string;
10127 /**
10128 * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable
10129 */
10130 sample_rate?: number;
10131 /**
10132 * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.
10133 */
10134 bit_rate?: number;
10135}
10136/**
10137 * The generated audio in MP3 format
10138 */
10139type Ai_Cf_Deepgram_Aura_2_Es_Output = string;
10140declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es {
10141 inputs: Ai_Cf_Deepgram_Aura_2_Es_Input;
10142 postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output;
10143}
10144interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input {
10145 multipart: {
10146 body?: object;
10147 contentType?: string;
10148 };
10149}
10150interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output {
10151 /**
10152 * Generated image as Base64 string.
10153 */
10154 image?: string;
10155}
10156declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev {
10157 inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input;
10158 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output;
10159}
10160interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input {
10161 multipart: {
10162 body?: object;
10163 contentType?: string;
10164 };
10165}
10166interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output {
10167 /**
10168 * Generated image as Base64 string.
10169 */
10170 image?: string;
10171}
10172declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B {
10173 inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input;
10174 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output;
10175}
10176interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input {
10177 multipart: {
10178 body?: object;
10179 contentType?: string;
10180 };
10181}
10182interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output {
10183 /**
10184 * Generated image as Base64 string.
10185 */
10186 image?: string;
10187}
10188declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B {
10189 inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input;
10190 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output;
10191}
10192declare abstract class Base_Ai_Cf_Zai_Org_Glm_4_7_Flash {
10193 inputs: ChatCompletionsInput;
10194 postProcessedOutputs: ChatCompletionsOutput;
10195}
10196declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 {
10197 inputs: ChatCompletionsInput;
10198 postProcessedOutputs: ChatCompletionsOutput;
10199}
10200declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_6 {
10201 inputs: ChatCompletionsInput;
10202 postProcessedOutputs: ChatCompletionsOutput;
10203}
10204declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B {
10205 inputs: ChatCompletionsInput;
10206 postProcessedOutputs: ChatCompletionsOutput;
10207}
10208declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT {
10209 inputs: ChatCompletionsInput;
10210 postProcessedOutputs: ChatCompletionsOutput;
10211}
10212declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_7_Code {
10213 inputs: ChatCompletionsInput;
10214 postProcessedOutputs: ChatCompletionsOutput;
10215}
10216declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_2 {
10217 inputs: ChatCompletionsInput;
10218 postProcessedOutputs: ChatCompletionsOutput;
10219}
10220interface Ai_Cf_Moondream_Moondream3_1_9B_A2B_Input {
10221 /**
10222 * Which Moondream skill to run.
10223 */
10224 task?: "query" | "caption" | "point" | "detect";
10225 /**
10226 * Input image as a public HTTPS URL or base64 data URI. Optional for `query`; required for `caption`, `point`, and `detect`.
10227 */
10228 image?: string;
10229 /**
10230 * Question for the `query` task.
10231 */
10232 question?: string;
10233 /**
10234 * Caption length for the `caption` task.
10235 */
10236 caption_length?: "short" | "normal" | "long";
10237 /**
10238 * Object phrase to locate for `point` and `detect` tasks (e.g. 'person wearing a red shirt').
10239 */
10240 target?: string;
10241 /**
10242 * Enable reasoning trace for the `query` task.
10243 */
10244 reasoning?: boolean;
10245 /**
10246 * Sampling temperature.
10247 */
10248 temperature?: number;
10249 /**
10250 * Top-p (nucleus) sampling.
10251 */
10252 top_p?: number;
10253 /**
10254 * Max tokens to generate for `query` and `caption`.
10255 */
10256 max_tokens?: number;
10257 /**
10258 * Max objects to return for `point` and `detect`.
10259 */
10260 max_objects?: number;
10261 /**
10262 * Return incremental tokens for `query` and `caption`. `point` and `detect` do not support streaming.
10263 */
10264 stream?: boolean;
10265}
10266interface Ai_Cf_Moondream_Moondream3_1_9B_A2B_Output {
10267 /**
10268 * Reason the generation finished.
10269 */
10270 finish_reason: string;
10271 metrics: {
10272 /**
10273 * Number of input tokens consumed.
10274 */
10275 input_tokens: number;
10276 /**
10277 * Number of output tokens generated.
10278 */
10279 output_tokens: number;
10280 /**
10281 * Prefill time in milliseconds.
10282 */
10283 prefill_time_ms: number;
10284 /**
10285 * Decode time in milliseconds.
10286 */
10287 decode_time_ms: number;
10288 /**
10289 * Time to first token in milliseconds.
10290 */
10291 ttft_ms: number;
10292 };
10293 /**
10294 * Answer text for the `query` task. Null for other tasks.
10295 */
10296 answer?: string;
10297 /**
10298 * Caption text for the `caption` task. Null for other tasks.
10299 */
10300 caption?: string;
10301 /**
10302 * Located points for the `point` task. Null for other tasks.
10303 */
10304 points?: {
10305 /**
10306 * X coordinate.
10307 */
10308 x: number;
10309 /**
10310 * Y coordinate.
10311 */
10312 y: number;
10313 }[];
10314 /**
10315 * Detected bounding boxes for the `detect` task. Null for other tasks.
10316 */
10317 objects?: {
10318 /**
10319 * Minimum X coordinate.
10320 */
10321 x_min: number;
10322 /**
10323 * Minimum Y coordinate.
10324 */
10325 y_min: number;
10326 /**
10327 * Maximum X coordinate.
10328 */
10329 x_max: number;
10330 /**
10331 * Maximum Y coordinate.
10332 */
10333 y_max: number;
10334 }[];
10335 /**
10336 * Reasoning trace for the `query` task when reasoning=true. Null otherwise.
10337 */
10338 reasoning?: {
10339 /**
10340 * Reasoning text.
10341 */
10342 text: string;
10343 /**
10344 * Grounding information.
10345 */
10346 grounding?: {}[];
10347 };
10348}
10349declare abstract class Base_Ai_Cf_Moondream_Moondream3_1_9B_A2B {
10350 inputs: Ai_Cf_Moondream_Moondream3_1_9B_A2B_Input;
10351 postProcessedOutputs: Ai_Cf_Moondream_Moondream3_1_9B_A2B_Output;
10352}
10353declare abstract class Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Flash_0731 {
10354 inputs: ChatCompletionsInput;
10355 postProcessedOutputs: ChatCompletionsOutput;
10356}
10357declare abstract class Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Pro_0813 {
10358 inputs: ChatCompletionsInput;
10359 postProcessedOutputs: ChatCompletionsOutput;
10360}
10361declare abstract class Base_Ai_Cf_Qwen_Qwen3_8_27B {
10362 inputs: ChatCompletionsInput;
10363 postProcessedOutputs: ChatCompletionsOutput;
10364}
10365declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_3_Flash {
10366 inputs: ChatCompletionsInput;
10367 postProcessedOutputs: ChatCompletionsOutput;
10368}
10369interface AiModels {
10370 "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification;
10371 "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage;
10372 "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage;
10373 "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage;
10374 "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage;
10375 "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage;
10376 "@cf/myshell-ai/melotts": BaseAiTextToSpeech;
10377 "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings;
10378 "@cf/microsoft/resnet-50": BaseAiImageClassification;
10379 "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration;
10380 "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration;
10381 "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration;
10382 "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration;
10383 "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration;
10384 "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration;
10385 "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration;
10386 "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration;
10387 "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration;
10388 "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration;
10389 "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration;
10390 "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration;
10391 "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration;
10392 "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration;
10393 "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration;
10394 "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration;
10395 "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration;
10396 "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration;
10397 "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration;
10398 "@cf/microsoft/phi-2": BaseAiTextGeneration;
10399 "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration;
10400 "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration;
10401 "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration;
10402 "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration;
10403 "@hf/google/gemma-7b-it": BaseAiTextGeneration;
10404 "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration;
10405 "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration;
10406 "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration;
10407 "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration;
10408 "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration;
10409 "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration;
10410 "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration;
10411 "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration;
10412 "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration;
10413 "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration;
10414 "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration;
10415 "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration;
10416 "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration;
10417 "@cf/facebook/bart-large-cnn": BaseAiSummarization;
10418 "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText;
10419 "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5;
10420 "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper;
10421 "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B;
10422 "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5;
10423 "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5;
10424 "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M;
10425 "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En;
10426 "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo;
10427 "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3;
10428 "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell;
10429 "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct;
10430 "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast;
10431 "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B;
10432 "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base;
10433 "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct;
10434 "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B;
10435 "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct;
10436 "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It;
10437 "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct;
10438 "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8;
10439 "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3;
10440 "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B;
10441 "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2;
10442 "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B;
10443 "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B;
10444 "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0;
10445 "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin;
10446 "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1;
10447 "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B;
10448 "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It;
10449 "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B;
10450 "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux;
10451 "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En;
10452 "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es;
10453 "@cf/black-forest-labs/flux-2-dev": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev;
10454 "@cf/black-forest-labs/flux-2-klein-4b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B;
10455 "@cf/black-forest-labs/flux-2-klein-9b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B;
10456 "@cf/zai-org/glm-4.7-flash": Base_Ai_Cf_Zai_Org_Glm_4_7_Flash;
10457 "@cf/moonshotai/kimi-k2.5": Base_Ai_Cf_Moonshotai_Kimi_K2_5;
10458 "@cf/moonshotai/kimi-k2.6": Base_Ai_Cf_Moonshotai_Kimi_K2_6;
10459 "@cf/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B;
10460 "@cf/google/gemma-4-26b-a4b-it": Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT;
10461 "@cf/moonshotai/kimi-k2.7-code": Base_Ai_Cf_Moonshotai_Kimi_K2_7_Code;
10462 "@cf/zai-org/glm-5.2": Base_Ai_Cf_Zai_Org_Glm_5_2;
10463 "@cf/moondream/moondream3.1-9B-A2B": Base_Ai_Cf_Moondream_Moondream3_1_9B_A2B;
10464 "@cf/deepseek-ai/deepseek-v4-flash-0731": Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Flash_0731;
10465 "@cf/deepseek-ai/deepseek-v4-pro-0813": Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Pro_0813;
10466 "@cf/qwen/qwen3.8-27b": Base_Ai_Cf_Qwen_Qwen3_8_27B;
10467 "@cf/zai-org/glm-5.3-flash": Base_Ai_Cf_Zai_Org_Glm_5_3_Flash;
10468}
10469type AiOptions = {
10470 /**
10471 * Send requests as an asynchronous batch job, only works for supported models
10472 * https://developers.cloudflare.com/workers-ai/features/batch-api
10473 */
10474 queueRequest?: boolean;
10475 /**
10476 * Establish websocket connections, only works for supported models
10477 */
10478 websocket?: boolean;
10479 /**
10480 * Tag your requests to group and view them in Cloudflare dashboard.
10481 *
10482 * Rules:
10483 * Tags must only contain letters, numbers, and the symbols: : - . / @
10484 * Each tag can have maximum 50 characters.
10485 * Maximum 5 tags are allowed each request.
10486 * Duplicate tags will removed.
10487 */
10488 tags?: string[];
10489 gateway?: GatewayOptions;
10490 returnRawResponse?: boolean;
10491 prefix?: string;
10492 extraHeaders?: object;
10493 signal?: AbortSignal;
10494};
10495type AiModelsSearchParams = {
10496 author?: string;
10497 hide_experimental?: boolean;
10498 page?: number;
10499 per_page?: number;
10500 search?: string;
10501 source?: number;
10502 task?: string;
10503};
10504type AiModelsSearchObject = {
10505 id: string;
10506 source: number;
10507 name: string;
10508 description: string;
10509 task: {
10510 id: string;
10511 name: string;
10512 description: string;
10513 };
10514 tags: string[];
10515 properties: {
10516 property_id: string;
10517 value: string;
10518 }[];
10519};
10520type ChatCompletionsBase = ChatCompletionsMessagesInput;
10521type ChatCompletionsInput = ChatCompletionsMessagesInput;
10522interface InferenceUpstreamError extends Error {
10523}
10524interface AiInternalError extends Error {
10525}
10526type AiModelListType = Record<string, any>;
10527type AiAsyncBatchResponse = {
10528 request_id: string;
10529};
10530declare abstract class Ai<AiModelList extends AiModelListType = AiModels> {
10531 aiGatewayLogId: string | null;
10532 gateway(gatewayId: string): AiGateway;
10533 /**
10534 * @deprecated Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead.
10535 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10536 */
10537 aiSearch(): AiSearchNamespace;
10538 /**
10539 * @deprecated AutoRAG has been replaced by AI Search.
10540 * Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead.
10541 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10542 *
10543 * @param autoragId Instance ID
10544 */
10545 autorag(autoragId: string): AutoRAG;
10546 // Batch request
10547 run<Name extends keyof AiModelList>(model: Name, inputs: {
10548 requests: AiModelList[Name]['inputs'][];
10549 }, options: AiOptions & {
10550 queueRequest: true;
10551 }): Promise<AiAsyncBatchResponse>;
10552 // Raw response
10553 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & {
10554 returnRawResponse: true;
10555 }): Promise<Response>;
10556 // WebSocket
10557 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & {
10558 websocket: true;
10559 }): Promise<Response>;
10560 // Streaming
10561 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'] & {
10562 stream: true;
10563 }, options?: AiOptions): Promise<ReadableStream>;
10564 // Normal (default) - known model
10565 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options?: AiOptions): Promise<AiModelList[Name]['postProcessedOutputs']>;
10566 // Unknown model (fallback).
10567 //
10568 // The `Exclude<..., keyof AiModelList>` constraint forces TypeScript to
10569 // route any model name that is a literal key of `AiModelList` to one of
10570 // the known-model overloads above (so input/output mismatches surface as
10571 // type errors rather than silently falling back to `Record<string, unknown>`).
10572 // Names that aren't in `AiModelList` โ€” e.g. third-party gateway models
10573 // like `"google/nano-banana"` โ€” still hit this overload.
10574 run<Model extends string>(model: Model extends keyof AiModelList ? never : Model, inputs: Record<string, unknown>, options?: AiOptions): Promise<Record<string, unknown>>;
10575 models(params?: AiModelsSearchParams): Promise<AiModelsSearchObject[]>;
10576 toMarkdown(): ToMarkdownService;
10577 toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise<ConversionResponse[]>;
10578 toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise<ConversionResponse>;
10579}
10580type GatewayRetries = {
10581 maxAttempts?: 1 | 2 | 3 | 4 | 5;
10582 retryDelayMs?: number;
10583 backoff?: 'constant' | 'linear' | 'exponential';
10584};
10585type GatewayOptions = {
10586 id: string;
10587 cacheKey?: string;
10588 cacheTtl?: number;
10589 skipCache?: boolean;
10590 metadata?: Record<string, number | string | boolean | null | bigint>;
10591 collectLog?: boolean;
10592 eventId?: string;
10593 requestTimeoutMs?: number;
10594 retries?: GatewayRetries;
10595};
10596type UniversalGatewayOptions = Exclude<GatewayOptions, 'id'> & {
10597 /**
10598 ** @deprecated
10599 */
10600 id?: string;
10601};
10602type AiGatewayPatchLog = {
10603 score?: number | null;
10604 feedback?: -1 | 1 | null;
10605 metadata?: Record<string, number | string | boolean | null | bigint> | null;
10606};
10607type AiGatewayLog = {
10608 id: string;
10609 provider: string;
10610 model: string;
10611 model_type?: string;
10612 path: string;
10613 duration: number;
10614 request_type?: string;
10615 request_content_type?: string;
10616 status_code: number;
10617 response_content_type?: string;
10618 success: boolean;
10619 cached: boolean;
10620 tokens_in?: number;
10621 tokens_out?: number;
10622 metadata?: Record<string, number | string | boolean | null | bigint>;
10623 step?: number;
10624 cost?: number;
10625 custom_cost?: boolean;
10626 request_size: number;
10627 request_head?: string;
10628 request_head_complete: boolean;
10629 response_size: number;
10630 response_head?: string;
10631 response_head_complete: boolean;
10632 created_at: Date;
10633};
10634type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly';
10635type AIGatewayHeaders = {
10636 'cf-aig-metadata': Record<string, number | string | boolean | null | bigint> | string;
10637 'cf-aig-custom-cost': {
10638 per_token_in?: number;
10639 per_token_out?: number;
10640 } | {
10641 total_cost?: number;
10642 } | string;
10643 'cf-aig-cache-ttl': number | string;
10644 'cf-aig-skip-cache': boolean | string;
10645 'cf-aig-cache-key': string;
10646 'cf-aig-event-id': string;
10647 'cf-aig-request-timeout': number | string;
10648 'cf-aig-max-attempts': number | string;
10649 'cf-aig-retry-delay': number | string;
10650 'cf-aig-backoff': string;
10651 'cf-aig-collect-log': boolean | string;
10652 Authorization: string;
10653 'Content-Type': string;
10654 [key: string]: string | number | boolean | object;
10655};
10656type AIGatewayUniversalRequest = {
10657 provider: AIGatewayProviders | string; // eslint-disable-line
10658 endpoint: string;
10659 headers: Partial<AIGatewayHeaders>;
10660 query: unknown;
10661};
10662interface AiGatewayInternalError extends Error {
10663}
10664interface AiGatewayLogNotFound extends Error {
10665}
10666declare abstract class AiGateway {
10667 patchLog(logId: string, data: AiGatewayPatchLog): Promise<void>;
10668 getLog(logId: string): Promise<AiGatewayLog>;
10669 run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: {
10670 gateway?: UniversalGatewayOptions;
10671 extraHeaders?: object;
10672 signal?: AbortSignal;
10673 }): Promise<Response>;
10674 getUrl(provider?: AIGatewayProviders | string): Promise<string>; // eslint-disable-line
10675}
10676// Copyright (c) 2022-2025 Cloudflare, Inc.
10677// Licensed under the Apache 2.0 license found in the LICENSE file or at:
10678// https://opensource.org/licenses/Apache-2.0
10679/**
10680 * Artifacts โ€” Git-compatible file storage on Cloudflare Workers.
10681 *
10682 * Provides programmatic access to create, manage, and fork repositories,
10683 * and to issue and revoke scoped access tokens.
10684 */
10685/** Information about a repository. */
10686interface ArtifactsRepoInfo {
10687 /** Unique repository ID. */
10688 id: string;
10689 /** Repository name. */
10690 name: string;
10691 /** Repository description, or null if not set. */
10692 description: string | null;
10693 /** Default branch name (e.g. "main"). */
10694 defaultBranch: string;
10695 /** ISO 8601 creation timestamp. */
10696 createdAt: string;
10697 /** ISO 8601 last-updated timestamp. */
10698 updatedAt: string;
10699 /** ISO 8601 timestamp of the last push, or null if never pushed. */
10700 lastPushAt: string | null;
10701 /** Fork source (e.g. "github:owner/repo", "artifacts:namespace/repo"), or null if not a fork. */
10702 source: string | null;
10703 /** Whether the repository is read-only. */
10704 readOnly: boolean;
10705 /** HTTPS git remote URL. */
10706 remote: string;
10707}
10708/** Result of creating a repository โ€” includes the initial access token. */
10709interface ArtifactsCreateRepoResult {
10710 /** Unique repository ID. */
10711 id: string;
10712 /** Repository name. */
10713 name: string;
10714 /** Repository description, or null if not set. */
10715 description: string | null;
10716 /** Default branch name. */
10717 defaultBranch: string;
10718 /** HTTPS git remote URL. */
10719 remote: string;
10720 /** Plaintext access token (only returned at creation time). */
10721 token: string;
10722 /** ISO 8601 token expiry timestamp. */
10723 tokenExpiresAt: string;
10724}
10725/** Paginated list of repositories. */
10726interface ArtifactsRepoListResult {
10727 /** Repositories in this page (without the `remote` field). */
10728 repos: Omit<ArtifactsRepoInfo, 'remote'>[];
10729 /** Total number of repositories in the namespace. */
10730 total: number;
10731 /** Cursor for the next page, if there are more results. */
10732 cursor?: string;
10733}
10734/** Result of creating an access token. */
10735interface ArtifactsCreateTokenResult {
10736 /** Unique token ID. */
10737 id: string;
10738 /** Plaintext token (only returned at creation time). */
10739 plaintext: string;
10740 /** Token scope: "read" or "write". */
10741 scope: 'read' | 'write';
10742 /** ISO 8601 token expiry timestamp. */
10743 expiresAt: string;
10744}
10745/** Token metadata (no plaintext). */
10746interface ArtifactsTokenInfo {
10747 /** Unique token ID. */
10748 id: string;
10749 /** Token scope: "read" or "write". */
10750 scope: 'read' | 'write';
10751 /** Token state: "active", "expired", or "revoked". */
10752 state: 'active' | 'expired' | 'revoked';
10753 /** ISO 8601 creation timestamp. */
10754 createdAt: string;
10755 /** ISO 8601 expiry timestamp. */
10756 expiresAt: string;
10757}
10758/** Paginated list of tokens for a repository. */
10759interface ArtifactsTokenListResult {
10760 /** Tokens in this page. */
10761 tokens: ArtifactsTokenInfo[];
10762 /** Total number of tokens for the repository. */
10763 total: number;
10764}
10765/**
10766 * Handle for a single repository. Returned by Artifacts.get().
10767 *
10768 * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs.
10769 */
10770interface ArtifactsRepo extends ArtifactsRepoInfo {
10771 /**
10772 * Create an access token for this repo.
10773 * @param scope Token scope: "write" (default) or "read".
10774 * @param ttl Time-to-live in seconds (default 86400, min 60, max 31536000).
10775 * @throws {ArtifactsError} with code `INVALID_TTL` if ttl is out of range.
10776 */
10777 createToken(scope?: 'write' | 'read', ttl?: number): Promise<ArtifactsCreateTokenResult>;
10778 /** List tokens for this repo (metadata only, no plaintext). */
10779 listTokens(): Promise<ArtifactsTokenListResult>;
10780 /**
10781 * Revoke a token by plaintext or ID.
10782 * @param tokenOrId Plaintext token or token ID.
10783 * @returns true if revoked, false if not found.
10784 * @throws {ArtifactsError} with code `INVALID_INPUT` if tokenOrId is empty.
10785 */
10786 revokeToken(tokenOrId: string): Promise<boolean>;
10787 // โ”€โ”€ Fork โ”€โ”€
10788 /**
10789 * Fork this repo to a new repo.
10790 * @param name Target repository name.
10791 * @param opts Optional: description, readOnly flag, defaultBranchOnly (default true).
10792 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.
10793 * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists.
10794 * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if a fork is already running.
10795 */
10796 fork(name: string, opts?: {
10797 description?: string;
10798 readOnly?: boolean;
10799 defaultBranchOnly?: boolean;
10800 }): Promise<ArtifactsCreateRepoResult>;
10801}
10802// โ”€โ”€ Error types โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
10803/**
10804 * Error codes returned by Artifacts binding operations.
10805 *
10806 * Each code maps to a numeric code available on `ArtifactsError.numericCode`.
10807 */
10808type ArtifactsErrorCode = 'ALREADY_EXISTS' | 'NOT_FOUND' | 'IMPORT_IN_PROGRESS' | 'FORK_IN_PROGRESS' | 'INVALID_INPUT' | 'INVALID_REPO_NAME' | 'INVALID_TTL' | 'INVALID_URL' | 'REMOTE_AUTH_REQUIRED' | 'UPSTREAM_UNAVAILABLE' | 'MEMORY_LIMIT' | 'INTERNAL_ERROR';
10809/**
10810 * Error thrown by Artifacts binding operations.
10811 *
10812 * Uses a string `.code` discriminator following the Cloudflare platform
10813 * convention (StreamError, ImagesError, etc.). The `.numericCode` matches
10814 * the REST API `errors[].code` values.
10815 */
10816interface ArtifactsError extends Error {
10817 readonly name: 'ArtifactsError';
10818 /** String error code for programmatic matching. */
10819 readonly code: ArtifactsErrorCode;
10820 /** Numeric error code matching the REST API. */
10821 readonly numericCode: number;
10822}
10823// โ”€โ”€ Binding โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
10824/**
10825 * Artifacts binding โ€” namespace-level operations.
10826 *
10827 * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs.
10828 */
10829interface Artifacts {
10830 /**
10831 * Create a new repository with an initial access token.
10832 * @param name Repository name (alphanumeric, dots, hyphens, underscores).
10833 * @param opts Optional: readOnly flag, description, default branch name.
10834 * @returns Repo metadata with initial token.
10835 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.
10836 * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the repo already exists.
10837 */
10838 create(name: string, opts?: {
10839 readOnly?: boolean;
10840 description?: string;
10841 setDefaultBranch?: string;
10842 }): Promise<ArtifactsCreateRepoResult>;
10843 /**
10844 * Get a handle to an existing repository.
10845 * @param name Repository name.
10846 * @returns Repo handle.
10847 * @throws {ArtifactsError} with code `NOT_FOUND` if the repo does not exist.
10848 * @throws {ArtifactsError} with code `IMPORT_IN_PROGRESS` if the repo is still importing.
10849 * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if the repo is still forking.
10850 */
10851 get(name: string): Promise<ArtifactsRepo>;
10852 /**
10853 * Import a repository from an external git remote.
10854 * @param params Source URL and optional branch/depth, plus target name and options.
10855 * @returns Repo metadata with initial token.
10856 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if the target name is invalid.
10857 * @throws {ArtifactsError} with code `INVALID_INPUT` if the source URL is not valid HTTPS.
10858 * @throws {ArtifactsError} with code `INVALID_URL` if the source URL does not point to a git repository.
10859 * @throws {ArtifactsError} with code `REMOTE_AUTH_REQUIRED` if the remote requires authentication.
10860 * @throws {ArtifactsError} with code `NOT_FOUND` if the remote repository does not exist.
10861 * @throws {ArtifactsError} with code `UPSTREAM_UNAVAILABLE` if the remote cannot be reached.
10862 * @throws {ArtifactsError} with code `MEMORY_LIMIT` if the import exceeds service memory limits.
10863 * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists.
10864 */
10865 import(params: {
10866 source: {
10867 url: string;
10868 branch?: string;
10869 depth?: number;
10870 };
10871 target: {
10872 name: string;
10873 opts?: {
10874 description?: string;
10875 readOnly?: boolean;
10876 };
10877 };
10878 }): Promise<ArtifactsCreateRepoResult>;
10879 /**
10880 * List repositories with cursor-based pagination.
10881 * @param opts Optional: limit (1โ€“200, default 50), cursor for next page.
10882 */
10883 list(opts?: {
10884 limit?: number;
10885 cursor?: string;
10886 }): Promise<ArtifactsRepoListResult>;
10887 /**
10888 * Delete a repository and all associated tokens.
10889 * @param name Repository name.
10890 * @returns true if deleted, false if not found.
10891 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.
10892 */
10893 delete(name: string): Promise<boolean>;
10894}
10895/**
10896 * @deprecated Use the standalone AI Search Workers binding instead.
10897 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10898 */
10899interface AutoRAGInternalError extends Error {
10900}
10901/**
10902 * @deprecated Use the standalone AI Search Workers binding instead.
10903 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10904 */
10905interface AutoRAGNotFoundError extends Error {
10906}
10907/**
10908 * @deprecated Use the standalone AI Search Workers binding instead.
10909 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10910 */
10911interface AutoRAGUnauthorizedError extends Error {
10912}
10913/**
10914 * @deprecated Use the standalone AI Search Workers binding instead.
10915 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10916 */
10917interface AutoRAGNameNotSetError extends Error {
10918}
10919type ComparisonFilter = {
10920 key: string;
10921 type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte';
10922 value: string | number | boolean;
10923};
10924type CompoundFilter = {
10925 type: 'and' | 'or';
10926 filters: ComparisonFilter[];
10927};
10928/**
10929 * @deprecated Use the standalone AI Search Workers binding instead.
10930 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10931 */
10932type AutoRagSearchRequest = {
10933 query: string;
10934 filters?: CompoundFilter | ComparisonFilter;
10935 max_num_results?: number;
10936 ranking_options?: {
10937 ranker?: string;
10938 score_threshold?: number;
10939 };
10940 reranking?: {
10941 enabled?: boolean;
10942 model?: string;
10943 };
10944 rewrite_query?: boolean;
10945};
10946/**
10947 * @deprecated Use the standalone AI Search Workers binding instead.
10948 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10949 */
10950type AutoRagAiSearchRequest = AutoRagSearchRequest & {
10951 stream?: boolean;
10952 system_prompt?: string;
10953};
10954/**
10955 * @deprecated Use the standalone AI Search Workers binding instead.
10956 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10957 */
10958type AutoRagAiSearchRequestStreaming = Omit<AutoRagAiSearchRequest, 'stream'> & {
10959 stream: true;
10960};
10961/**
10962 * @deprecated Use the standalone AI Search Workers binding instead.
10963 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10964 */
10965type AutoRagSearchResponse = {
10966 object: 'vector_store.search_results.page';
10967 search_query: string;
10968 data: {
10969 file_id: string;
10970 filename: string;
10971 score: number;
10972 attributes: Record<string, string | number | boolean | null>;
10973 content: {
10974 type: 'text';
10975 text: string;
10976 }[];
10977 }[];
10978 has_more: boolean;
10979 next_page: string | null;
10980};
10981/**
10982 * @deprecated Use the standalone AI Search Workers binding instead.
10983 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10984 */
10985type AutoRagListResponse = {
10986 id: string;
10987 enable: boolean;
10988 type: string;
10989 source: string;
10990 vectorize_name: string;
10991 paused: boolean;
10992 status: string;
10993}[];
10994/**
10995 * @deprecated Use the standalone AI Search Workers binding instead.
10996 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10997 */
10998type AutoRagAiSearchResponse = AutoRagSearchResponse & {
10999 response: string;
11000};
11001/**
11002 * @deprecated Use the standalone AI Search Workers binding instead.
11003 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11004 */
11005declare abstract class AutoRAG {
11006 /**
11007 * @deprecated Use the standalone AI Search Workers binding instead.
11008 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11009 */
11010 list(): Promise<AutoRagListResponse>;
11011 /**
11012 * @deprecated Use the standalone AI Search Workers binding instead.
11013 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11014 */
11015 search(params: AutoRagSearchRequest): Promise<AutoRagSearchResponse>;
11016 /**
11017 * @deprecated Use the standalone AI Search Workers binding instead.
11018 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11019 */
11020 aiSearch(params: AutoRagAiSearchRequestStreaming): Promise<Response>;
11021 /**
11022 * @deprecated Use the standalone AI Search Workers binding instead.
11023 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11024 */
11025 aiSearch(params: AutoRagAiSearchRequest): Promise<AutoRagAiSearchResponse>;
11026 /**
11027 * @deprecated Use the standalone AI Search Workers binding instead.
11028 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11029 */
11030 aiSearch(params: AutoRagAiSearchRequest): Promise<AutoRagAiSearchResponse | Response>;
11031}
11032type BrowserRunLifecycleEvent = 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2';
11033type BrowserRunResourceType = 'document' | 'stylesheet' | 'image' | 'media' | 'font' | 'script' | 'texttrack' | 'xhr' | 'fetch' | 'prefetch' | 'eventsource' | 'websocket' | 'manifest' | 'signedexchange' | 'ping' | 'cspviolationreport' | 'preflight' | 'other';
11034/** Options fields shared by all quick actions. */
11035interface BrowserRunBaseOptions {
11036 /** Adds `<script>` tags into the page with the desired URL or content.
11037 * @see https://pptr.dev/api/puppeteer.frameaddscripttagoptions
11038 */
11039 addScriptTag?: Array<{
11040 content?: string;
11041 url?: string;
11042 type?: string;
11043 id?: string;
11044 }>;
11045 /** Adds `<link rel="stylesheet">` or `<style>` tags into the page.
11046 * @see https://pptr.dev/api/puppeteer.frameaddstyletagoptions
11047 */
11048 addStyleTag?: Array<{
11049 content?: string;
11050 url?: string;
11051 }>;
11052 /** Provide credentials for HTTP authentication. @see https://pptr.dev/api/puppeteer.credentials */
11053 authenticate?: {
11054 username: string;
11055 password: string;
11056 };
11057 /** Set cookies before navigating. @see https://pptr.dev/api/puppeteer.cookieparam */
11058 cookies?: Array<{
11059 name: string;
11060 value: string;
11061 url?: string;
11062 domain?: string;
11063 path?: string;
11064 secure?: boolean;
11065 httpOnly?: boolean;
11066 sameSite?: 'Strict' | 'Lax' | 'None';
11067 expires?: number;
11068 priority?: 'Low' | 'Medium' | 'High';
11069 sameParty?: boolean;
11070 sourceScheme?: 'Unset' | 'NonSecure' | 'Secure';
11071 sourcePort?: number;
11072 partitionKey?: string;
11073 }>;
11074 /** Emulate a specific CSS media type (e.g. `"screen"`, `"print"`). */
11075 emulateMediaType?: string;
11076 /** Navigation options. @see https://pptr.dev/api/puppeteer.gotooptions */
11077 gotoOptions?: {
11078 /** Navigation timeout in milliseconds (max 60 000). @default 30000 */
11079 timeout?: number;
11080 /** When to consider navigation complete. @default "domcontentloaded" */
11081 waitUntil?: BrowserRunLifecycleEvent | BrowserRunLifecycleEvent[];
11082 referer?: string;
11083 referrerPolicy?: string;
11084 };
11085 /** Block requests matching these regex patterns. Mutually exclusive with `allowRequestPattern`. */
11086 rejectRequestPattern?: string[];
11087 /** Only allow requests matching these regex patterns. Mutually exclusive with `rejectRequestPattern`. */
11088 allowRequestPattern?: string[];
11089 /** Block requests of these resource types. Mutually exclusive with `allowResourceTypes`. */
11090 rejectResourceTypes?: BrowserRunResourceType[];
11091 /** Only allow requests of these resource types. Mutually exclusive with `rejectResourceTypes`. */
11092 allowResourceTypes?: BrowserRunResourceType[];
11093 /** Additional HTTP headers sent with every request. */
11094 setExtraHTTPHeaders?: Record<string, string>;
11095 /** Whether JavaScript is enabled on the page. */
11096 setJavaScriptEnabled?: boolean;
11097 /** Override the default user agent string.
11098 * @default "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
11099 * */
11100 userAgent?: string;
11101 /** Set the browser viewport size.
11102 * @see https://pptr.dev/api/puppeteer.viewport
11103 * @default {width:1920,height:1080}
11104 * */
11105 viewport?: {
11106 width: number;
11107 height: number;
11108 deviceScaleFactor?: number;
11109 isMobile?: boolean;
11110 isLandscape?: boolean;
11111 hasTouch?: boolean;
11112 };
11113 /** Wait for a CSS selector to appear in the page before proceeding.
11114 * @see https://pptr.dev/api/puppeteer.waitforselectoroptions
11115 */
11116 waitForSelector?: {
11117 selector: string;
11118 hidden?: true;
11119 visible?: true;
11120 /** Timeout in milliseconds. Max 120000 */
11121 timeout?: number;
11122 };
11123 /** Wait for a fixed delay in milliseconds before proceeding. Max 120000 */
11124 waitForTimeout?: number;
11125 /** When true, continue on best-effort when awaited events fail or timeout. */
11126 bestAttempt?: boolean;
11127 /** Maximum duration in milliseconds for the browser action after page load. Max 120000 */
11128 actionTimeout?: number;
11129 /** Cache time to live in seconds (0-86400). Set to 0 to disable.
11130 * @default 5
11131 */
11132 cacheTTL?: number;
11133}
11134/**
11135 * Backend selection, mixed into the options of the quick actions that support it.
11136 * Deliberately not part of `BrowserRunBaseOptions`: `scrape`, `links` and `snapshot`
11137 * reject an alternate backend, so they must not accept the field.
11138 */
11139interface BrowserRunAlternateBackendOptions {
11140 /** Render with an alternate browser backend instead of the default one. */
11141 browser?: 'kitesurf';
11142}
11143/** Common options shared by all quick actions. Exactly one of `url` or `html` must be provided.*/
11144type BrowserRunCommonOptions = (BrowserRunBaseOptions & {
11145 /** URL to navigate to, e.g. `"https://example.com"`. */
11146 url: string;
11147}) | (BrowserRunBaseOptions & {
11148 /** Set the HTML content of the page directly. */
11149 html: string;
11150});
11151type BrowserRunPuppeteerScreenshotOptions = {
11152 /** @default "png" */
11153 type?: 'png' | 'jpeg' | 'webp';
11154 /** @default "binary" */
11155 encoding?: 'binary' | 'base64';
11156 quality?: number;
11157 fullPage?: boolean;
11158 clip?: {
11159 x: number;
11160 y: number;
11161 width: number;
11162 height: number;
11163 scale?: number;
11164 };
11165 omitBackground?: boolean;
11166 optimizeForSpeed?: boolean;
11167 captureBeyondViewport?: boolean;
11168 fromSurface?: boolean;
11169};
11170type BrowserRunScreenshotOptions = BrowserRunCommonOptions & {
11171 /** CSS selector of the element to screenshot. */
11172 selector?: string;
11173 /** When true, scroll the entire page before taking the screenshot. */
11174 scrollPage?: boolean;
11175 /** @see https://pptr.dev/api/puppeteer.screenshotoptions */
11176 screenshotOptions?: BrowserRunPuppeteerScreenshotOptions;
11177} & BrowserRunAlternateBackendOptions;
11178type BrowserRunPDFOptions = BrowserRunCommonOptions & {
11179 /** @see https://pptr.dev/api/puppeteer.pdfoptions */
11180 pdfOptions?: {
11181 /** @default 1 */
11182 scale?: number;
11183 /** @default false */
11184 displayHeaderFooter?: boolean;
11185 headerTemplate?: string;
11186 footerTemplate?: string;
11187 /** @default false */
11188 printBackground?: boolean;
11189 /** @default false */
11190 landscape?: boolean;
11191 pageRanges?: string;
11192 /** @default "letter" */
11193 format?: 'letter' | 'legal' | 'tabloid' | 'ledger' | 'a0' | 'a1' | 'a2' | 'a3' | 'a4' | 'a5' | 'a6';
11194 width?: string | number;
11195 height?: string | number;
11196 /** @default false */
11197 preferCSSPageSize?: boolean;
11198 margin?: {
11199 top?: string | number;
11200 right?: string | number;
11201 bottom?: string | number;
11202 left?: string | number;
11203 };
11204 /** @default false */
11205 omitBackground?: boolean;
11206 /** @default true */
11207 tagged?: boolean;
11208 /** @default false */
11209 outline?: boolean;
11210 /** @default 30000 */
11211 timeout?: number;
11212 };
11213} & BrowserRunAlternateBackendOptions;
11214type BrowserRunScrapeOptions = BrowserRunCommonOptions & {
11215 /** CSS selectors to scrape. At least one element is required. */
11216 elements: Array<{
11217 selector: string;
11218 }>;
11219};
11220type BrowserRunLinksOptions = BrowserRunCommonOptions & {
11221 /** When true, only return links that are visible on the page. @default false */
11222 visibleLinksOnly?: boolean;
11223 /** When true, exclude links pointing to external domains. @default false */
11224 excludeExternalLinks?: boolean;
11225};
11226type BrowserRunSnapshotFormat = 'content' | 'screenshot' | 'markdown' | 'accessibilityTree';
11227type BrowserRunSnapshotOptions = BrowserRunCommonOptions & {
11228 /** Which representations of the page to return. At least two distinct formats
11229 * are required; request a single format from its dedicated action instead.
11230 * @default ["content","screenshot"]
11231 */
11232 formats?: BrowserRunSnapshotFormat[];
11233 /** @see https://pptr.dev/api/puppeteer.screenshotoptions */
11234 screenshotOptions?: Omit<BrowserRunPuppeteerScreenshotOptions, 'encoding'>;
11235};
11236/** Options for the `accessibilityTree` quick action. */
11237type BrowserRunAccessibilityTreeOptions = BrowserRunCommonOptions & {
11238 /** When true, prune nodes that carry no semantic meaning, such as generic
11239 * containers. Defaults to true, or to false when `root` is set so that the
11240 * requested subtree is returned as-is.
11241 */
11242 interestingOnly?: boolean;
11243 /** CSS selector limiting the tree to the matching element's subtree.
11244 * A selector that matches nothing yields `accessibilityTree: null` with
11245 * HTTP 200; a malformed selector is an error.
11246 */
11247 root?: string;
11248} & BrowserRunAlternateBackendOptions;
11249interface BrowserRunJsonBaseOptions {
11250 /** Custom AI models to try in order. Max 3. Falls back to next on error. */
11251 custom_ai?: Array<{
11252 /** Model ID in `<provider>/<model_name>` format, e.g. `"workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast"`. */
11253 model: string;
11254 /** Bearer token. Not needed for workers-ai models. */
11255 authorization?: string;
11256 }>;
11257}
11258/**
11259 * Options for the `json` quick action.
11260 * At least one of `prompt` or `response_format` must be provided.
11261 */
11262type BrowserRunJsonOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions & BrowserRunJsonBaseOptions & ({
11263 /** Natural-language prompt describing what data to extract. */
11264 prompt: string;
11265 /** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */
11266 response_format?: AiTextGenerationResponseFormat;
11267} | {
11268 /** Natural-language prompt describing what data to extract. */
11269 prompt?: string;
11270 /** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */
11271 response_format: AiTextGenerationResponseFormat;
11272});
11273type BrowserRunContentOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions;
11274type BrowserRunMarkdownOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions;
11275type BrowserRunRedirectHop = {
11276 /** URL that returned the redirect. */
11277 url: string;
11278 /** HTTP status of the redirect. */
11279 status: number;
11280 /** Redirect response headers, including `location`. */
11281 headers: Record<string, string>;
11282};
11283type BrowserRunResponseMeta = {
11284 /** HTTP status code of the rendered page */
11285 status: number;
11286 /** Page title */
11287 title: string;
11288 /** Origin response headers, lowercased. Repeated headers are joined with a newline. Credential and transport-only headers that do not survive rendering are omitted. */
11289 headers?: Record<string, string>;
11290 /** URL that served the response, after any redirects the browser followed. */
11291 finalUrl?: string;
11292 /** HTTP redirects followed to reach `finalUrl`, oldest first. Omitted for direct navigation and for client-side redirects such as meta refresh. An empty array means redirects occurred but their intermediate responses could not be read. */
11293 redirectChain?: BrowserRunRedirectHop[];
11294};
11295/**
11296 * A node in the page's accessibility tree, as exposed to assistive technology.
11297 * `role` is the only field always present; the rest are populated when the
11298 * underlying element defines them.
11299 * @see https://pptr.dev/api/puppeteer.serializedaxnode
11300 */
11301interface BrowserRunSerializedAXNode {
11302 /** The ARIA role, e.g. `"button"`, `"heading"`, `"RootWebArea"`. */
11303 role: string;
11304 /** The `aria-autocomplete` value. */
11305 autocomplete?: string;
11306 /** Checked state of a checkbox, radio, or menu item. */
11307 checked?: boolean | 'mixed';
11308 /** Accessible description, typically from `aria-describedby` or `title`. */
11309 description?: string;
11310 disabled?: boolean;
11311 expanded?: boolean;
11312 /** Whether the element currently holds keyboard focus. */
11313 focused?: boolean;
11314 /** The kind of popup the element triggers, e.g. `"menu"`, `"dialog"`. */
11315 haspopup?: string;
11316 /** The `aria-invalid` value. */
11317 invalid?: string;
11318 /** Keyboard shortcuts bound to the element, from `aria-keyshortcuts`. */
11319 keyshortcuts?: string;
11320 /** Hierarchical level, e.g. the heading level of an `<h2>`. */
11321 level?: number;
11322 /** Whether the element is a modal dialog. */
11323 modal?: boolean;
11324 /** Whether a text input accepts multiple lines. */
11325 multiline?: boolean;
11326 /** Whether more than one option can be selected. */
11327 multiselectable?: boolean;
11328 /** Accessible name, e.g. a button's label or an image's alt text. */
11329 name?: string;
11330 orientation?: string;
11331 /** Pressed state of a toggle button. */
11332 pressed?: boolean | 'mixed';
11333 readonly?: boolean;
11334 required?: boolean;
11335 /** Author-supplied role description, from `aria-roledescription`. */
11336 roledescription?: string;
11337 selected?: boolean;
11338 /** Current value of an input or range element. */
11339 value?: string | number;
11340 valuemax?: number;
11341 valuemin?: number;
11342 /** Human-readable form of `value`, from `aria-valuetext`. */
11343 valuetext?: string;
11344 /** Child nodes. Absent for leaf nodes. */
11345 children?: BrowserRunSerializedAXNode[];
11346}
11347/** Success response for `content` action. */
11348type BrowserRunContentSuccessResponse = {
11349 success: true;
11350 /** Extracted HTML content */
11351 result: string;
11352 meta: BrowserRunResponseMeta;
11353};
11354/** Success response for `links` action. */
11355type BrowserRunLinksSuccessResponse = {
11356 success: true;
11357 /** Extracted links */
11358 result: string[];
11359 meta: BrowserRunResponseMeta;
11360};
11361/** Success response for `scrape` action. */
11362type BrowserRunScrapeSuccessResponse = {
11363 success: true;
11364 result: Array<{
11365 /** The CSS selector used to find elements. */
11366 selector: string;
11367 /** Array of elements matching the selector. */
11368 results: Array<{
11369 /** Outer HTML of the element. */
11370 html: string;
11371 /** Text content of the element. */
11372 text: string;
11373 /** Width of the element in pixels. */
11374 width: number;
11375 /** Height of the element in pixels. */
11376 height: number;
11377 /** Top position of the element relative to the viewport in pixels. */
11378 top: number;
11379 /** Left position of the element relative to the viewport in pixels. */
11380 left: number;
11381 /** Array of HTML attributes on the element. */
11382 attributes: Array<{
11383 /** Attribute name. */
11384 name: string;
11385 /** Attribute value. */
11386 value: string;
11387 }>;
11388 }>;
11389 }>;
11390 meta: BrowserRunResponseMeta;
11391};
11392/** Success response for `snapshot` action. Each field is present only when the
11393 * corresponding entry was requested in `formats`.
11394 */
11395type BrowserRunSnapshotSuccessResponse = {
11396 success: true;
11397 result: {
11398 /** HTML content of the page. */
11399 content?: string;
11400 /** Base64-encoded screenshot image. */
11401 screenshot?: string;
11402 /** Markdown content. Prefixed with YAML frontmatter (e.g. `title`) when the
11403 * page provides that metadata.
11404 */
11405 markdown?: string;
11406 /** Root of the page's accessibility tree. */
11407 accessibilityTree?: BrowserRunSerializedAXNode;
11408 };
11409 meta: BrowserRunResponseMeta;
11410};
11411/** Success response for `accessibilityTree` action. */
11412type BrowserRunAccessibilityTreeSuccessResponse = {
11413 success: true;
11414 result: {
11415 /** Root of the accessibility tree, or `null` when `root` matched no element. */
11416 accessibilityTree: BrowserRunSerializedAXNode | null;
11417 };
11418 meta: BrowserRunResponseMeta;
11419};
11420/** Success response for `json` action. */
11421type BrowserRunJsonSuccessResponse = {
11422 success: true;
11423 /** JSON data extracted from the page using an AI model */
11424 result: Record<string, unknown>;
11425 meta: BrowserRunResponseMeta;
11426};
11427/** Success response for `markdown` action. */
11428type BrowserRunMarkdownSuccessResponse = {
11429 success: true;
11430 /** Extracted markdown content */
11431 result: string;
11432 meta: BrowserRunResponseMeta;
11433};
11434/** Error response for BrowserRun actions. */
11435type BrowserRunErrorResponse = {
11436 success: false;
11437 errors: {
11438 message: string;
11439 code?: number;
11440 detail?: string;
11441 path?: string;
11442 }[];
11443};
11444/** Error response for BrowserRun `json` action. */
11445type BrowserRunJsonErrorResponse = BrowserRunErrorResponse & {
11446 /** Raw AI response text for debugging */
11447 rawAiResponse?: string;
11448};
11449/**
11450 * Browser Run API binding for automating headless browsers.
11451 * @see https://developers.cloudflare.com/browser-run/
11452 */
11453declare abstract class BrowserRun {
11454 /**
11455 * Send a raw HTTP request to the Browser Run API.
11456 * Used by libraries like `@cloudflare/puppeteer` to acquire and connect to a browser instance.
11457 * @see https://developers.cloudflare.com/browser-run/
11458 */
11459 fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
11460 /**
11461 * Take a screenshot of a web page.
11462 * @param action - Must be `'screenshot'`.
11463 * @param options - Screenshot options including viewport, selectors, and image format.
11464 * @returns A `Response` containing one of:
11465 *
11466 * **Success (HTTP 200):**
11467 * - Binary image data with `Content-Type: image/png`, `image/jpeg`, or `image/webp` (when `encoding: 'binary'`, the default)
11468 * - Data URI string with `Content-Type: text/plain` (when `encoding: 'base64'`)
11469 *
11470 * **Error:**
11471 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
11472 *
11473 * **Headers:**
11474 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
11475 */
11476 quickAction(action: 'screenshot', options: BrowserRunScreenshotOptions): Promise<Response>;
11477 /**
11478 * Generate a PDF of a web page.
11479 * @param action - Must be `'pdf'`.
11480 * @param options - PDF generation options including page size, margins, and headers/footers.
11481 * @returns A `Response` containing one of:
11482 *
11483 * **Success (HTTP 200):**
11484 * - Binary PDF data with `Content-Type: application/pdf`
11485 *
11486 * **Error:**
11487 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
11488 *
11489 * **Headers:**
11490 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
11491 */
11492 quickAction(action: 'pdf', options: BrowserRunPDFOptions): Promise<Response>;
11493 /**
11494 * Get the HTML content of a web page.
11495 * @param action - Must be `'content'`.
11496 * @param options - Navigation and page interaction options.
11497 * @returns A `Response` containing one of:
11498 *
11499 * **Success (HTTP 200):**
11500 * - `BrowserRunContentSuccessResponse` JSON with `Content-Type: application/json`
11501 *
11502 * **Error:**
11503 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
11504 *
11505 * **Headers:**
11506 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
11507 */
11508 quickAction(action: 'content', options: BrowserRunContentOptions): Promise<Response>;
11509 /**
11510 * Scrape elements from a web page by CSS selector.
11511 * @param action - Must be `'scrape'`.
11512 * @param options - Scrape options with CSS selectors for elements to extract.
11513 * @returns A `Response` containing one of:
11514 *
11515 * **Success (HTTP 200):**
11516 * - `BrowserRunScrapeSuccessResponse` JSON with `Content-Type: application/json`
11517 *
11518 * **Error:**
11519 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
11520 *
11521 * **Headers:**
11522 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
11523 */
11524 quickAction(action: 'scrape', options: BrowserRunScrapeOptions): Promise<Response>;
11525 /**
11526 * Extract all links from a web page.
11527 * @param action - Must be `'links'`.
11528 * @param options - Options to filter visible or internal links only.
11529 * @returns A `Response` containing one of:
11530 *
11531 * **Success (HTTP 200):**
11532 * - `BrowserRunLinksSuccessResponse` JSON with `Content-Type: application/json`
11533 *
11534 * **Error:**
11535 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
11536 *
11537 * **Headers:**
11538 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
11539 */
11540 quickAction(action: 'links', options: BrowserRunLinksOptions): Promise<Response>;
11541 /**
11542 * Get several representations of a web page in one request.
11543 * @param action - Must be `'snapshot'`.
11544 * @param options - Snapshot options including the `formats` to return and
11545 * screenshot settings (encoding is always base64).
11546 * @returns A `Response` containing one of:
11547 *
11548 * **Success (HTTP 200):**
11549 * - `BrowserRunSnapshotSuccessResponse` JSON with `Content-Type: application/json`
11550 *
11551 * **Error:**
11552 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
11553 *
11554 * **Headers:**
11555 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
11556 */
11557 quickAction(action: 'snapshot', options: BrowserRunSnapshotOptions): Promise<Response>;
11558 /**
11559 * Extract structured JSON data from a web page using AI.
11560 * @param action - Must be `'json'`.
11561 * @param options - JSON extraction options with prompt or response_format schema.
11562 * @returns A `Response` containing one of:
11563 *
11564 * **Success (HTTP 200):**
11565 * - `BrowserRunJsonSuccessResponse` JSON with `Content-Type: application/json`
11566 *
11567 * **Error:**
11568 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
11569 * - HTTP 422 with code `2012` for HTML-to-markdown conversion failures
11570 * - HTTP 422/500 for AI extraction failures (may include `rawAiResponse` field)
11571 *
11572 * **Headers:**
11573 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
11574 */
11575 quickAction(action: 'json', options: BrowserRunJsonOptions): Promise<Response>;
11576 /**
11577 * Convert a web page to Markdown.
11578 * @param action - Must be `'markdown'`.
11579 * @param options - Navigation and page interaction options.
11580 * @returns A `Response` containing one of:
11581 *
11582 * **Success (HTTP 200):**
11583 * - `BrowserRunMarkdownSuccessResponse` JSON with `Content-Type: application/json`
11584 *
11585 * **Error:**
11586 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
11587 * - HTTP 422 with code `2012` for HTML-to-markdown conversion failures
11588 *
11589 * **Headers:**
11590 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
11591 */
11592 quickAction(action: 'markdown', options: BrowserRunMarkdownOptions): Promise<Response>;
11593 /**
11594 * Get the accessibility tree of a web page.
11595 * @param action - Must be `'accessibilityTree'`.
11596 * @param options - Options to scope the tree to a subtree and to control
11597 * whether semantically uninteresting nodes are pruned.
11598 * @returns A `Response` containing one of:
11599 *
11600 * **Success (HTTP 200):**
11601 * - `BrowserRunAccessibilityTreeSuccessResponse` JSON with `Content-Type: application/json`
11602 * - `result.accessibilityTree` is `null` when `root` matched no element
11603 *
11604 * **Error:**
11605 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
11606 * - HTTP 422 for a malformed `root` selector
11607 * - HTTP 500 with code `2017` or `2018` when the tree could not be built
11608 *
11609 * **Headers:**
11610 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
11611 */
11612 quickAction(action: 'accessibilityTree', options: BrowserRunAccessibilityTreeOptions): Promise<Response>;
11613}
11614/**
11615 * In addition to the properties you can set in the RequestInit dict
11616 * that you pass as an argument to the Request constructor, you can
11617 * set certain properties of a `cf` object to control how Cloudflare
11618 * features are applied to that new Request.
11619 *
11620 * Note: Currently, these properties cannot be tested in the
11621 * playground.
11622 */
11623interface RequestInitCfProperties extends Record<string, unknown> {
11624 cacheEverything?: boolean;
11625 /**
11626 * A request's cache key is what determines if two requests are
11627 * "the same" for caching purposes. If a request has the same cache key
11628 * as some previous request, then we can serve the same cached response for
11629 * both. (e.g. 'some-key')
11630 *
11631 * Only available for Enterprise customers.
11632 */
11633 cacheKey?: string;
11634 /**
11635 * This allows you to append additional Cache-Tag response headers
11636 * to the origin response without modifications to the origin server.
11637 * This will allow for greater control over the Purge by Cache Tag feature
11638 * utilizing changes only in the Workers process.
11639 *
11640 * Only available for Enterprise customers.
11641 */
11642 cacheTags?: string[];
11643 /**
11644 * Force response to be cached for a given number of seconds. (e.g. 300)
11645 */
11646 cacheTtl?: number;
11647 /**
11648 * Force response to be cached for a given number of seconds based on the Origin status code.
11649 * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 })
11650 */
11651 cacheTtlByStatus?: Record<string, number>;
11652 /** Controls how responses with a `Vary` header are cached for this request. */
11653 vary?: RequestInitCfPropertiesVary;
11654 /**
11655 * Explicit Cache-Control header value to set on the response stored in cache.
11656 * This gives full control over cache directives (e.g. 'public, max-age=3600, s-maxage=86400').
11657 *
11658 * Cannot be used together with `cacheTtl` or the `cache` request option (`no-store`/`no-cache`),
11659 * as these are mutually exclusive cache control mechanisms. Setting both will throw a TypeError.
11660 *
11661 * Can be used together with `cacheTtlByStatus`.
11662 */
11663 cacheControl?: string;
11664 /**
11665 * Whether the response should be eligible for Cache Reserve storage.
11666 */
11667 cacheReserveEligible?: boolean;
11668 /**
11669 * Whether to respect strong ETags (as opposed to weak ETags) from the origin.
11670 */
11671 respectStrongEtag?: boolean;
11672 /**
11673 * Whether to strip ETag headers from the origin response before caching.
11674 */
11675 stripEtags?: boolean;
11676 /**
11677 * Whether to strip Last-Modified headers from the origin response before caching.
11678 */
11679 stripLastModified?: boolean;
11680 /**
11681 * Whether to enable Cache Deception Armor, which protects against web cache
11682 * deception attacks by verifying the Content-Type matches the URL extension.
11683 */
11684 cacheDeceptionArmor?: boolean;
11685 /**
11686 * Minimum file size in bytes for a response to be eligible for Cache Reserve storage.
11687 */
11688 cacheReserveMinimumFileSize?: number;
11689 scrapeShield?: boolean;
11690 apps?: boolean;
11691 /**
11692 * Controls whether an outbound gRPC-web subrequest from this Worker is
11693 * converted to gRPC at the Cloudflare edge.
11694 *
11695 * - `"passthrough"`: forward the subrequest unchanged as gRPC-web (default).
11696 * - `"convert"`: convert the gRPC-web subrequest to gRPC at the edge.
11697 *
11698 * Provides per-request control over the same edge conversion behavior
11699 * gated by the `auto_grpc_convert` compatibility flag.
11700 */
11701 grpcWeb?: "passthrough" | "convert";
11702 image?: RequestInitCfPropertiesImage;
11703 minify?: RequestInitCfPropertiesImageMinify;
11704 mirage?: boolean;
11705 polish?: "lossy" | "lossless" | "off";
11706 r2?: RequestInitCfPropertiesR2;
11707 /**
11708 * Redirects the request to an alternate origin server. You can use this,
11709 * for example, to implement load balancing across several origins.
11710 * (e.g.us-east.example.com)
11711 *
11712 * Note - For security reasons, the hostname set in resolveOverride must
11713 * be proxied on the same Cloudflare zone of the incoming request.
11714 * Otherwise, the setting is ignored. CNAME hosts are allowed, so to
11715 * resolve to a host under a different domain or a DNS only domain first
11716 * declare a CNAME record within your own zoneโ€™s DNS mapping to the
11717 * external hostname, set proxy on Cloudflare, then set resolveOverride
11718 * to point to that CNAME record.
11719 */
11720 resolveOverride?: string;
11721}
11722/**
11723 * Controls how Workers Standard Vary handles a request header listed by an
11724 * origin `Vary` response header:
11725 *
11726 * - `"normalize"`: normalize the request header value before it is used in the
11727 * cache variance key.
11728 * - `"passthrough"`: use the raw request header value in the cache variance
11729 * key.
11730 * - `"bypass"`: bypass cache when the header appears in the origin `Vary`
11731 * response header.
11732 */
11733type RequestInitCfPropertiesVaryAction = "normalize" | "passthrough" | "bypass";
11734/** Configuration for Workers Standard Vary support. */
11735interface RequestInitCfPropertiesVary {
11736 /** The fallback action for varied request headers not listed in `headers`. */
11737 default: RequestInitCfPropertiesVaryHeader;
11738 /**
11739 * Lowercase request header names and their Vary configuration.
11740 *
11741 * The `accept` header can include `media_types`, the `accept-language`
11742 * header can include `languages`, and other headers support only `action`.
11743 */
11744 headers?: RequestInitCfPropertiesVaryHeaders;
11745}
11746/** Common Vary behavior for a single request header. */
11747interface RequestInitCfPropertiesVaryHeader {
11748 /** How this request header contributes to cache variance. */
11749 action: RequestInitCfPropertiesVaryAction;
11750}
11751/** Vary behavior for the `accept` request header. */
11752interface RequestInitCfPropertiesVaryAcceptHeader extends RequestInitCfPropertiesVaryHeader {
11753 /**
11754 * Media types to keep when normalizing the `Accept` request header.
11755 *
11756 * Named `media_types` to match the serialized `cf.vary` configuration.
11757 */
11758 media_types?: string[];
11759}
11760/** Vary behavior for the `accept-language` request header. */
11761interface RequestInitCfPropertiesVaryAcceptLanguageHeader extends RequestInitCfPropertiesVaryHeader {
11762 /**
11763 * Language tags to keep when normalizing the `Accept-Language` request
11764 * header.
11765 */
11766 languages?: string[];
11767}
11768/**
11769 * Lowercase request header names and their Vary behavior.
11770 *
11771 * The index signature allows arbitrary custom request headers beyond the
11772 * well-known `accept` and `accept-language` specializations.
11773 */
11774interface RequestInitCfPropertiesVaryHeaders {
11775 accept?: RequestInitCfPropertiesVaryAcceptHeader;
11776 "accept-language"?: RequestInitCfPropertiesVaryAcceptLanguageHeader;
11777 [header: string]: RequestInitCfPropertiesVaryHeader | RequestInitCfPropertiesVaryAcceptHeader | RequestInitCfPropertiesVaryAcceptLanguageHeader | undefined;
11778}
11779interface BasicImageTransformations {
11780 /**
11781 * Maximum width in image pixels. The value must be an integer.
11782 */
11783 width?: number;
11784 /**
11785 * Maximum height in image pixels. The value must be an integer.
11786 */
11787 height?: number;
11788 /**
11789 * When cropping with fit: "cover", this defines the side or point that should
11790 * be left uncropped. The value is either a string
11791 * "left", "right", "top", "bottom", "auto", or "center" (the default),
11792 * or an object {x, y} containing focal point coordinates in the original
11793 * image expressed as fractions ranging from 0.0 (top or left) to 1.0
11794 * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will
11795 * crop bottom or left and right sides as necessary, but wonโ€™t crop anything
11796 * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to
11797 * preserve as much as possible around a point at 20% of the height of the
11798 * source image.
11799 */
11800 gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates;
11801 /**
11802 * Specifies how closely the image is cropped toward detected faces when combined
11803 * with the gravity=face option. Accepts a valid range between 0.0 (includes as much
11804 * of the background as possible) and 1.0 (crops the image as closely to the face as
11805 * possible). The default is 0.
11806 */
11807 zoom?: number;
11808 /**
11809 * Resizing mode as a string. It affects interpretation of width and height
11810 * options:
11811 * - scale-down: Similar to contain, but the image is never enlarged. If
11812 * the image is larger than given width or height, it will be resized.
11813 * Otherwise its original size will be kept.
11814 * - scale-up: Similar to contain, but the image is never shrunk. If the
11815 * image is smaller than the given width or height, it will be resized.
11816 * Otherwise its original size will be kept.
11817 * - contain: Resizes to maximum size that fits within the given width and
11818 * height. If only a single dimension is given (e.g. only width), the
11819 * image will be shrunk or enlarged to exactly match that dimension.
11820 * Aspect ratio is always preserved.
11821 * - cover: Resizes (shrinks or enlarges) to fill the entire area of width
11822 * and height. If the image has an aspect ratio different from the ratio
11823 * of width and height, it will be cropped to fit.
11824 * - crop: The image will be shrunk and cropped to fit within the area
11825 * specified by width and height. The image will not be enlarged. For images
11826 * smaller than the given dimensions it's the same as scale-down. For
11827 * images larger than the given dimensions, it's the same as cover.
11828 * See also trim.
11829 * - pad: Resizes to the maximum size that fits within the given width and
11830 * height, and then fills the remaining area with a background color
11831 * (white by default). Use of this mode is not recommended, as the same
11832 * effect can be more efficiently achieved with the contain mode and the
11833 * CSS object-fit: contain property.
11834 * - squeeze: Stretches and deforms to the width and height given, even if it
11835 * breaks aspect ratio
11836 */
11837 fit?: "scale-down" | "scale-up" | "contain" | "cover" | "crop" | "pad" | "squeeze";
11838 /**
11839 * Allows you to trim your image. Takes dpr into account and is performed before
11840 * resizing or rotation.
11841 *
11842 * It can be used as:
11843 * - left, top, right, bottom - it will specify the number of pixels to cut
11844 * off each side
11845 * - width, height - the width/height you'd like to end up with - can be used
11846 * in combination with the properties above
11847 * - border - this will automatically trim the surroundings of an image based on
11848 * it's color. It consists of three properties:
11849 * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit)
11850 * - tolerance: difference from color to treat as color
11851 * - keep: the number of pixels of border to keep
11852 */
11853 trim?: "border" | {
11854 top?: number;
11855 bottom?: number;
11856 left?: number;
11857 right?: number;
11858 width?: number;
11859 height?: number;
11860 border?: boolean | {
11861 color?: string;
11862 tolerance?: number;
11863 keep?: number;
11864 };
11865 };
11866 /**
11867 * Background color to add underneath the image. Applies only to images with
11868 * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(โ€ฆ),
11869 * hsl(โ€ฆ), etc.)
11870 */
11871 background?: string;
11872 /**
11873 * Flips the images horizontally, vertically, or both. Flipping is applied before
11874 * rotation, so if you apply flip=h,rotate=90 then the image will be flipped
11875 * horizontally, then rotated by 90 degrees.
11876 */
11877 flip?: 'h' | 'v' | 'hv';
11878 /**
11879 * Number of degrees (90, 180, 270) to rotate the image by. width and height
11880 * options refer to axes after rotation.
11881 */
11882 rotate?: 0 | 90 | 180 | 270 | 360;
11883 /**
11884 * Strength of sharpening filter to apply to the image. Floating-point
11885 * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a
11886 * recommended value for downscaled images.
11887 */
11888 sharpen?: number;
11889 /**
11890 * Radius of a blur filter (approximate gaussian). Maximum supported radius
11891 * is 250.
11892 */
11893 blur?: number;
11894 /**
11895 * Increase contrast by a factor. A value of 1.0 equals no change, a value of
11896 * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is
11897 * ignored.
11898 */
11899 contrast?: number;
11900 /**
11901 * Increase brightness by a factor. A value of 1.0 equals no change, a value
11902 * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright.
11903 * 0 is ignored.
11904 */
11905 brightness?: number;
11906 /**
11907 * Increase exposure by a factor. A value of 1.0 equals no change, a value of
11908 * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored.
11909 */
11910 gamma?: number;
11911 /**
11912 * Increase contrast by a factor. A value of 1.0 equals no change, a value of
11913 * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is
11914 * ignored.
11915 */
11916 saturation?: number;
11917 /**
11918 * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it
11919 * easier to specify higher-DPI sizes in <img srcset>.
11920 */
11921 dpr?: number;
11922 /**
11923 * Adds a border around the image. The border is added after resizing. Border
11924 * width takes dpr into account, and can be specified either using a single
11925 * width property, or individually for each side.
11926 */
11927 border?: {
11928 color: string;
11929 width: number;
11930 } | {
11931 color: string;
11932 top: number;
11933 right: number;
11934 bottom: number;
11935 left: number;
11936 };
11937 /**
11938 * Image segmentation using artificial intelligence models. Sets pixels not
11939 * within selected segment area to transparent e.g "foreground" sets every
11940 * background pixel as transparent.
11941 */
11942 segment?: "foreground";
11943 /**
11944 * Controls the algorithm used when an image needs to be enlarged. This
11945 * parameter works with any fit mode that upscales, such as `contain`,
11946 * `cover`, and `scale-up`. It has no effect when `fit=scale-down` or when
11947 * the target dimensions are smaller than the source.
11948 * - interpolate: Uses bicubic interpolation, which may reduce image quality.
11949 * This is the default behavior when `upscale` is not specified.
11950 * - generate: Uses AI upscaling to produce sharper, more detailed results
11951 * when enlarging images.
11952 */
11953 upscale?: "interpolate" | "generate";
11954}
11955interface BasicImageTransformationsGravityCoordinates {
11956 x?: number;
11957 y?: number;
11958 mode?: 'remainder' | 'box-center';
11959}
11960interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations {
11961 /**
11962 * Absolute URL of the image file to use for the drawing. It can be any of
11963 * the supported file formats. For drawing of watermarks or non-rectangular
11964 * overlays we recommend using PNG or WebP images.
11965 */
11966 url: string;
11967 /**
11968 * Floating-point number between 0 (transparent) and 1 (opaque).
11969 * For example, opacity: 0.5 makes overlay semitransparent.
11970 */
11971 opacity?: number;
11972 /**
11973 * - If set to true, the overlay image will be tiled to cover the entire
11974 * area. This is useful for stock-photo-like watermarks.
11975 * - If set to "x", the overlay image will be tiled horizontally only
11976 * (form a line).
11977 * - If set to "y", the overlay image will be tiled vertically only
11978 * (form a line).
11979 */
11980 repeat?: true | "x" | "y";
11981 /**
11982 * How to combine the foreground and backdrop pixels to create the result
11983 */
11984 composite?:
11985 /** Foreground drawn on top of backdrop (default) */
11986 'over'
11987 /** Foreground shown only where backdrop is opaque */
11988 | 'in'
11989 /** Foreground drawn on top, but clipped to the backdrop's shape */
11990 | 'atop'
11991 /** Foreground shown only where backdrop is transparent */
11992 | 'out'
11993 /** Foreground and backdrop visible only where the other is not */
11994 | 'xor'
11995 /** Foreground and backdrop channels added (brightening) */
11996 | 'lighter';
11997 /**
11998 * Position of the overlay image relative to a given edge. Each property is
11999 * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10
12000 * positions left side of the overlay 10 pixels from the left edge of the
12001 * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom
12002 * of the background image.
12003 *
12004 * Setting both left & right, or both top & bottom is an error.
12005 *
12006 * If no position is specified, the image will be centered.
12007 */
12008 top?: number;
12009 left?: number;
12010 bottom?: number;
12011 right?: number;
12012}
12013interface RequestInitCfPropertiesImage extends BasicImageTransformations {
12014 /**
12015 * Quality setting from 1-100 (useful values are in 60-90 range). Lower values
12016 * make images look worse, but load faster. The default is 85. It applies only
12017 * to JPEG and WebP images. It doesnโ€™t have any effect on PNG.
12018 */
12019 quality?: number | "low" | "medium-low" | "medium-high" | "high";
12020 /**
12021 * Output format to generate. It can be:
12022 * - avif: generate images in AVIF format.
12023 * - webp: generate images in Google WebP format. Set quality to 100 to get
12024 * the WebP-lossless format.
12025 * - json: instead of generating an image, outputs information about the
12026 * image, in JSON format. The JSON object will contain image size
12027 * (before and after resizing), source imageโ€™s MIME type, file size, etc.
12028 * - jpeg: generate images in JPEG format.
12029 * - png: generate images in PNG format.
12030 */
12031 format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg";
12032 /**
12033 * Whether to preserve animation frames from input files. Default is true.
12034 * Setting it to false reduces animations to still images. This setting is
12035 * recommended when enlarging images or processing arbitrary user content,
12036 * because large GIF animations can weigh tens or even hundreds of megabytes.
12037 * It is also useful to set anim:false when using format:"json" to get the
12038 * response quicker without the number of frames.
12039 */
12040 anim?: boolean;
12041 /**
12042 * What EXIF data should be preserved in the output image. Note that EXIF
12043 * rotation and embedded color profiles are always applied ("baked in" into
12044 * the image), and aren't affected by this option. Note that if the Polish
12045 * feature is enabled, all metadata may have been removed already and this
12046 * option may have no effect.
12047 * - keep: Preserve most of EXIF metadata, including GPS location if there's
12048 * any.
12049 * - copyright: Only keep the copyright tag, and discard everything else.
12050 * This is the default behavior for JPEG files.
12051 * - none: Discard all invisible EXIF metadata. Currently WebP and PNG
12052 * output formats always discard metadata.
12053 */
12054 metadata?: "keep" | "copyright" | "none";
12055 /**
12056 * Overlays are drawn in the order they appear in the array (last array
12057 * entry is the topmost layer).
12058 */
12059 draw?: RequestInitCfPropertiesImageDraw[];
12060 /**
12061 * Fetching image from authenticated origin. Setting this property will
12062 * pass authentication headers (Authorization, Cookie, etc.) through to
12063 * the origin.
12064 */
12065 "origin-auth"?: "share-publicly";
12066 /**
12067 * Slightly reduces latency on a cache miss by selecting a
12068 * quickest-to-compress file format, at a cost of increased file size and
12069 * lower image quality. It will usually override the format option and choose
12070 * JPEG over WebP or AVIF. We do not recommend using this option, except in
12071 * unusual circumstances like resizing uncacheable dynamically-generated
12072 * images.
12073 */
12074 compression?: "fast";
12075}
12076interface RequestInitCfPropertiesImageMinify {
12077 javascript?: boolean;
12078 css?: boolean;
12079 html?: boolean;
12080}
12081interface RequestInitCfPropertiesR2 {
12082 /**
12083 * Colo id of bucket that an object is stored in
12084 */
12085 bucketColoId?: number;
12086}
12087/**
12088 * Request metadata provided by Cloudflare's edge.
12089 */
12090type IncomingRequestCfProperties<HostMetadata = unknown> = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield;
12091interface IncomingRequestCfPropertiesBase extends Record<string, unknown> {
12092 /**
12093 * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request.
12094 *
12095 * @example 395747
12096 */
12097 asn?: number;
12098 /**
12099 * The organization which owns the ASN of the incoming request.
12100 *
12101 * @example "Google Cloud"
12102 */
12103 asOrganization?: string;
12104 /**
12105 * The original value of the `Accept-Encoding` header if Cloudflare modified it.
12106 *
12107 * @example "gzip, deflate, br"
12108 */
12109 clientAcceptEncoding?: string;
12110 /**
12111 * The number of milliseconds it took for the request to reach your worker.
12112 *
12113 * @example 22
12114 */
12115 clientTcpRtt?: number;
12116 /**
12117 * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code)
12118 * airport code of the data center that the request hit.
12119 *
12120 * @example "DFW"
12121 */
12122 colo: string;
12123 /**
12124 * Represents the upstream's response to a
12125 * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html)
12126 * from cloudflare.
12127 *
12128 * For workers with no upstream, this will always be `1`.
12129 *
12130 * @example 3
12131 */
12132 edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus;
12133 /**
12134 * The HTTP Protocol the request used.
12135 *
12136 * @example "HTTP/2"
12137 */
12138 httpProtocol: string;
12139 /**
12140 * The browser-requested prioritization information in the request object.
12141 *
12142 * If no information was set, defaults to the empty string `""`
12143 *
12144 * @example "weight=192;exclusive=0;group=3;group-weight=127"
12145 * @default ""
12146 */
12147 requestPriority: string;
12148 /**
12149 * The TLS version of the connection to Cloudflare.
12150 * In requests served over plaintext (without TLS), this property is the empty string `""`.
12151 *
12152 * @example "TLSv1.3"
12153 */
12154 tlsVersion: string;
12155 /**
12156 * The cipher for the connection to Cloudflare.
12157 * In requests served over plaintext (without TLS), this property is the empty string `""`.
12158 *
12159 * @example "AEAD-AES128-GCM-SHA256"
12160 */
12161 tlsCipher: string;
12162 /**
12163 * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake.
12164 *
12165 * If the incoming request was served over plaintext (without TLS) this field is undefined.
12166 */
12167 tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata;
12168}
12169interface IncomingRequestCfPropertiesBotManagementBase {
12170 /**
12171 * Cloudflareโ€™s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot,
12172 * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human).
12173 *
12174 * @example 54
12175 */
12176 score: number;
12177 /**
12178 * A boolean value that is true if the request comes from a good bot, like Google or Bing.
12179 * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots).
12180 */
12181 verifiedBot: boolean;
12182 /**
12183 * A boolean value that is true if the request originates from a
12184 * Cloudflare-verified proxy service.
12185 */
12186 corporateProxy: boolean;
12187 /**
12188 * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources.
12189 */
12190 staticResource: boolean;
12191 /**
12192 * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request).
12193 */
12194 detectionIds: number[];
12195}
12196interface IncomingRequestCfPropertiesBotManagement {
12197 /**
12198 * Results of Cloudflare's Bot Management analysis
12199 */
12200 botManagement: IncomingRequestCfPropertiesBotManagementBase;
12201 /**
12202 * Duplicate of `botManagement.score`.
12203 *
12204 * @deprecated
12205 */
12206 clientTrustScore: number;
12207}
12208interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement {
12209 /**
12210 * Results of Cloudflare's Bot Management analysis
12211 */
12212 botManagement: IncomingRequestCfPropertiesBotManagementBase & {
12213 /**
12214 * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients
12215 * across different destination IPs, Ports, and X509 certificates.
12216 */
12217 ja3Hash: string;
12218 };
12219}
12220interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> {
12221 /**
12222 * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/).
12223 *
12224 * This field is only present if you have Cloudflare for SaaS enabled on your account
12225 * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)).
12226 */
12227 hostMetadata?: HostMetadata;
12228}
12229interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield {
12230 /**
12231 * Information about the client certificate presented to Cloudflare.
12232 *
12233 * This is populated when the incoming request is served over TLS using
12234 * either Cloudflare Access or API Shield (mTLS)
12235 * and the presented SSL certificate has a valid
12236 * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number)
12237 * (i.e., not `null` or `""`).
12238 *
12239 * Otherwise, a set of placeholder values are used.
12240 *
12241 * The property `certPresented` will be set to `"1"` when
12242 * the object is populated (i.e. the above conditions were met).
12243 */
12244 tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder;
12245}
12246/**
12247 * Metadata about the request's TLS handshake
12248 */
12249interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata {
12250 /**
12251 * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal
12252 *
12253 * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d"
12254 */
12255 clientHandshake: string;
12256 /**
12257 * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal
12258 *
12259 * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d"
12260 */
12261 serverHandshake: string;
12262 /**
12263 * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal
12264 *
12265 * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b"
12266 */
12267 clientFinished: string;
12268 /**
12269 * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal
12270 *
12271 * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b"
12272 */
12273 serverFinished: string;
12274}
12275/**
12276 * Geographic data about the request's origin.
12277 */
12278interface IncomingRequestCfPropertiesGeographicInformation {
12279 /**
12280 * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from.
12281 *
12282 * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR.
12283 *
12284 * If Cloudflare is unable to determine where the request originated this property is omitted.
12285 *
12286 * The country code `"T1"` is used for requests originating on TOR.
12287 *
12288 * @example "GB"
12289 */
12290 country?: Iso3166Alpha2Code | "T1";
12291 /**
12292 * If present, this property indicates that the request originated in the EU
12293 *
12294 * @example "1"
12295 */
12296 isEUCountry?: "1";
12297 /**
12298 * A two-letter code indicating the continent the request originated from.
12299 *
12300 * @example "AN"
12301 */
12302 continent?: ContinentCode;
12303 /**
12304 * The city the request originated from
12305 *
12306 * @example "Austin"
12307 */
12308 city?: string;
12309 /**
12310 * Postal code of the incoming request
12311 *
12312 * @example "78701"
12313 */
12314 postalCode?: string;
12315 /**
12316 * Latitude of the incoming request
12317 *
12318 * @example "30.27130"
12319 */
12320 latitude?: string;
12321 /**
12322 * Longitude of the incoming request
12323 *
12324 * @example "-97.74260"
12325 */
12326 longitude?: string;
12327 /**
12328 * Timezone of the incoming request
12329 *
12330 * @example "America/Chicago"
12331 */
12332 timezone?: string;
12333 /**
12334 * If known, the ISO 3166-2 name for the first level region associated with
12335 * the IP address of the incoming request
12336 *
12337 * @example "Texas"
12338 */
12339 region?: string;
12340 /**
12341 * If known, the ISO 3166-2 code for the first-level region associated with
12342 * the IP address of the incoming request
12343 *
12344 * @example "TX"
12345 */
12346 regionCode?: string;
12347 /**
12348 * Metro code (DMA) of the incoming request
12349 *
12350 * @example "635"
12351 */
12352 metroCode?: string;
12353}
12354/** Data about the incoming request's TLS certificate */
12355interface IncomingRequestCfPropertiesTLSClientAuth {
12356 /** Always `"1"`, indicating that the certificate was presented */
12357 certPresented: "1";
12358 /**
12359 * Result of certificate verification.
12360 *
12361 * @example "FAILED:self signed certificate"
12362 */
12363 certVerified: Exclude<CertVerificationStatus, "NONE">;
12364 /** The presented certificate's revokation status.
12365 *
12366 * - A value of `"1"` indicates the certificate has been revoked
12367 * - A value of `"0"` indicates the certificate has not been revoked
12368 */
12369 certRevoked: "1" | "0";
12370 /**
12371 * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)
12372 *
12373 * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"
12374 */
12375 certIssuerDN: string;
12376 /**
12377 * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)
12378 *
12379 * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"
12380 */
12381 certSubjectDN: string;
12382 /**
12383 * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)
12384 *
12385 * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"
12386 */
12387 certIssuerDNRFC2253: string;
12388 /**
12389 * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)
12390 *
12391 * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"
12392 */
12393 certSubjectDNRFC2253: string;
12394 /** The certificate issuer's distinguished name (legacy policies) */
12395 certIssuerDNLegacy: string;
12396 /** The certificate subject's distinguished name (legacy policies) */
12397 certSubjectDNLegacy: string;
12398 /**
12399 * The certificate's serial number
12400 *
12401 * @example "00936EACBE07F201DF"
12402 */
12403 certSerial: string;
12404 /**
12405 * The certificate issuer's serial number
12406 *
12407 * @example "2489002934BDFEA34"
12408 */
12409 certIssuerSerial: string;
12410 /**
12411 * The certificate's Subject Key Identifier
12412 *
12413 * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4"
12414 */
12415 certSKI: string;
12416 /**
12417 * The certificate issuer's Subject Key Identifier
12418 *
12419 * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4"
12420 */
12421 certIssuerSKI: string;
12422 /**
12423 * The certificate's SHA-1 fingerprint
12424 *
12425 * @example "6b9109f323999e52259cda7373ff0b4d26bd232e"
12426 */
12427 certFingerprintSHA1: string;
12428 /**
12429 * The certificate's SHA-256 fingerprint
12430 *
12431 * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea"
12432 */
12433 certFingerprintSHA256: string;
12434 /**
12435 * The effective starting date of the certificate
12436 *
12437 * @example "Dec 22 19:39:00 2018 GMT"
12438 */
12439 certNotBefore: string;
12440 /**
12441 * The effective expiration date of the certificate
12442 *
12443 * @example "Dec 22 19:39:00 2018 GMT"
12444 */
12445 certNotAfter: string;
12446 /**
12447 * The client leaf certificate in [RFC 9440](https://www.rfc-editor.org/rfc/rfc9440)
12448 * format (`:base64-DER:`). Empty if no client certificate was presented or if
12449 * the leaf certificate exceeded 10 KB (see {@link certRFC9440TooLarge}).
12450 *
12451 * Suitable for forwarding to an origin via the `Client-Cert` HTTP header.
12452 */
12453 certRFC9440: string;
12454 /**
12455 * `true` if the leaf certificate exceeded 10 KB and was omitted from
12456 * {@link certRFC9440}.
12457 */
12458 certRFC9440TooLarge: boolean;
12459 /**
12460 * The intermediate certificate chain in [RFC 9440](https://www.rfc-editor.org/rfc/rfc9440)
12461 * format as a comma-separated list. Empty if no intermediates were sent or
12462 * if the chain exceeded 16 KB (see {@link certChainRFC9440TooLarge}).
12463 *
12464 * Suitable for forwarding to an origin via the `Client-Cert-Chain` HTTP header.
12465 */
12466 certChainRFC9440: string;
12467 /**
12468 * `true` if the intermediate chain exceeded 16 KB and was omitted from
12469 * {@link certChainRFC9440}.
12470 */
12471 certChainRFC9440TooLarge: boolean;
12472}
12473/** Placeholder values for TLS Client Authorization */
12474interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder {
12475 certPresented: "0";
12476 certVerified: "NONE";
12477 certRevoked: "0";
12478 certIssuerDN: "";
12479 certSubjectDN: "";
12480 certIssuerDNRFC2253: "";
12481 certSubjectDNRFC2253: "";
12482 certIssuerDNLegacy: "";
12483 certSubjectDNLegacy: "";
12484 certSerial: "";
12485 certIssuerSerial: "";
12486 certSKI: "";
12487 certIssuerSKI: "";
12488 certFingerprintSHA1: "";
12489 certFingerprintSHA256: "";
12490 certNotBefore: "";
12491 certNotAfter: "";
12492 certRFC9440: "";
12493 certRFC9440TooLarge: false;
12494 certChainRFC9440: "";
12495 certChainRFC9440TooLarge: false;
12496}
12497/** Possible outcomes of TLS verification */
12498declare type CertVerificationStatus =
12499/** Authentication succeeded */
12500"SUCCESS"
12501/** No certificate was presented */
12502 | "NONE"
12503/** Failed because the certificate was self-signed */
12504 | "FAILED:self signed certificate"
12505/** Failed because the certificate failed a trust chain check */
12506 | "FAILED:unable to verify the first certificate"
12507/** Failed because the certificate not yet valid */
12508 | "FAILED:certificate is not yet valid"
12509/** Failed because the certificate is expired */
12510 | "FAILED:certificate has expired"
12511/** Failed for another unspecified reason */
12512 | "FAILED";
12513/**
12514 * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare.
12515 */
12516declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5; /** connection re-use, accepted by the origin server */
12517/** ISO 3166-1 Alpha-2 codes */
12518declare type Iso3166Alpha2Code = "AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" | "AO" | "AQ" | "AR" | "AS" | "AT" | "AU" | "AW" | "AX" | "AZ" | "BA" | "BB" | "BD" | "BE" | "BF" | "BG" | "BH" | "BI" | "BJ" | "BL" | "BM" | "BN" | "BO" | "BQ" | "BR" | "BS" | "BT" | "BV" | "BW" | "BY" | "BZ" | "CA" | "CC" | "CD" | "CF" | "CG" | "CH" | "CI" | "CK" | "CL" | "CM" | "CN" | "CO" | "CR" | "CU" | "CV" | "CW" | "CX" | "CY" | "CZ" | "DE" | "DJ" | "DK" | "DM" | "DO" | "DZ" | "EC" | "EE" | "EG" | "EH" | "ER" | "ES" | "ET" | "FI" | "FJ" | "FK" | "FM" | "FO" | "FR" | "GA" | "GB" | "GD" | "GE" | "GF" | "GG" | "GH" | "GI" | "GL" | "GM" | "GN" | "GP" | "GQ" | "GR" | "GS" | "GT" | "GU" | "GW" | "GY" | "HK" | "HM" | "HN" | "HR" | "HT" | "HU" | "ID" | "IE" | "IL" | "IM" | "IN" | "IO" | "IQ" | "IR" | "IS" | "IT" | "JE" | "JM" | "JO" | "JP" | "KE" | "KG" | "KH" | "KI" | "KM" | "KN" | "KP" | "KR" | "KW" | "KY" | "KZ" | "LA" | "LB" | "LC" | "LI" | "LK" | "LR" | "LS" | "LT" | "LU" | "LV" | "LY" | "MA" | "MC" | "MD" | "ME" | "MF" | "MG" | "MH" | "MK" | "ML" | "MM" | "MN" | "MO" | "MP" | "MQ" | "MR" | "MS" | "MT" | "MU" | "MV" | "MW" | "MX" | "MY" | "MZ" | "NA" | "NC" | "NE" | "NF" | "NG" | "NI" | "NL" | "NO" | "NP" | "NR" | "NU" | "NZ" | "OM" | "PA" | "PE" | "PF" | "PG" | "PH" | "PK" | "PL" | "PM" | "PN" | "PR" | "PS" | "PT" | "PW" | "PY" | "QA" | "RE" | "RO" | "RS" | "RU" | "RW" | "SA" | "SB" | "SC" | "SD" | "SE" | "SG" | "SH" | "SI" | "SJ" | "SK" | "SL" | "SM" | "SN" | "SO" | "SR" | "SS" | "ST" | "SV" | "SX" | "SY" | "SZ" | "TC" | "TD" | "TF" | "TG" | "TH" | "TJ" | "TK" | "TL" | "TM" | "TN" | "TO" | "TR" | "TT" | "TV" | "TW" | "TZ" | "UA" | "UG" | "UM" | "US" | "UY" | "UZ" | "VA" | "VC" | "VE" | "VG" | "VI" | "VN" | "VU" | "WF" | "WS" | "YE" | "YT" | "ZA" | "ZM" | "ZW";
12519/** The 2-letter continent codes Cloudflare uses */
12520declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA";
12521type CfProperties<HostMetadata = unknown> = IncomingRequestCfProperties<HostMetadata> | RequestInitCfProperties;
12522interface D1Meta {
12523 duration: number;
12524 size_after: number;
12525 rows_read: number;
12526 rows_written: number;
12527 last_row_id: number;
12528 changed_db: boolean;
12529 changes: number;
12530 /**
12531 * The region of the database instance that executed the query.
12532 */
12533 served_by_region?: string;
12534 /**
12535 * The three letters airport code of the colo that executed the query.
12536 */
12537 served_by_colo?: string;
12538 /**
12539 * True if-and-only-if the database instance that executed the query was the primary.
12540 */
12541 served_by_primary?: boolean;
12542 timings?: {
12543 /**
12544 * The duration of the SQL query execution by the database instance. It doesn't include any network time.
12545 */
12546 sql_duration_ms: number;
12547 };
12548 /**
12549 * Number of total attempts to execute the query, due to automatic retries.
12550 * Note: All other fields in the response like `timings` only apply to the last attempt.
12551 */
12552 total_attempts?: number;
12553}
12554interface D1Response {
12555 success: true;
12556 meta: D1Meta & Record<string, unknown>;
12557 error?: never;
12558}
12559type D1Result<T = unknown> = D1Response & {
12560 results: T[];
12561};
12562interface D1ExecResult {
12563 count: number;
12564 duration: number;
12565}
12566type D1SessionConstraint =
12567// Indicates that the first query should go to the primary, and the rest queries
12568// using the same D1DatabaseSession will go to any replica that is consistent with
12569// the bookmark maintained by the session (returned by the first query).
12570'first-primary'
12571// Indicates that the first query can go anywhere (primary or replica), and the rest queries
12572// using the same D1DatabaseSession will go to any replica that is consistent with
12573// the bookmark maintained by the session (returned by the first query).
12574 | 'first-unconstrained';
12575type D1SessionBookmark = string;
12576declare abstract class D1Database {
12577 prepare(query: string): D1PreparedStatement;
12578 batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
12579 exec(query: string): Promise<D1ExecResult>;
12580 /**
12581 * Creates a new D1 Session anchored at the given constraint or the bookmark.
12582 * All queries executed using the created session will have sequential consistency,
12583 * meaning that all writes done through the session will be visible in subsequent reads.
12584 *
12585 * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session.
12586 */
12587 withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession;
12588 /**
12589 * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases.
12590 */
12591 dump(): Promise<ArrayBuffer>;
12592}
12593declare abstract class D1DatabaseSession {
12594 prepare(query: string): D1PreparedStatement;
12595 batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
12596 /**
12597 * @returns The latest session bookmark across all executed queries on the session.
12598 * If no query has been executed yet, `null` is returned.
12599 */
12600 getBookmark(): D1SessionBookmark | null;
12601}
12602declare abstract class D1PreparedStatement {
12603 bind(...values: unknown[]): D1PreparedStatement;
12604 first<T = unknown>(colName: string): Promise<T | null>;
12605 first<T = Record<string, unknown>>(): Promise<T | null>;
12606 run<T = Record<string, unknown>>(): Promise<D1Result<T>>;
12607 all<T = Record<string, unknown>>(): Promise<D1Result<T>>;
12608 raw<T = unknown[]>(options: {
12609 columnNames: true;
12610 }): Promise<[
12611 string[],
12612 ...T[]
12613 ]>;
12614 raw<T = unknown[]>(options?: {
12615 columnNames?: false;
12616 }): Promise<T[]>;
12617}
12618// `Disposable` was added to TypeScript's standard lib types in version 5.2.
12619// To support older TypeScript versions, define an empty `Disposable` interface.
12620// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2,
12621// but this will ensure type checking on older versions still passes.
12622// TypeScript's interface merging will ensure our empty interface is effectively
12623// ignored when `Disposable` is included in the standard lib.
12624interface Disposable {
12625}
12626/**
12627 * The returned data after sending an email
12628 */
12629interface EmailSendResult {
12630 /**
12631 * The Email Message ID
12632 */
12633 messageId: string;
12634}
12635/**
12636 * An email message that can be sent from a Worker.
12637 */
12638interface EmailMessage {
12639 /**
12640 * Envelope From attribute of the email message.
12641 */
12642 readonly from: string;
12643 /**
12644 * Envelope To attribute of the email message.
12645 */
12646 readonly to: string;
12647}
12648/**
12649 * An email message that is sent to a consumer Worker and can be rejected/forwarded.
12650 */
12651interface ForwardableEmailMessage extends EmailMessage {
12652 /**
12653 * Stream of the email message content.
12654 */
12655 readonly raw: ReadableStream<Uint8Array>;
12656 /**
12657 * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).
12658 */
12659 readonly headers: Headers;
12660 /**
12661 * Size of the email message content.
12662 */
12663 readonly rawSize: number;
12664 /**
12665 * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason.
12666 * @param reason The reject reason.
12667 * @returns void
12668 */
12669 setReject(reason: string): void;
12670 /**
12671 * Forward this email message to a verified destination address of the account.
12672 * @param rcptTo Verified destination address.
12673 * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).
12674 * @returns A promise that resolves when the email message is forwarded.
12675 */
12676 forward(rcptTo: string, headers?: Headers): Promise<EmailSendResult>;
12677 /**
12678 * Reply to the sender of this email message with a new EmailMessage object.
12679 * @param message The reply message.
12680 * @returns A promise that resolves when the email message is replied.
12681 */
12682 reply(message: EmailMessage): Promise<EmailSendResult>;
12683 /**
12684 * Reply to the sender of this email message with a message built from the given
12685 * fields. Threading headers (In-Reply-To/References) are set automatically.
12686 * @param builder The reply message contents.
12687 * @returns A promise that resolves when the email message is replied.
12688 */
12689 reply(builder: EmailReplyMessageBuilder): Promise<EmailSendResult>;
12690}
12691/** A file attachment for an email message */
12692type EmailAttachment = {
12693 disposition: 'inline';
12694 contentId: string;
12695 filename: string;
12696 type: string;
12697 content: string | ArrayBuffer | ArrayBufferView;
12698} | {
12699 disposition: 'attachment';
12700 contentId?: undefined;
12701 filename: string;
12702 type: string;
12703 content: string | ArrayBuffer | ArrayBufferView;
12704};
12705/** An Email Address */
12706interface EmailAddress {
12707 name: string;
12708 email: string;
12709}
12710/**
12711 * Recipient fields for `SendEmail.send()`. At least one of `to`, `cc`, or
12712 * `bcc` must be provided.
12713 */
12714type EmailDestinations = {
12715 to?: string | EmailAddress | (string | EmailAddress)[];
12716 cc?: string | EmailAddress | (string | EmailAddress)[];
12717 bcc?: string | EmailAddress | (string | EmailAddress)[];
12718} & ({
12719 to: string | EmailAddress | (string | EmailAddress)[];
12720} | {
12721 cc: string | EmailAddress | (string | EmailAddress)[];
12722} | {
12723 bcc: string | EmailAddress | (string | EmailAddress)[];
12724});
12725/**
12726 * Fields shared by all composed emails (no recipients). Used directly by
12727 * `ForwardableEmailMessage.reply()`, which always replies to the original
12728 * sender, and extended by `EmailMessageBuilder` for `SendEmail.send()`.
12729 */
12730interface EmailReplyMessageBuilder {
12731 from: string | EmailAddress;
12732 subject: string;
12733 replyTo?: string | EmailAddress;
12734 headers?: Record<string, string>;
12735 text?: string;
12736 html?: string;
12737 attachments?: EmailAttachment[];
12738}
12739/**
12740 * Fields for composing an email without constructing raw MIME, for
12741 * `SendEmail.send()`. Requires at least one of `to`, `cc`, or `bcc`.
12742 */
12743type EmailMessageBuilder = EmailReplyMessageBuilder & EmailDestinations;
12744/**
12745 * A binding that allows a Worker to send email messages.
12746 */
12747interface SendEmail {
12748 send(message: EmailMessage): Promise<EmailSendResult>;
12749 send(builder: EmailMessageBuilder): Promise<EmailSendResult>;
12750}
12751declare abstract class EmailEvent extends ExtendableEvent {
12752 readonly message: ForwardableEmailMessage;
12753}
12754declare type EmailExportedHandler<Env = unknown, Props = unknown> = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
12755declare module "cloudflare:email" {
12756 let _EmailMessage: {
12757 prototype: EmailMessage;
12758 new (from: string, to: string, raw: ReadableStream | string): EmailMessage;
12759 };
12760 export { _EmailMessage as EmailMessage };
12761}
12762/**
12763 * Evaluation context for targeting rules.
12764 * Keys are attribute names (e.g. "userId", "country"), values are the attribute values.
12765 */
12766type FlagshipEvaluationContext = Record<string, string | number | boolean>;
12767interface FlagshipEvaluationDetails<T> {
12768 flagKey: string;
12769 value: T;
12770 variant?: string | undefined;
12771 reason?: string | undefined;
12772 errorCode?: string | undefined;
12773 errorMessage?: string | undefined;
12774}
12775interface FlagshipEvaluationError extends Error {
12776}
12777/**
12778 * Feature flags binding for evaluating feature flags from a Cloudflare Workers script.
12779 *
12780 * @example
12781 * ```typescript
12782 * // Get a boolean flag value with a default
12783 * const enabled = await env.FLAGS.getBooleanValue('my-feature', false);
12784 *
12785 * // Get a flag value with evaluation context for targeting
12786 * const variant = await env.FLAGS.getStringValue('experiment', 'control', {
12787 * userId: 'user-123',
12788 * country: 'US',
12789 * });
12790 *
12791 * // Get full evaluation details including variant and reason
12792 * const details = await env.FLAGS.getBooleanDetails('my-feature', false);
12793 * console.log(details.variant, details.reason);
12794 * ```
12795 */
12796declare abstract class Flagship {
12797 /**
12798 * Get a flag value without type checking.
12799 * @param flagKey The key of the flag to evaluate.
12800 * @param defaultValue Optional default value returned when evaluation fails.
12801 * @param context Optional evaluation context for targeting rules.
12802 */
12803 get(flagKey: string, defaultValue?: unknown, context?: FlagshipEvaluationContext): Promise<unknown>;
12804 /**
12805 * Get a boolean flag value.
12806 * @param flagKey The key of the flag to evaluate.
12807 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
12808 * @param context Optional evaluation context for targeting rules.
12809 */
12810 getBooleanValue(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise<boolean>;
12811 /**
12812 * Get a string flag value.
12813 * @param flagKey The key of the flag to evaluate.
12814 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
12815 * @param context Optional evaluation context for targeting rules.
12816 */
12817 getStringValue(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise<string>;
12818 /**
12819 * Get a number flag value.
12820 * @param flagKey The key of the flag to evaluate.
12821 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
12822 * @param context Optional evaluation context for targeting rules.
12823 */
12824 getNumberValue(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise<number>;
12825 /**
12826 * Get an object flag value.
12827 * @param flagKey The key of the flag to evaluate.
12828 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
12829 * @param context Optional evaluation context for targeting rules.
12830 */
12831 getObjectValue<T extends object>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<T>;
12832 /**
12833 * Get a boolean flag value with full evaluation details.
12834 * @param flagKey The key of the flag to evaluate.
12835 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
12836 * @param context Optional evaluation context for targeting rules.
12837 */
12838 getBooleanDetails(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<boolean>>;
12839 /**
12840 * Get a string flag value with full evaluation details.
12841 * @param flagKey The key of the flag to evaluate.
12842 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
12843 * @param context Optional evaluation context for targeting rules.
12844 */
12845 getStringDetails(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<string>>;
12846 /**
12847 * Get a number flag value with full evaluation details.
12848 * @param flagKey The key of the flag to evaluate.
12849 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
12850 * @param context Optional evaluation context for targeting rules.
12851 */
12852 getNumberDetails(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<number>>;
12853 /**
12854 * Get an object flag value with full evaluation details.
12855 * @param flagKey The key of the flag to evaluate.
12856 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
12857 * @param context Optional evaluation context for targeting rules.
12858 */
12859 getObjectDetails<T extends object>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<T>>;
12860}
12861/**
12862 * Hello World binding to serve as an explanatory example. DO NOT USE
12863 */
12864interface HelloWorldBinding {
12865 /**
12866 * Retrieve the current stored value
12867 */
12868 get(): Promise<{
12869 value: string;
12870 ms?: number;
12871 }>;
12872 /**
12873 * Set a new stored value
12874 */
12875 set(value: string): Promise<void>;
12876}
12877interface Hyperdrive {
12878 /**
12879 * Connect directly to Hyperdrive as if it's your database, returning a TCP socket.
12880 *
12881 * Calling this method returns an identical socket to if you call
12882 * `connect("host:port")` using the `host` and `port` fields from this object.
12883 * Pick whichever approach works better with your preferred DB client library.
12884 *
12885 * Note that this socket is not yet authenticated -- it's expected that your
12886 * code (or preferably, the client library of your choice) will authenticate
12887 * using the information in this class's readonly fields.
12888 */
12889 connect(): Socket;
12890 /**
12891 * A valid DB connection string that can be passed straight into the typical
12892 * client library/driver/ORM. This will typically be the easiest way to use
12893 * Hyperdrive.
12894 */
12895 readonly connectionString: string;
12896 /*
12897 * A randomly generated hostname that is only valid within the context of the
12898 * currently running Worker which, when passed into `connect()` function from
12899 * the "cloudflare:sockets" module, will connect to the Hyperdrive instance
12900 * for your database.
12901 */
12902 readonly host: string;
12903 /*
12904 * A synthetic IPv4 address (in the reserved 240.0.0.0/4 range) that, like the
12905 * host field, is only valid within the context of the currently running
12906 * Worker and, when passed into the `connect()` function from the
12907 * "cloudflare:sockets" module, will connect to the Hyperdrive instance for
12908 * your database. This is provided for database drivers that require the host
12909 * to be an IP literal rather than a hostname.
12910 */
12911 readonly ip: string;
12912 /*
12913 * The port that must be paired the the host field when connecting.
12914 */
12915 readonly port: number;
12916 /*
12917 * The username to use when authenticating to your database via Hyperdrive.
12918 * Unlike the host and password, this will be the same every time
12919 */
12920 readonly user: string;
12921 /*
12922 * The randomly generated password to use when authenticating to your
12923 * database via Hyperdrive. Like the host field, this password is only valid
12924 * within the context of the currently running Worker instance from which
12925 * it's read.
12926 */
12927 readonly password: string;
12928 /*
12929 * The name of the database to connect to.
12930 */
12931 readonly database: string;
12932}
12933/**
12934 * A handle to a dynamically-provisioned Hyperdrive connection, returned by
12935 * `HyperdriveApi.get()`.
12936 */
12937interface HyperdriveDynamic extends Disposable {
12938 /**
12939 * The database name to use when connecting through this Hyperdrive.
12940 */
12941 readonly database: Promise<string>;
12942 /*
12943 * The randomly generated user to use when authenticating to your
12944 * database via Hyperdrive.
12945 */
12946 readonly user: Promise<string>;
12947 /*
12948 * The randomly generated password to use when authenticating to your
12949 * database via Hyperdrive.
12950 */
12951 readonly password: Promise<string>;
12952 /**
12953 * Open a TCP socket to the target database through this Hyperdrive.
12954 *
12955 */
12956 connect(): Promise<Socket>;
12957}
12958/**
12959 * Binding that provisions Hyperdrive connections at request time, rather than
12960 * from static configuration.
12961 */
12962interface HyperdriveDynamicApi {
12963 /**
12964 * Provision a connection for the database described by `args`.
12965 *
12966 */
12967 get(args: HyperdriveDynamicConfig): Promise<HyperdriveDynamic>;
12968 /**
12969 * Get a pre-generated connection string used for connecting to dynamic Hyperdrive.
12970 */
12971 getHyperdriveConnectionString(connectionString: string): Promise<string>;
12972}
12973/**
12974 * Parameters identifying the database that a dynamically-provisioned
12975 * Hyperdrive connection should target.
12976 */
12977interface HyperdriveDynamicConfig {
12978 /**
12979 * Generated connection string to pass into the dynamic worker.
12980 *
12981 */
12982 dynamicHyperdriveConnectionString: string;
12983 /**
12984 * Connection string for the origin database Hyperdrive should connect to.
12985 * Contains credentials, so treat it as a secret.
12986 *
12987 * The scheme selects the database engine. PostgreSQL origins are supported.
12988 */
12989 connectionString: string;
12990 /**
12991 * Region in which to place the connection pool. See the Hyperdrive
12992 * documentation for the set of supported regions.
12993 */
12994 targetRegion: string;
12995 /**
12996 * Whether Hyperdrive should cache query results for this connection.
12997 */
12998 cachingEnabled?: boolean;
12999 /**
13000 * Maximum number of connections the pool may open to the origin database.
13001 * Defaults to 60.
13002 */
13003 maxConnections?: number;
13004}
13005// Copyright (c) 2024 Cloudflare, Inc.
13006// Licensed under the Apache 2.0 license found in the LICENSE file or at:
13007// https://opensource.org/licenses/Apache-2.0
13008type ImageInfoResponse = {
13009 format: 'image/svg+xml';
13010} | {
13011 format: string;
13012 fileSize: number;
13013 width: number;
13014 height: number;
13015};
13016/**
13017 * Parameters for rasterizing text into an image.
13018 */
13019type TextRasterize = {
13020 /** The text content to render */
13021 content: string;
13022 /** rasterization options for the text **/
13023 options: TextOptions;
13024};
13025type TextOptions = {
13026 /** Font configuration */
13027 font: {
13028 /** URL to a font file in TrueType (.ttf), OpenType (.otf), WOFF (.woff), or WOFF2 (.woff2) format */
13029 url: string;
13030 };
13031 /** Font size in points (pt) */
13032 size?: number;
13033 /** Text color in CSS format: hex (#RRGGBB or #RRGGBBAA), rgb(r,g,b), rgba(r,g,b,a), or named colors */
13034 color?: string;
13035};
13036type ImageSource = ReadableStream<Uint8Array> | TextRasterize;
13037type ImageTransform = {
13038 width?: number;
13039 height?: number;
13040 background?: string;
13041 blur?: number;
13042 border?: {
13043 color?: string;
13044 width?: number;
13045 } | {
13046 top?: number;
13047 bottom?: number;
13048 left?: number;
13049 right?: number;
13050 };
13051 brightness?: number;
13052 contrast?: number;
13053 fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop';
13054 flip?: 'h' | 'v' | 'hv';
13055 gamma?: number;
13056 segment?: 'foreground';
13057 gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | {
13058 x?: number;
13059 y?: number;
13060 mode: 'remainder' | 'box-center';
13061 };
13062 rotate?: 0 | 90 | 180 | 270;
13063 saturation?: number;
13064 sharpen?: number;
13065 trim?: 'border' | {
13066 top?: number;
13067 bottom?: number;
13068 left?: number;
13069 right?: number;
13070 width?: number;
13071 height?: number;
13072 border?: boolean | {
13073 color?: string;
13074 tolerance?: number;
13075 keep?: number;
13076 };
13077 };
13078};
13079type ImageDrawOptions = {
13080 opacity?: number;
13081 repeat?: boolean | string;
13082 composite?: ImageCompositeMode;
13083 top?: number;
13084 left?: number;
13085 bottom?: number;
13086 right?: number;
13087};
13088type ImageCompositeMode =
13089/** Foreground drawn on top of backdrop (default) */
13090'over'
13091/** Foreground shown only where backdrop is opaque */
13092 | 'in'
13093/** Foreground drawn on top, but clipped to the backdrop's shape */
13094 | 'atop'
13095/** Foreground shown only where backdrop is transparent */
13096 | 'out'
13097/** Foreground and backdrop visible only where the other is not */
13098 | 'xor'
13099/** Foreground and backdrop channels added (brightening) */
13100 | 'lighter';
13101type ImageInputOptions = {
13102 encoding?: 'base64';
13103};
13104type ImageOutputOptions = {
13105 format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba';
13106 quality?: number;
13107 background?: string;
13108 anim?: boolean;
13109};
13110interface ImageMetadata {
13111 id: string;
13112 filename?: string;
13113 uploaded?: string;
13114 requireSignedURLs: boolean;
13115 meta?: Record<string, unknown>;
13116 variants: string[];
13117 draft?: boolean;
13118 creator?: string;
13119}
13120interface ImageUploadOptions {
13121 id?: string;
13122 filename?: string;
13123 requireSignedURLs?: boolean;
13124 metadata?: Record<string, unknown>;
13125 creator?: string;
13126 /**
13127 * If 'base64', the input data will be decoded from base64 before processing
13128 */
13129 encoding?: 'base64';
13130}
13131interface ImageUpdateOptions {
13132 requireSignedURLs?: boolean;
13133 metadata?: Record<string, unknown>;
13134 creator?: string;
13135}
13136type ImageMetadataFilterOperators = {
13137 eq?: string | number | boolean;
13138 in?: string[] | number[];
13139 gt?: number;
13140 gte?: number;
13141 lt?: number;
13142 lte?: number;
13143};
13144type ImageMetadataFilterValue = string | number | boolean | ImageMetadataFilterOperators;
13145interface ImageListFilter {
13146 metadata?: Record<string, ImageMetadataFilterValue>;
13147}
13148interface ImageListOptions {
13149 limit?: number;
13150 cursor?: string;
13151 sortOrder?: 'asc' | 'desc';
13152 creator?: string;
13153 filter?: ImageListFilter;
13154}
13155interface ImageSignedUrlOptions {
13156 variant: string;
13157 expiresIn?: number;
13158 keyName?: string;
13159}
13160interface ImageDirectUploadOptions {
13161 id?: string;
13162 requireSignedURLs?: boolean;
13163 metadata?: Record<string, unknown>;
13164 creator?: string;
13165 expiresIn?: number;
13166}
13167interface ImageDirectUploadResult {
13168 id: string;
13169 uploadURL: string;
13170}
13171interface ImageList {
13172 images: ImageMetadata[];
13173 cursor?: string;
13174 listComplete: boolean;
13175}
13176interface ImageHandle {
13177 /**
13178 * Get metadata for a hosted image
13179 * @returns Image metadata, or null if not found
13180 */
13181 details(): Promise<ImageMetadata | null>;
13182 /**
13183 * Get the raw image data for a hosted image
13184 * @returns ReadableStream of image bytes, or null if not found
13185 */
13186 bytes(): Promise<ReadableStream<Uint8Array> | null>;
13187 /**
13188 * Generate a signed delivery URL for this hosted image.
13189 * @param options Signing configuration
13190 * @returns A signed image delivery URL
13191 * @throws {@link ImagesError} if signing fails
13192 */
13193 signedUrl(options: ImageSignedUrlOptions): Promise<string>;
13194 /**
13195 * Update hosted image metadata
13196 * @param options Properties to update
13197 * @returns Updated image metadata
13198 * @throws {@link ImagesError} if update fails
13199 */
13200 update(options: ImageUpdateOptions): Promise<ImageMetadata>;
13201 /**
13202 * Delete a hosted image
13203 * @returns True if deleted, false if not found
13204 */
13205 delete(): Promise<boolean>;
13206}
13207interface HostedImagesBinding {
13208 /**
13209 * Get a handle for a hosted image
13210 * @param imageId The ID of the image (UUID or custom ID)
13211 * @returns A handle for per-image operations
13212 */
13213 image(imageId: string): ImageHandle;
13214 /**
13215 * Upload a new hosted image
13216 * @param image The image file to upload
13217 * @param options Upload configuration
13218 * @returns Metadata for the uploaded image
13219 * @throws {@link ImagesError} if upload fails
13220 */
13221 upload(image: ReadableStream<Uint8Array> | ArrayBuffer, options?: ImageUploadOptions): Promise<ImageMetadata>;
13222 /**
13223 * List hosted images with pagination
13224 * @param options List configuration
13225 * @returns List of images with pagination info
13226 * @throws {@link ImagesError} if list fails
13227 */
13228 list(options?: ImageListOptions): Promise<ImageList>;
13229 /**
13230 * Create a Direct Creator Upload link, letting an end user upload an
13231 * image straight to Cloudflare without exposing an API token
13232 * @param options Upload link configuration
13233 * @returns The new image ID and the upload URL to hand to the end user
13234 * @throws {@link ImagesError} if creation fails
13235 */
13236 createDirectUpload(options?: ImageDirectUploadOptions): Promise<ImageDirectUploadResult>;
13237}
13238interface ImagesBinding {
13239 /**
13240 * Get image metadata (type, width and height)
13241 * @throws {@link ImagesError} with code 9412 if input is not an image
13242 * @param stream The image bytes
13243 */
13244 info(stream: ReadableStream<Uint8Array>, options?: ImageInputOptions): Promise<ImageInfoResponse>;
13245 /**
13246 * Begin applying a series of transformations to an image
13247 * @param stream The image bytes
13248 * @returns A transform handle
13249 */
13250 input(stream: ReadableStream<Uint8Array>, options?: ImageInputOptions): ImageTransformer;
13251 /**
13252 * Begin applying a series of transformations to text
13253 * @param content string to be rendered
13254 * @param options font, optional color and size to use in rendering text
13255 * @returns A transform handle
13256 */
13257 text(content: string, options: TextOptions): ImageTransformer;
13258 /**
13259 * Access hosted images CRUD operations
13260 */
13261 readonly hosted: HostedImagesBinding;
13262}
13263interface ImageTransformer {
13264 /**
13265 * Apply transform next, returning a transform handle.
13266 * You can then apply more transformations, draw, or retrieve the output.
13267 * @param transform
13268 */
13269 transform(transform: ImageTransform): ImageTransformer;
13270 /**
13271 * Draw an image on this transformer, returning a transform handle.
13272 * You can then apply more transformations, draw, or retrieve the output.
13273 * @param image The image (or transformer that will give the image) to draw
13274 * @param options The options configuring how to draw the image
13275 */
13276 draw(image: ReadableStream<Uint8Array> | ImageTransformer, options?: ImageDrawOptions): ImageTransformer;
13277 /**
13278 * Retrieve the image that results from applying the transforms to the
13279 * provided input
13280 * @param options Options that apply to the output e.g. output format
13281 */
13282 output(options: ImageOutputOptions): Promise<ImageTransformationResult>;
13283}
13284type ImageTransformationOutputOptions = {
13285 encoding?: 'base64';
13286};
13287type ImageTransformationResponseOptions = {
13288 headers?: HeadersInit;
13289};
13290interface ImageTransformationResult {
13291 /**
13292 * The image as a response, ready to store in cache or return to users
13293 * @param options Options that apply to the returned response, e.g. additional headers
13294 */
13295 response(options?: ImageTransformationResponseOptions): Response;
13296 /**
13297 * The content type of the returned image
13298 */
13299 contentType(): string;
13300 /**
13301 * The bytes of the response
13302 */
13303 image(options?: ImageTransformationOutputOptions): ReadableStream<Uint8Array>;
13304}
13305interface ImagesError extends Error {
13306 readonly code: number;
13307 readonly message: string;
13308 readonly stack?: string;
13309}
13310/**
13311 * Media binding for transforming media streams.
13312 * Provides the entry point for media transformation operations.
13313 */
13314interface MediaBinding {
13315 /**
13316 * Creates a media transformer from an input stream.
13317 * @param media - The input media bytes
13318 * @returns A MediaTransformer instance for applying transformations
13319 */
13320 input(media: ReadableStream<Uint8Array>): MediaTransformer;
13321}
13322/**
13323 * Media transformer for applying transformation operations to media content.
13324 * Handles sizing, fitting, and other input transformation parameters.
13325 */
13326interface MediaTransformer {
13327 /**
13328 * Applies transformation options to the media content.
13329 * @param transform - Configuration for how the media should be transformed
13330 * @returns A generator for producing the transformed media output
13331 */
13332 transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator;
13333 /**
13334 * Generates the final media output with specified options.
13335 * @param output - Configuration for the output format and parameters
13336 * @returns The final transformation result containing the transformed media
13337 */
13338 output(output?: MediaTransformationOutputOptions): MediaTransformationResult;
13339}
13340/**
13341 * Generator for producing media transformation results.
13342 * Configures the output format and parameters for the transformed media.
13343 */
13344interface MediaTransformationGenerator {
13345 /**
13346 * Generates the final media output with specified options.
13347 * @param output - Configuration for the output format and parameters
13348 * @returns The final transformation result containing the transformed media
13349 */
13350 output(output?: MediaTransformationOutputOptions): MediaTransformationResult;
13351}
13352/**
13353 * Result of a media transformation operation.
13354 * Provides multiple ways to access the transformed media content.
13355 */
13356interface MediaTransformationResult {
13357 /**
13358 * Returns the transformed media as a readable stream of bytes.
13359 * @returns A promise containing a readable stream with the transformed media
13360 */
13361 media(): Promise<ReadableStream<Uint8Array>>;
13362 /**
13363 * Returns the transformed media as an HTTP response object.
13364 * @returns The transformed media as a Promise<Response>, ready to store in cache or return to users
13365 */
13366 response(): Promise<Response>;
13367 /**
13368 * Returns the MIME type of the transformed media.
13369 * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4')
13370 */
13371 contentType(): Promise<string>;
13372}
13373/**
13374 * Configuration options for transforming media input.
13375 * Controls how the media should be resized and fitted.
13376 */
13377type MediaTransformationInputOptions = {
13378 /** How the media should be resized to fit the specified dimensions */
13379 fit?: 'contain' | 'cover' | 'scale-down';
13380 /** Target width in pixels */
13381 width?: number;
13382 /** Target height in pixels */
13383 height?: number;
13384};
13385/**
13386 * Configuration options for Media Transformations output.
13387 * Controls the format, timing, and type of the generated output.
13388 */
13389type MediaTransformationOutputOptions = {
13390 /**
13391 * Output mode determining the type of media to generate
13392 */
13393 mode?: 'video' | 'spritesheet' | 'frame' | 'audio';
13394 /** Whether to include audio in the output */
13395 audio?: boolean;
13396 /**
13397 * Starting timestamp for frame extraction or start time for clips. (e.g. '2s').
13398 */
13399 time?: string;
13400 /**
13401 * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s').
13402 */
13403 duration?: string;
13404 /**
13405 * Number of frames in the spritesheet.
13406 */
13407 imageCount?: number;
13408 /**
13409 * Output format for the generated media.
13410 */
13411 format?: 'jpg' | 'png' | 'm4a';
13412};
13413/**
13414 * Error object for media transformation operations.
13415 * Extends the standard Error interface with additional media-specific information.
13416 */
13417interface MediaError extends Error {
13418 readonly code: number;
13419 readonly message: string;
13420 readonly stack?: string;
13421}
13422declare module 'cloudflare:node' {
13423 interface NodeStyleServer {
13424 listen(...args: unknown[]): this;
13425 address(): {
13426 port?: number | null | undefined;
13427 };
13428 }
13429 export function httpServerHandler(port: number): ExportedHandler;
13430 export function httpServerHandler(options: {
13431 port: number;
13432 }): ExportedHandler;
13433 export function httpServerHandler(server: NodeStyleServer): ExportedHandler;
13434}
13435type Params<P extends string = any> = Record<P, string | string[]>;
13436type EventContext<Env, P extends string, Data> = {
13437 request: Request<unknown, IncomingRequestCfProperties<unknown>>;
13438 functionPath: string;
13439 waitUntil: (promise: Promise<any>) => void;
13440 passThroughOnException: () => void;
13441 next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
13442 env: Env & {
13443 ASSETS: {
13444 fetch: typeof fetch;
13445 };
13446 };
13447 params: Params<P>;
13448 data: Data;
13449};
13450type PagesFunction<Env = unknown, Params extends string = any, Data extends Record<string, unknown> = Record<string, unknown>> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>;
13451type EventPluginContext<Env, P extends string, Data, PluginArgs> = {
13452 request: Request<unknown, IncomingRequestCfProperties<unknown>>;
13453 functionPath: string;
13454 waitUntil: (promise: Promise<any>) => void;
13455 passThroughOnException: () => void;
13456 next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
13457 env: Env & {
13458 ASSETS: {
13459 fetch: typeof fetch;
13460 };
13461 };
13462 params: Params<P>;
13463 data: Data;
13464 pluginArgs: PluginArgs;
13465};
13466type PagesPluginFunction<Env = unknown, Params extends string = any, Data extends Record<string, unknown> = Record<string, unknown>, PluginArgs = unknown> = (context: EventPluginContext<Env, Params, Data, PluginArgs>) => Response | Promise<Response>;
13467declare module "assets:*" {
13468 export const onRequest: PagesFunction;
13469}
13470// Copyright (c) 2022-2023 Cloudflare, Inc.
13471// Licensed under the Apache 2.0 license found in the LICENSE file or at:
13472// https://opensource.org/licenses/Apache-2.0
13473declare module "cloudflare:pipelines" {
13474 export abstract class PipelineTransformationEntrypoint<Env = unknown, I extends PipelineRecord = PipelineRecord, O extends PipelineRecord = PipelineRecord> {
13475 protected env: Env;
13476 protected ctx: ExecutionContext;
13477 constructor(ctx: ExecutionContext, env: Env);
13478 /**
13479 * run receives an array of PipelineRecord which can be
13480 * transformed and returned to the pipeline
13481 * @param records Incoming records from the pipeline to be transformed
13482 * @param metadata Information about the specific pipeline calling the transformation entrypoint
13483 * @returns A promise containing the transformed PipelineRecord array
13484 */
13485 public run(records: I[], metadata: PipelineBatchMetadata): Promise<O[]>;
13486 }
13487 export type PipelineRecord = Record<string, unknown>;
13488 export type PipelineBatchMetadata = {
13489 pipelineId: string;
13490 pipelineName: string;
13491 };
13492 export interface Pipeline<T extends PipelineRecord = PipelineRecord> {
13493 /**
13494 * The Pipeline interface represents the type of a binding to a Pipeline
13495 *
13496 * @param records The records to send to the pipeline
13497 */
13498 send(records: T[]): Promise<void>;
13499 }
13500}
13501// PubSubMessage represents an incoming PubSub message.
13502// The message includes metadata about the broker, the client, and the payload
13503// itself.
13504// https://developers.cloudflare.com/pub-sub/
13505interface PubSubMessage {
13506 // Message ID
13507 readonly mid: number;
13508 // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT
13509 readonly broker: string;
13510 // The MQTT topic the message was sent on.
13511 readonly topic: string;
13512 // The client ID of the client that published this message.
13513 readonly clientId: string;
13514 // The unique identifier (JWT ID) used by the client to authenticate, if token
13515 // auth was used.
13516 readonly jti?: string;
13517 // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker
13518 // received the message from the client.
13519 readonly receivedAt: number;
13520 // An (optional) string with the MIME type of the payload, if set by the
13521 // client.
13522 readonly contentType: string;
13523 // Set to 1 when the payload is a UTF-8 string
13524 // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063
13525 readonly payloadFormatIndicator: number;
13526 // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays.
13527 // You can use payloadFormatIndicator to inspect this before decoding.
13528 payload: string | Uint8Array;
13529}
13530// JsonWebKey extended by kid parameter
13531interface JsonWebKeyWithKid extends JsonWebKey {
13532 // Key Identifier of the JWK
13533 readonly kid: string;
13534}
13535interface RateLimitOptions {
13536 key: string;
13537}
13538interface RateLimitOutcome {
13539 success: boolean;
13540}
13541interface RateLimit {
13542 /**
13543 * Rate limit a request based on the provided options.
13544 * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/
13545 * @returns A promise that resolves with the outcome of the rate limit.
13546 */
13547 limit(options: RateLimitOptions): Promise<RateLimitOutcome>;
13548}
13549// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need
13550// to referenced by `Fetcher`. This is included in the "importable" version of the types which
13551// strips all `module` blocks.
13552declare namespace Rpc {
13553 // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s.
13554 // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`.
13555 // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to
13556 // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape)
13557 export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND';
13558 export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND';
13559 export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND';
13560 export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND';
13561 export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND';
13562 export interface RpcTargetBranded {
13563 [__RPC_TARGET_BRAND]: never;
13564 }
13565 export interface WorkerEntrypointBranded {
13566 [__WORKER_ENTRYPOINT_BRAND]: never;
13567 }
13568 export interface DurableObjectBranded {
13569 [__DURABLE_OBJECT_BRAND]: never;
13570 }
13571 export interface WorkflowEntrypointBranded {
13572 [__WORKFLOW_ENTRYPOINT_BRAND]: never;
13573 }
13574 export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded;
13575 // Types that can be used through `Stub`s
13576 export type Stubable = RpcTargetBranded | ((...args: any[]) => any);
13577 // Types that can be passed over RPC
13578 // The reason for using a generic type here is to build a serializable subset of structured
13579 // cloneable composite types. This allows types defined with the "interface" keyword to pass the
13580 // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
13581 type Serializable<T> =
13582 // Structured cloneables
13583 BaseType
13584 // Structured cloneable composites
13585 | Map<T extends Map<infer U, unknown> ? Serializable<U> : never, T extends Map<unknown, infer U> ? Serializable<U> : never> | Set<T extends Set<infer U> ? Serializable<U> : never> | ReadonlyArray<T extends ReadonlyArray<infer U> ? Serializable<U> : never> | {
13586 [K in keyof T]: K extends number | string ? Serializable<T[K]> : never;
13587 }
13588 // Special types
13589 | Stub<Stubable>
13590 // Serialized as stubs, see `Stubify`
13591 | Stubable;
13592 // Base type for all RPC stubs, including common memory management methods.
13593 // `T` is used as a marker type for unwrapping `Stub`s later.
13594 interface StubBase<T extends Stubable> extends Disposable {
13595 [__RPC_STUB_BRAND]: T;
13596 dup(): this;
13597 }
13598 export type Stub<T extends Stubable> = Provider<T> & StubBase<T>;
13599 // This represents all the types that can be sent as-is over an RPC boundary
13600 type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream<Uint8Array> | WritableStream<Uint8Array> | Request | Response | Headers;
13601 // Recursively rewrite all `Stubable` types with `Stub`s
13602 // prettier-ignore
13603 type Stubify<T> = T extends Stubable ? Stub<T> : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T : T extends {
13604 [key: string | number]: any;
13605 } ? {
13606 [K in keyof T]: Stubify<T[K]>;
13607 } : T;
13608 // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.
13609 // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:
13610 // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.
13611 // prettier-ignore
13612 type Unstubify<T> = T extends StubBase<infer V> ? V : T extends Map<infer K, infer V> ? Map<Unstubify<K>, Unstubify<V>> : T extends Set<infer V> ? Set<Unstubify<V>> : T extends Array<infer V> ? Array<Unstubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Unstubify<V>> : T extends BaseType ? T : T extends {
13613 [key: string | number]: unknown;
13614 } ? {
13615 [K in keyof T]: Unstubify<T[K]>;
13616 } : T;
13617 type UnstubifyAll<A extends any[]> = {
13618 [I in keyof A]: Unstubify<A[I]>;
13619 };
13620 // Utility type for adding `Provider`/`Disposable`s to `object` types only.
13621 // Note `unknown & T` is equivalent to `T`.
13622 type MaybeProvider<T> = T extends object ? Provider<T> : unknown;
13623 type MaybeDisposable<T> = T extends object ? Disposable : unknown;
13624 // Type for method return or property on an RPC interface.
13625 // - Stubable types are replaced by stubs.
13626 // - Serializable types are passed by value, with stubable types replaced by stubs
13627 // and a top-level `Disposer`.
13628 // Everything else can't be passed over PRC.
13629 // Technically, we use custom thenables here, but they quack like `Promise`s.
13630 // Intersecting with `(Maybe)Provider` allows pipelining.
13631 // prettier-ignore
13632 type Result<R> = R extends Stubable ? Promise<Stub<R>> & Provider<R> : R extends Serializable<R> ? Promise<Stubify<R> & MaybeDisposable<R>> & MaybeProvider<R> : never;
13633 // Type for method or property on an RPC interface.
13634 // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
13635 // Unwrapping `Stub`s allows calling with `Stubable` arguments.
13636 // For properties, rewrite types to be `Result`s.
13637 // In each case, unwrap `Promise`s.
13638 type MethodOrProperty<V> = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>;
13639 // Type for the callable part of an `Provider` if `T` is callable.
13640 // This is intersected with methods/properties.
13641 type MaybeCallableProvider<T> = T extends (...args: any[]) => any ? MethodOrProperty<T> : unknown;
13642 // Base type for all other types providing RPC-like interfaces.
13643 // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
13644 // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC.
13645 export type Provider<T extends object, Reserved extends string = never> = MaybeCallableProvider<T> & Pick<{
13646 [K in keyof T]: MethodOrProperty<T[K]>;
13647 }, Exclude<keyof T, Reserved | symbol | keyof StubBase<never>>>;
13648}
13649declare namespace Cloudflare {
13650 // Type of `env`.
13651 //
13652 // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript
13653 // will merge all declarations.
13654 //
13655 // You can use `wrangler types` to generate the `Env` type automatically.
13656 interface Env {
13657 }
13658 // Project-specific parameters used to inform types.
13659 //
13660 // This interface is, again, intended to be declared in project-specific files, and then that
13661 // declaration will be merged with this one.
13662 //
13663 // A project should have a declaration like this:
13664 //
13665 // interface GlobalProps {
13666 // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type
13667 // // of `ctx.exports`.
13668 // mainModule: typeof import("my-main-module");
13669 //
13670 // // Declares which of the main module's exports are configured with durable storage, and
13671 // // thus should behave as Durable Object namsepace bindings.
13672 // durableNamespaces: "MyDurableObject" | "AnotherDurableObject";
13673 // }
13674 //
13675 // You can use `wrangler types` to generate `GlobalProps` automatically.
13676 interface GlobalProps {
13677 }
13678 // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not
13679 // present.
13680 type GlobalProp<K extends string, Default> = K extends keyof GlobalProps ? GlobalProps[K] : Default;
13681 // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the
13682 // `mainModule` property.
13683 type MainModule = GlobalProp<"mainModule", {}>;
13684 // The type of ctx.exports, which contains loopback bindings for all top-level exports.
13685 type Exports = {
13686 [K in keyof MainModule]: LoopbackForExport<MainModule[K]>
13687 // If the export is listed in `durableNamespaces`, then it is also a
13688 // DurableObjectNamespace.
13689 & (K extends GlobalProp<"durableNamespaces", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace<DoInstance> : DurableObjectNamespace<undefined> : DurableObjectNamespace<undefined> : {});
13690 };
13691}
13692declare namespace CloudflareWorkersModule {
13693 export type RpcStub<T extends Rpc.Stubable> = Rpc.Stub<T>;
13694 export const RpcStub: {
13695 new <T extends Rpc.Stubable>(value: T): Rpc.Stub<T>;
13696 };
13697 export abstract class RpcTarget implements Rpc.RpcTargetBranded {
13698 [Rpc.__RPC_TARGET_BRAND]: never;
13699 }
13700 // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC
13701 export abstract class WorkerEntrypoint<Env = Cloudflare.Env, Props = {}> implements Rpc.WorkerEntrypointBranded {
13702 [Rpc.__WORKER_ENTRYPOINT_BRAND]: never;
13703 protected ctx: ExecutionContext<Props>;
13704 protected env: Env;
13705 constructor(ctx: ExecutionContext, env: Env);
13706 email?(message: ForwardableEmailMessage): void | Promise<void>;
13707 fetch?(request: Request): Response | Promise<Response>;
13708 connect?(socket: Socket): void | Promise<void>;
13709 queue?(batch: MessageBatch): void | Promise<void>;
13710 scheduled?(controller: ScheduledController): void | Promise<void>;
13711 tail?(events: TraceItem[]): void | Promise<void>;
13712 tailStream?(event: TailStream.TailEvent<TailStream.Onset>): TailStream.TailEventHandlerType | Promise<TailStream.TailEventHandlerType>;
13713 test?(controller: TestController): void | Promise<void>;
13714 trace?(traces: TraceItem[]): void | Promise<void>;
13715 }
13716 export abstract class DurableObject<Env = Cloudflare.Env, Props = {}> implements Rpc.DurableObjectBranded {
13717 [Rpc.__DURABLE_OBJECT_BRAND]: never;
13718 protected ctx: DurableObjectState<Props>;
13719 protected env: Env;
13720 constructor(ctx: DurableObjectState, env: Env);
13721 alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;
13722 fetch?(request: Request): Response | Promise<Response>;
13723 connect?(socket: Socket): void | Promise<void>;
13724 webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;
13725 webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;
13726 webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;
13727 }
13728 export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
13729 export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;
13730 export type WorkflowDelayDuration = WorkflowSleepDuration;
13731 export type WorkflowDynamicDelayContext = {
13732 ctx: WorkflowStepContext<WorkflowDelayFunction>;
13733 error: Error;
13734 };
13735 export type WorkflowDelayFunction = (input: WorkflowDynamicDelayContext) => WorkflowDelayDuration | Promise<WorkflowDelayDuration>;
13736 export type WorkflowTimeoutDuration = WorkflowSleepDuration;
13737 export type WorkflowRetentionDuration = WorkflowSleepDuration;
13738 export type WorkflowBackoff = 'constant' | 'linear' | 'exponential';
13739 export type WorkflowStepSensitivity = 'output';
13740 export type WorkflowStepConfig = {
13741 retries?: {
13742 limit: number;
13743 delay: WorkflowDelayDuration | number | WorkflowDelayFunction;
13744 backoff?: WorkflowBackoff;
13745 };
13746 timeout?: WorkflowTimeoutDuration | number;
13747 sensitive?: WorkflowStepSensitivity;
13748 };
13749 // Internal discriminators used only for `WorkflowStep.do` overload
13750 // resolution. They mirror `WorkflowStepConfig` but pin `retries.delay` to a
13751 // single kind so the callback context can be narrowed based on the shape of
13752 // the config argument (rather than on an inferred type parameter, which is
13753 // lost when the caller supplies an explicit return-type argument). Not
13754 // exported: they must not widen the public type surface.
13755 type WorkflowStepConfigWithStaticDelay = Omit<WorkflowStepConfig, 'retries'> & {
13756 retries?: {
13757 limit: number;
13758 delay: WorkflowDelayDuration | number;
13759 backoff?: WorkflowBackoff;
13760 };
13761 };
13762 type WorkflowStepConfigWithDelayFunction = Omit<WorkflowStepConfig, 'retries'> & {
13763 retries: {
13764 limit: number;
13765 delay: WorkflowDelayFunction;
13766 backoff?: WorkflowBackoff;
13767 };
13768 };
13769 export type WorkflowStepRollbackConfig = Pick<WorkflowStepConfig, 'retries' | 'timeout'>;
13770 export type WorkflowCronSchedule = {
13771 /** Cron expression that triggered this event. */
13772 cron: string;
13773 /** Timestamp of the scheduled trigger, in milliseconds since the Unix epoch. */
13774 scheduledTime: number;
13775 };
13776 export type WorkflowEvent<T> = {
13777 payload: Readonly<T>;
13778 timestamp: Date;
13779 instanceId: string;
13780 workflowName: string;
13781 schedule?: WorkflowCronSchedule;
13782 };
13783 export type WorkflowStepEvent<T> = {
13784 payload: Readonly<T>;
13785 timestamp: Date;
13786 type: string;
13787 sensitive?: WorkflowStepSensitivity;
13788 };
13789 export type WorkflowStepContext<Delay = WorkflowDelayDuration | number> = {
13790 step: {
13791 name: string;
13792 count: number;
13793 };
13794 attempt: number;
13795 config: {
13796 retries?: {
13797 limit: number;
13798 backoff?: WorkflowBackoff;
13799 } & (Delay extends WorkflowDelayFunction ? {} : {
13800 delay: WorkflowDelayDuration | number;
13801 });
13802 timeout?: WorkflowTimeoutDuration | number;
13803 sensitive?: WorkflowStepSensitivity;
13804 };
13805 };
13806 // The rollback handler receives the step context, so it mirrors the same
13807 // delay discriminant as the step callback: when the step was configured with
13808 // a dynamic delay function the resolved `config.retries.delay` is omitted,
13809 // otherwise it is present. `Delay` is threaded from the `WorkflowStep.do`
13810 // overload that matched the step config.
13811 export type WorkflowRollbackContext<T = unknown, Delay = WorkflowDelayDuration | number> = {
13812 ctx: WorkflowStepContext<Delay>;
13813 error: Error;
13814 output: T | undefined;
13815 /** @deprecated Use `ctx.step.name` and `ctx.step.count` instead. */
13816 stepName: string;
13817 };
13818 export type WorkflowRollbackHandler<T = unknown, Delay = WorkflowDelayDuration | number> = (ctx: WorkflowRollbackContext<T, Delay>) => Promise<void>;
13819 export type WorkflowStepRollbackOptions<T = unknown, Delay = WorkflowDelayDuration | number> = {
13820 rollback: WorkflowRollbackHandler<T, Delay>;
13821 rollbackConfig?: WorkflowStepRollbackConfig;
13822 };
13823 export abstract class WorkflowStep {
13824 do<T extends Rpc.Serializable<T>>(name: string, callback: (ctx: WorkflowStepContext) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;
13825 // The config overloads discriminate on the shape of `config.retries.delay`
13826 // so the callback context reflects whether the resolved delay is present
13827 // (static delay) or omitted (dynamic delay function). Each has a single
13828 // type parameter, so an explicit return-type argument (`do<T>(...)`) still
13829 // resolves here. ORDERING IS LOAD-BEARING: the broad `WorkflowStepConfig`
13830 // fallback MUST remain last, otherwise it shadows the discriminating
13831 // overloads and narrowing is silently lost.
13832 do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfigWithDelayFunction, callback: (ctx: WorkflowStepContext<WorkflowDelayFunction>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T, WorkflowDelayFunction>): Promise<T>;
13833 do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfigWithStaticDelay, callback: (ctx: WorkflowStepContext<WorkflowDelayDuration | number>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T, WorkflowDelayDuration | number>): Promise<T>;
13834 do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;
13835 sleep: (name: string, duration: WorkflowSleepDuration) => Promise<void>;
13836 sleepUntil: (name: string, timestamp: Date | number) => Promise<void>;
13837 waitForEvent<T extends Rpc.Serializable<T>>(name: string, options: {
13838 type: string;
13839 timeout?: WorkflowTimeoutDuration | number;
13840 }): Promise<WorkflowStepEvent<T>>;
13841 }
13842 export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown';
13843 export abstract class WorkflowEntrypoint<Env = unknown, T extends Rpc.Serializable<T> | unknown = unknown> implements Rpc.WorkflowEntrypointBranded {
13844 [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never;
13845 protected ctx: ExecutionContext;
13846 protected env: Env;
13847 constructor(ctx: ExecutionContext, env: Env);
13848 run(event: Readonly<WorkflowEvent<T>>, step: WorkflowStep): Promise<unknown>;
13849 }
13850 export function waitUntil(promise: Promise<unknown>): void;
13851 export function withEnv(newEnv: unknown, fn: () => unknown): unknown;
13852 export function withExports(newExports: unknown, fn: () => unknown): unknown;
13853 export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown;
13854 export const env: Cloudflare.Env;
13855 export const exports: Cloudflare.Exports;
13856 export const cache: CacheContext;
13857 export const tracing: Tracing;
13858}
13859declare module 'cloudflare:workers' {
13860 export = CloudflareWorkersModule;
13861}
13862interface SecretsStoreSecret {
13863 /**
13864 * Get a secret from the Secrets Store, returning a string of the secret value
13865 * if it exists, or throws an error if it does not exist
13866 */
13867 get(): Promise<string>;
13868}
13869declare module "cloudflare:sockets" {
13870 function _connect(address: string | SocketAddress, options?: SocketOptions): Socket;
13871 export { _connect as connect };
13872}
13873/**
13874 * Binding entrypoint for Cloudflare Stream.
13875 *
13876 * Usage:
13877 * - Binding-level operations:
13878 * `await env.STREAM.videos.upload`
13879 * `await env.STREAM.videos.createDirectUpload`
13880 * `await env.STREAM.videos.*`
13881 * `await env.STREAM.watermarks.*`
13882 * - Per-video operations:
13883 * `await env.STREAM.video(id).downloads.*`
13884 * `await env.STREAM.video(id).captions.*`
13885 *
13886 * Example usage:
13887 * ```ts
13888 * await env.STREAM.video(id).downloads.generate();
13889 *
13890 * const video = env.STREAM.video(id)
13891 * const captions = video.captions.list();
13892 * const videoDetails = video.details()
13893 * ```
13894 */
13895interface StreamBinding {
13896 /**
13897 * Returns a handle scoped to a single video for per-video operations.
13898 * @param id The unique identifier for the video.
13899 * @returns A handle for per-video operations.
13900 */
13901 video(id: string): StreamVideoHandle;
13902 /**
13903 * Uploads a new video from a provided URL.
13904 * @param url The URL to upload from.
13905 * @param params Optional upload parameters.
13906 * @returns The uploaded video details.
13907 * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid
13908 * @throws {QuotaReachedError} if the account storage capacity is exceeded
13909 * @throws {MaxFileSizeError} if the file size is too large
13910 * @throws {RateLimitedError} if the server received too many requests
13911 * @throws {AlreadyUploadedError} if a video was already uploaded to this URL
13912 * @throws {InternalError} if an unexpected error occurs
13913 */
13914 upload(url: string, params?: StreamUrlUploadParams): Promise<StreamVideo>;
13915 /**
13916 * Creates a direct upload that allows video uploads without an API key.
13917 * @param params Parameters for the direct upload
13918 * @returns The direct upload details.
13919 * @throws {BadRequestError} if the parameters are invalid
13920 * @throws {RateLimitedError} if the server received too many requests
13921 * @throws {InternalError} if an unexpected error occurs
13922 */
13923 createDirectUpload(params: StreamDirectUploadCreateParams): Promise<StreamDirectUpload>;
13924 videos: StreamVideos;
13925 watermarks: StreamWatermarks;
13926}
13927/**
13928 * Handle for operations scoped to a single Stream video.
13929 */
13930interface StreamVideoHandle {
13931 /**
13932 * The unique identifier for the video.
13933 */
13934 id: string;
13935 /**
13936 * Get a full videos details
13937 * @returns The full video details.
13938 * @throws {NotFoundError} if the video is not found
13939 * @throws {InternalError} if an unexpected error occurs
13940 */
13941 details(): Promise<StreamVideo>;
13942 /**
13943 * Update details for a single video.
13944 * @param params The fields to update for the video.
13945 * @returns The updated video details.
13946 * @throws {NotFoundError} if the video is not found
13947 * @throws {BadRequestError} if the parameters are invalid
13948 * @throws {InternalError} if an unexpected error occurs
13949 */
13950 update(params: StreamUpdateVideoParams): Promise<StreamVideo>;
13951 /**
13952 * Deletes a video and its copies from Cloudflare Stream.
13953 * @returns A promise that resolves when deletion completes.
13954 * @throws {NotFoundError} if the video is not found
13955 * @throws {InternalError} if an unexpected error occurs
13956 */
13957 delete(): Promise<void>;
13958 /**
13959 * Creates a signed URL token for a video.
13960 * @returns The signed token that was created.
13961 * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed
13962 */
13963 generateToken(): Promise<string>;
13964 downloads: StreamScopedDownloads;
13965 captions: StreamScopedCaptions;
13966}
13967interface StreamVideo {
13968 /**
13969 * The unique identifier for the video.
13970 */
13971 id: string;
13972 /**
13973 * A user-defined identifier for the media creator.
13974 */
13975 creator: string | null;
13976 /**
13977 * The thumbnail URL for the video.
13978 */
13979 thumbnail: string;
13980 /**
13981 * The thumbnail timestamp percentage.
13982 */
13983 thumbnailTimestampPct: number;
13984 /**
13985 * Indicates whether the video is ready to stream.
13986 */
13987 readyToStream: boolean;
13988 /**
13989 * The date and time the video became ready to stream.
13990 */
13991 readyToStreamAt: string | null;
13992 /**
13993 * Processing status information.
13994 */
13995 status: StreamVideoStatus;
13996 /**
13997 * A user modifiable key-value store.
13998 */
13999 meta: Record<string, string>;
14000 /**
14001 * The date and time the video was created.
14002 */
14003 created: string;
14004 /**
14005 * The date and time the video was last modified.
14006 */
14007 modified: string;
14008 /**
14009 * The date and time at which the video will be deleted.
14010 */
14011 scheduledDeletion: string | null;
14012 /**
14013 * The size of the video in bytes.
14014 */
14015 size: number;
14016 /**
14017 * The preview URL for the video.
14018 */
14019 preview?: string;
14020 /**
14021 * Origins allowed to display the video.
14022 */
14023 allowedOrigins: Array<string>;
14024 /**
14025 * Indicates whether signed URLs are required.
14026 */
14027 requireSignedURLs: boolean | null;
14028 /**
14029 * The date and time the video was uploaded.
14030 */
14031 uploaded: string | null;
14032 /**
14033 * The date and time when the upload URL expires.
14034 */
14035 uploadExpiry: string | null;
14036 /**
14037 * The maximum size in bytes for direct uploads.
14038 */
14039 maxSizeBytes: number | null;
14040 /**
14041 * The maximum duration in seconds for direct uploads.
14042 */
14043 maxDurationSeconds: number | null;
14044 /**
14045 * The video duration in seconds. -1 indicates unknown.
14046 */
14047 duration: number;
14048 /**
14049 * Input metadata for the original upload.
14050 */
14051 input: StreamVideoInput;
14052 /**
14053 * Playback URLs for the video.
14054 */
14055 hlsPlaybackUrl: string;
14056 dashPlaybackUrl: string;
14057 /**
14058 * The watermark applied to the video, if any.
14059 */
14060 watermark: StreamWatermark | null;
14061 /**
14062 * The live input id associated with the video, if any.
14063 */
14064 liveInputId?: string | null;
14065 /**
14066 * The source video id if this is a clip.
14067 */
14068 clippedFromId: string | null;
14069 /**
14070 * Public details associated with the video.
14071 */
14072 publicDetails: StreamPublicDetails | null;
14073}
14074type StreamVideoStatus = {
14075 /**
14076 * The current processing state.
14077 */
14078 state: string;
14079 /**
14080 * The current processing step.
14081 */
14082 step?: string;
14083 /**
14084 * The percent complete as a string.
14085 */
14086 pctComplete?: string;
14087 /**
14088 * An error reason code, if applicable.
14089 */
14090 errorReasonCode: string;
14091 /**
14092 * An error reason text, if applicable.
14093 */
14094 errorReasonText: string;
14095};
14096type StreamVideoInput = {
14097 /**
14098 * The input width in pixels.
14099 */
14100 width: number;
14101 /**
14102 * The input height in pixels.
14103 */
14104 height: number;
14105};
14106type StreamPublicDetails = {
14107 /**
14108 * The public title for the video.
14109 */
14110 title: string | null;
14111 /**
14112 * The public share link.
14113 */
14114 share_link: string | null;
14115 /**
14116 * The public channel link.
14117 */
14118 channel_link: string | null;
14119 /**
14120 * The public logo URL.
14121 */
14122 logo: string | null;
14123};
14124type StreamDirectUpload = {
14125 /**
14126 * The URL an unauthenticated upload can use for a single multipart request.
14127 */
14128 uploadURL: string;
14129 /**
14130 * A Cloudflare-generated unique identifier for a media item.
14131 */
14132 id: string;
14133 /**
14134 * The watermark profile applied to the upload.
14135 */
14136 watermark: StreamWatermark | null;
14137 /**
14138 * The scheduled deletion time, if any.
14139 */
14140 scheduledDeletion: string | null;
14141};
14142type StreamDirectUploadCreateParams = {
14143 /**
14144 * The maximum duration in seconds for a video upload.
14145 */
14146 maxDurationSeconds: number;
14147 /**
14148 * The date and time after upload when videos will not be accepted.
14149 */
14150 expiry?: string;
14151 /**
14152 * A user-defined identifier for the media creator.
14153 */
14154 creator?: string;
14155 /**
14156 * A user modifiable key-value store used to reference other systems of record for
14157 * managing videos.
14158 */
14159 meta?: Record<string, string>;
14160 /**
14161 * Lists the origins allowed to display the video.
14162 */
14163 allowedOrigins?: Array<string>;
14164 /**
14165 * Indicates whether the video can be accessed using the id. When set to `true`,
14166 * a signed token must be generated with a signing key to view the video.
14167 */
14168 requireSignedURLs?: boolean;
14169 /**
14170 * The thumbnail timestamp percentage.
14171 */
14172 thumbnailTimestampPct?: number;
14173 /**
14174 * The date and time at which the video will be deleted. Include `null` to remove
14175 * a scheduled deletion.
14176 */
14177 scheduledDeletion?: string | null;
14178 /**
14179 * The watermark profile to apply.
14180 */
14181 watermark?: StreamDirectUploadWatermark;
14182};
14183type StreamDirectUploadWatermark = {
14184 /**
14185 * The unique identifier for the watermark profile.
14186 */
14187 id: string;
14188};
14189type StreamUrlUploadParams = {
14190 /**
14191 * Lists the origins allowed to display the video. Enter allowed origin
14192 * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the
14193 * video to be viewed on any origin.
14194 */
14195 allowedOrigins?: Array<string>;
14196 /**
14197 * A user-defined identifier for the media creator.
14198 */
14199 creator?: string;
14200 /**
14201 * A user modifiable key-value store used to reference other systems of
14202 * record for managing videos.
14203 */
14204 meta?: Record<string, string>;
14205 /**
14206 * Indicates whether the video can be a accessed using the id. When
14207 * set to `true`, a signed token must be generated with a signing key to view the
14208 * video.
14209 */
14210 requireSignedURLs?: boolean;
14211 /**
14212 * Indicates the date and time at which the video will be deleted. Omit
14213 * the field to indicate no change, or include with a `null` value to remove an
14214 * existing scheduled deletion. If specified, must be at least 30 days from upload
14215 * time.
14216 */
14217 scheduledDeletion?: string | null;
14218 /**
14219 * The timestamp for a thumbnail image calculated as a percentage value
14220 * of the video's duration. To convert from a second-wise timestamp to a
14221 * percentage, divide the desired timestamp by the total duration of the video. If
14222 * this value is not set, the default thumbnail image is taken from 0s of the
14223 * video.
14224 */
14225 thumbnailTimestampPct?: number;
14226 /**
14227 * The identifier for the watermark profile
14228 */
14229 watermarkId?: string;
14230};
14231interface StreamScopedCaptions {
14232 /**
14233 * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language.
14234 * One caption or subtitle file per language is allowed.
14235 * @param language The BCP 47 language tag for the caption or subtitle.
14236 * @param input The caption or subtitle stream to upload.
14237 * @returns The created caption entry.
14238 * @throws {NotFoundError} if the video is not found
14239 * @throws {BadRequestError} if the language or file is invalid
14240 * @throws {InternalError} if an unexpected error occurs
14241 */
14242 upload(language: string, input: ReadableStream): Promise<StreamCaption>;
14243 /**
14244 * Generate captions or subtitles for the provided language via AI.
14245 * @param language The BCP 47 language tag to generate.
14246 * @returns The generated caption entry.
14247 * @throws {NotFoundError} if the video is not found
14248 * @throws {BadRequestError} if the language is invalid
14249 * @throws {StreamError} if a generated caption already exists
14250 * @throws {StreamError} if the video duration is too long
14251 * @throws {StreamError} if the video is missing audio
14252 * @throws {StreamError} if the requested language is not supported
14253 * @throws {InternalError} if an unexpected error occurs
14254 */
14255 generate(language: string): Promise<StreamCaption>;
14256 /**
14257 * Lists the captions or subtitles.
14258 * Use the language parameter to filter by a specific language.
14259 * @param language The optional BCP 47 language tag to filter by.
14260 * @returns The list of captions or subtitles.
14261 * @throws {NotFoundError} if the video or caption is not found
14262 * @throws {InternalError} if an unexpected error occurs
14263 */
14264 list(language?: string): Promise<StreamCaption[]>;
14265 /**
14266 * Removes the captions or subtitles from a video.
14267 * @param language The BCP 47 language tag to remove.
14268 * @returns A promise that resolves when deletion completes.
14269 * @throws {NotFoundError} if the video or caption is not found
14270 * @throws {InternalError} if an unexpected error occurs
14271 */
14272 delete(language: string): Promise<void>;
14273}
14274interface StreamScopedDownloads {
14275 /**
14276 * Generates a download for a video when a video is ready to view. Available
14277 * types are `default` and `audio`. Defaults to `default` when omitted.
14278 * @param downloadType The download type to create.
14279 * @returns The current downloads for the video.
14280 * @throws {NotFoundError} if the video is not found
14281 * @throws {BadRequestError} if the download type is invalid
14282 * @throws {StreamError} if the video duration is too long to generate a download
14283 * @throws {StreamError} if the video is not ready to stream
14284 * @throws {InternalError} if an unexpected error occurs
14285 */
14286 generate(downloadType?: StreamDownloadType): Promise<StreamDownloadGetResponse>;
14287 /**
14288 * Lists the downloads created for a video.
14289 * @returns The current downloads for the video.
14290 * @throws {NotFoundError} if the video or downloads are not found
14291 * @throws {InternalError} if an unexpected error occurs
14292 */
14293 get(): Promise<StreamDownloadGetResponse>;
14294 /**
14295 * Delete the downloads for a video. Available types are `default` and `audio`.
14296 * Defaults to `default` when omitted.
14297 * @param downloadType The download type to delete.
14298 * @returns A promise that resolves when deletion completes.
14299 * @throws {NotFoundError} if the video or downloads are not found
14300 * @throws {InternalError} if an unexpected error occurs
14301 */
14302 delete(downloadType?: StreamDownloadType): Promise<void>;
14303}
14304interface StreamVideos {
14305 /**
14306 * Lists all videos in a users account.
14307 * @returns The list of videos.
14308 * @throws {BadRequestError} if the parameters are invalid
14309 * @throws {InternalError} if an unexpected error occurs
14310 */
14311 list(params?: StreamVideosListParams): Promise<StreamVideo[]>;
14312}
14313interface StreamWatermarks {
14314 /**
14315 * Generate a new watermark profile
14316 * @param input The image stream to upload
14317 * @param params The watermark creation parameters.
14318 * @returns The created watermark profile.
14319 * @throws {BadRequestError} if the parameters are invalid
14320 * @throws {InvalidURLError} if the URL is invalid
14321 * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached
14322 * @throws {InternalError} if an unexpected error occurs
14323 */
14324 generate(input: ReadableStream, params: StreamWatermarkCreateParams): Promise<StreamWatermark>;
14325 /**
14326 * Generate a new watermark profile
14327 * @param url The image url to upload
14328 * @param params The watermark creation parameters.
14329 * @returns The created watermark profile.
14330 * @throws {BadRequestError} if the parameters are invalid
14331 * @throws {InvalidURLError} if the URL is invalid
14332 * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached
14333 * @throws {InternalError} if an unexpected error occurs
14334 */
14335 generate(url: string, params: StreamWatermarkCreateParams): Promise<StreamWatermark>;
14336 /**
14337 * Lists all watermark profiles for an account.
14338 * @returns The list of watermark profiles.
14339 * @throws {InternalError} if an unexpected error occurs
14340 */
14341 list(): Promise<StreamWatermark[]>;
14342 /**
14343 * Retrieves details for a single watermark profile.
14344 * @param watermarkId The watermark profile identifier.
14345 * @returns The watermark profile details.
14346 * @throws {NotFoundError} if the watermark is not found
14347 * @throws {InternalError} if an unexpected error occurs
14348 */
14349 get(watermarkId: string): Promise<StreamWatermark>;
14350 /**
14351 * Deletes a watermark profile.
14352 * @param watermarkId The watermark profile identifier.
14353 * @returns A promise that resolves when deletion completes.
14354 * @throws {NotFoundError} if the watermark is not found
14355 * @throws {InternalError} if an unexpected error occurs
14356 */
14357 delete(watermarkId: string): Promise<void>;
14358}
14359type StreamUpdateVideoParams = {
14360 /**
14361 * Lists the origins allowed to display the video. Enter allowed origin
14362 * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the
14363 * video to be viewed on any origin.
14364 */
14365 allowedOrigins?: Array<string>;
14366 /**
14367 * A user-defined identifier for the media creator.
14368 */
14369 creator?: string;
14370 /**
14371 * The maximum duration in seconds for a video upload. Can be set for a
14372 * video that is not yet uploaded to limit its duration. Uploads that exceed the
14373 * specified duration will fail during processing. A value of `-1` means the value
14374 * is unknown.
14375 */
14376 maxDurationSeconds?: number;
14377 /**
14378 * A user modifiable key-value store used to reference other systems of
14379 * record for managing videos.
14380 */
14381 meta?: Record<string, string>;
14382 /**
14383 * Indicates whether the video can be a accessed using the id. When
14384 * set to `true`, a signed token must be generated with a signing key to view the
14385 * video.
14386 */
14387 requireSignedURLs?: boolean;
14388 /**
14389 * Indicates the date and time at which the video will be deleted. Omit
14390 * the field to indicate no change, or include with a `null` value to remove an
14391 * existing scheduled deletion. If specified, must be at least 30 days from upload
14392 * time.
14393 */
14394 scheduledDeletion?: string | null;
14395 /**
14396 * The timestamp for a thumbnail image calculated as a percentage value
14397 * of the video's duration. To convert from a second-wise timestamp to a
14398 * percentage, divide the desired timestamp by the total duration of the video. If
14399 * this value is not set, the default thumbnail image is taken from 0s of the
14400 * video.
14401 */
14402 thumbnailTimestampPct?: number;
14403};
14404type StreamCaption = {
14405 /**
14406 * Whether the caption was generated via AI.
14407 */
14408 generated?: boolean;
14409 /**
14410 * The language label displayed in the native language to users.
14411 */
14412 label: string;
14413 /**
14414 * The language tag in BCP 47 format.
14415 */
14416 language: string;
14417 /**
14418 * The status of a generated caption.
14419 */
14420 status?: 'ready' | 'inprogress' | 'error';
14421};
14422type StreamDownloadStatus = 'ready' | 'inprogress' | 'error';
14423type StreamDownloadType = 'default' | 'audio';
14424type StreamDownload = {
14425 /**
14426 * Indicates the progress as a percentage between 0 and 100.
14427 */
14428 percentComplete: number;
14429 /**
14430 * The status of a generated download.
14431 */
14432 status: StreamDownloadStatus;
14433 /**
14434 * The URL to access the generated download.
14435 */
14436 url?: string;
14437};
14438/**
14439 * An object with download type keys. Each key is optional and only present if that
14440 * download type has been created.
14441 */
14442type StreamDownloadGetResponse = {
14443 /**
14444 * The audio-only download. Only present if this download type has been created.
14445 */
14446 audio?: StreamDownload;
14447 /**
14448 * The default video download. Only present if this download type has been created.
14449 */
14450 default?: StreamDownload;
14451};
14452type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center';
14453type StreamWatermark = {
14454 /**
14455 * The unique identifier for a watermark profile.
14456 */
14457 id: string;
14458 /**
14459 * The size of the image in bytes.
14460 */
14461 size: number;
14462 /**
14463 * The height of the image in pixels.
14464 */
14465 height: number;
14466 /**
14467 * The width of the image in pixels.
14468 */
14469 width: number;
14470 /**
14471 * The date and a time a watermark profile was created.
14472 */
14473 created: string;
14474 /**
14475 * The source URL for a downloaded image. If the watermark profile was created via
14476 * direct upload, this field is null.
14477 */
14478 downloadedFrom: string | null;
14479 /**
14480 * A short description of the watermark profile.
14481 */
14482 name: string;
14483 /**
14484 * The translucency of the image. A value of `0.0` makes the image completely
14485 * transparent, and `1.0` makes the image completely opaque. Note that if the image
14486 * is already semi-transparent, setting this to `1.0` will not make the image
14487 * completely opaque.
14488 */
14489 opacity: number;
14490 /**
14491 * The whitespace between the adjacent edges (determined by position) of the video
14492 * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded
14493 * video width or length, as determined by the algorithm.
14494 */
14495 padding: number;
14496 /**
14497 * The size of the image relative to the overall size of the video. This parameter
14498 * will adapt to horizontal and vertical videos automatically. `0.0` indicates no
14499 * scaling (use the size of the image as-is), and `1.0 `fills the entire video.
14500 */
14501 scale: number;
14502 /**
14503 * The location of the image. Valid positions are: `upperRight`, `upperLeft`,
14504 * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the
14505 * `padding` parameter.
14506 */
14507 position: StreamWatermarkPosition;
14508};
14509type StreamWatermarkCreateParams = {
14510 /**
14511 * A short description of the watermark profile.
14512 */
14513 name?: string;
14514 /**
14515 * The translucency of the image. A value of `0.0` makes the image completely
14516 * transparent, and `1.0` makes the image completely opaque. Note that if the
14517 * image is already semi-transparent, setting this to `1.0` will not make the
14518 * image completely opaque.
14519 */
14520 opacity?: number;
14521 /**
14522 * The whitespace between the adjacent edges (determined by position) of the
14523 * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully
14524 * padded video width or length, as determined by the algorithm.
14525 */
14526 padding?: number;
14527 /**
14528 * The size of the image relative to the overall size of the video. This
14529 * parameter will adapt to horizontal and vertical videos automatically. `0.0`
14530 * indicates no scaling (use the size of the image as-is), and `1.0 `fills the
14531 * entire video.
14532 */
14533 scale?: number;
14534 /**
14535 * The location of the image.
14536 */
14537 position?: StreamWatermarkPosition;
14538};
14539type StreamVideosListParams = {
14540 /**
14541 * The maximum number of videos to return.
14542 */
14543 limit?: number;
14544 /**
14545 * Return videos created before this timestamp.
14546 * (RFC3339/RFC3339Nano)
14547 */
14548 before?: string;
14549 /**
14550 * Comparison operator for the `before` field.
14551 * @default 'lt'
14552 */
14553 beforeComp?: StreamPaginationComparison;
14554 /**
14555 * Return videos created after this timestamp.
14556 * (RFC3339/RFC3339Nano)
14557 */
14558 after?: string;
14559 /**
14560 * Comparison operator for the `after` field.
14561 * @default 'gte'
14562 */
14563 afterComp?: StreamPaginationComparison;
14564};
14565type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte';
14566/**
14567 * Error object for Stream binding operations.
14568 */
14569interface StreamError extends Error {
14570 readonly code: number;
14571 readonly statusCode: number;
14572 readonly message: string;
14573 readonly stack?: string;
14574}
14575interface InternalError extends StreamError {
14576 name: 'InternalError';
14577}
14578interface BadRequestError extends StreamError {
14579 name: 'BadRequestError';
14580}
14581interface NotFoundError extends StreamError {
14582 name: 'NotFoundError';
14583}
14584interface ForbiddenError extends StreamError {
14585 name: 'ForbiddenError';
14586}
14587interface RateLimitedError extends StreamError {
14588 name: 'RateLimitedError';
14589}
14590interface QuotaReachedError extends StreamError {
14591 name: 'QuotaReachedError';
14592}
14593interface MaxFileSizeError extends StreamError {
14594 name: 'MaxFileSizeError';
14595}
14596interface InvalidURLError extends StreamError {
14597 name: 'InvalidURLError';
14598}
14599interface AlreadyUploadedError extends StreamError {
14600 name: 'AlreadyUploadedError';
14601}
14602interface TooManyWatermarksError extends StreamError {
14603 name: 'TooManyWatermarksError';
14604}
14605type MarkdownDocument = {
14606 name: string;
14607 blob: Blob;
14608};
14609type OutputFormat = 'markdown' | 'text';
14610type ConversionResponse = {
14611 id: string;
14612 name: string;
14613 mimeType: string;
14614 format: OutputFormat;
14615 tokens: number;
14616 data: string;
14617} | {
14618 id: string;
14619 name: string;
14620 mimeType: string;
14621 format: 'error';
14622 error: string;
14623};
14624type ImageConversionOptions = {
14625 descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de';
14626};
14627type EmbeddedImageConversionOptions = ImageConversionOptions & {
14628 convert?: boolean;
14629 maxConvertedImages?: number;
14630};
14631type ConversionOutputOptions = {
14632 format?: OutputFormat;
14633};
14634type ConversionOptions = {
14635 output?: ConversionOutputOptions;
14636 html?: {
14637 images?: EmbeddedImageConversionOptions & {
14638 convertOGImage?: boolean;
14639 };
14640 hostname?: string;
14641 cssSelector?: string;
14642 };
14643 docx?: {
14644 images?: EmbeddedImageConversionOptions;
14645 };
14646 image?: ImageConversionOptions;
14647 pdf?: {
14648 images?: EmbeddedImageConversionOptions;
14649 metadata?: boolean;
14650 };
14651};
14652type ConversionRequestOptions = {
14653 gateway?: GatewayOptions;
14654 extraHeaders?: object;
14655 conversionOptions?: ConversionOptions;
14656};
14657type SupportedFileFormat = {
14658 mimeType: string;
14659 extension: string;
14660};
14661declare abstract class ToMarkdownService {
14662 transform(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise<ConversionResponse[]>;
14663 transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise<ConversionResponse>;
14664 supported(): Promise<SupportedFileFormat[]>;
14665}
14666declare namespace TailStream {
14667 interface Header {
14668 readonly name: string;
14669 readonly value: string;
14670 }
14671 interface FetchEventInfo {
14672 readonly type: "fetch";
14673 readonly method: string;
14674 readonly url: string;
14675 readonly cfJson?: object;
14676 readonly headers: Header[];
14677 }
14678 interface JsRpcEventInfo {
14679 readonly type: "jsrpc";
14680 }
14681 interface ScheduledEventInfo {
14682 readonly type: "scheduled";
14683 readonly scheduledTime: Date;
14684 readonly cron: string;
14685 }
14686 interface AlarmEventInfo {
14687 readonly type: "alarm";
14688 readonly scheduledTime: Date;
14689 }
14690 interface QueueEventInfo {
14691 readonly type: "queue";
14692 readonly queueName: string;
14693 readonly batchSize: number;
14694 }
14695 interface EmailEventInfo {
14696 readonly type: "email";
14697 readonly mailFrom: string;
14698 readonly rcptTo: string;
14699 readonly rawSize: number;
14700 }
14701 interface TraceEventInfo {
14702 readonly type: "trace";
14703 readonly traces: (string | null)[];
14704 }
14705 interface HibernatableWebSocketEventInfoMessage {
14706 readonly type: "message";
14707 }
14708 interface HibernatableWebSocketEventInfoError {
14709 readonly type: "error";
14710 }
14711 interface HibernatableWebSocketEventInfoClose {
14712 readonly type: "close";
14713 readonly code: number;
14714 readonly wasClean: boolean;
14715 }
14716 interface HibernatableWebSocketEventInfo {
14717 readonly type: "hibernatableWebSocket";
14718 readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage;
14719 }
14720 interface CustomEventInfo {
14721 readonly type: "custom";
14722 }
14723 interface FetchResponseInfo {
14724 readonly type: "fetch";
14725 readonly statusCode: number;
14726 }
14727 interface ConnectEventInfo {
14728 readonly type: "connect";
14729 }
14730 type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound" | "internalError" | "exceededWallTime" | "aborted";
14731 interface ScriptVersion {
14732 readonly id: string;
14733 readonly tag?: string;
14734 readonly message?: string;
14735 }
14736 interface TracePreviewInfo {
14737 readonly id: string;
14738 readonly slug: string;
14739 readonly name: string;
14740 }
14741 interface Onset {
14742 readonly type: "onset";
14743 readonly attributes: Attribute[];
14744 // id for the span being opened by this Onset event.
14745 readonly spanId: string;
14746 readonly dispatchNamespace?: string;
14747 readonly entrypoint?: string;
14748 readonly executionModel: string;
14749 readonly durableObjectId?: string;
14750 readonly scriptName?: string;
14751 readonly scriptTags?: string[];
14752 readonly scriptVersion?: ScriptVersion;
14753 readonly preview?: TracePreviewInfo;
14754 readonly info: FetchEventInfo | ConnectEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo;
14755 }
14756 interface Outcome {
14757 readonly type: "outcome";
14758 readonly outcome: EventOutcome;
14759 readonly cpuTime: number;
14760 readonly wallTime: number;
14761 }
14762 interface SpanOpen {
14763 readonly type: "spanOpen";
14764 readonly name: string;
14765 // id for the span being opened by this SpanOpen event.
14766 readonly spanId: string;
14767 readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes;
14768 }
14769 interface SpanClose {
14770 readonly type: "spanClose";
14771 readonly outcome: EventOutcome;
14772 }
14773 interface DiagnosticChannelEvent {
14774 readonly type: "diagnosticChannel";
14775 readonly channel: string;
14776 readonly message: any;
14777 }
14778 interface Exception {
14779 readonly type: "exception";
14780 readonly code?: string | number;
14781 readonly name: string;
14782 readonly message: string;
14783 readonly stack?: string;
14784 }
14785 interface TailStreamErrorInfo {
14786 readonly name: string;
14787 readonly message: string;
14788 readonly stack?: string;
14789 }
14790 type Log = {
14791 readonly type: "log";
14792 readonly level: "debug" | "error" | "info" | "log" | "warn";
14793 readonly errorInfo?: readonly (TailStreamErrorInfo | null)[];
14794 } & ({
14795 readonly message: object;
14796 readonly truncated?: false;
14797 } | {
14798 readonly message: string;
14799 readonly truncated: true;
14800 });
14801 interface DroppedEventsDiagnostic {
14802 readonly diagnosticsType: "droppedEvents";
14803 readonly count: number;
14804 }
14805 interface StreamDiagnostic {
14806 readonly type: 'streamDiagnostic';
14807 // To add new diagnostic types, define a new interface and add it to this union type.
14808 readonly diagnostic: DroppedEventsDiagnostic;
14809 }
14810 // This marks the worker handler return information.
14811 // This is separate from Outcome because the worker invocation can live for a long time after
14812 // returning. For example - Websockets that return an http upgrade response but then continue
14813 // streaming information or SSE http connections.
14814 interface Return {
14815 readonly type: "return";
14816 readonly info?: FetchResponseInfo;
14817 }
14818 interface Attribute {
14819 readonly name: string;
14820 readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[];
14821 }
14822 interface Attributes {
14823 readonly type: "attributes";
14824 readonly info: Attribute[];
14825 }
14826 type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes;
14827 // Context in which this trace event lives.
14828 interface SpanContext {
14829 // Single id for the entire top-level invocation
14830 // This should be a new traceId for the first worker stage invoked in the eyeball request and then
14831 // same-account service-bindings should reuse the same traceId but cross-account service-bindings
14832 // should use a new traceId.
14833 readonly traceId: string;
14834 // spanId in which this event is handled
14835 // for Onset and SpanOpen events this would be the parent span id
14836 // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events
14837 // For Hibernate and Mark this would be the span under which they were emitted.
14838 // spanId is not set ONLY if:
14839 // 1. This is an Onset event
14840 // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation)
14841 readonly spanId?: string;
14842 // W3C trace flags from an upstream traceparent. Absent when no upstream
14843 // sampling decision was made.
14844 readonly traceFlags?: number;
14845 }
14846 interface TailEvent<Event extends EventType> {
14847 // invocation id of the currently invoked worker stage.
14848 // invocation id will always be unique to every Onset event and will be the same until the Outcome event.
14849 readonly invocationId: string;
14850 // Inherited spanContext for this event.
14851 readonly spanContext: SpanContext;
14852 readonly timestamp: Date;
14853 readonly sequence: number;
14854 readonly event: Event;
14855 }
14856 type TailEventHandler<Event extends EventType = EventType> = (event: TailEvent<Event>) => void | Promise<void>;
14857 type TailEventHandlerObject = {
14858 outcome?: TailEventHandler<Outcome>;
14859 spanOpen?: TailEventHandler<SpanOpen>;
14860 spanClose?: TailEventHandler<SpanClose>;
14861 diagnosticChannel?: TailEventHandler<DiagnosticChannelEvent>;
14862 exception?: TailEventHandler<Exception>;
14863 log?: TailEventHandler<Log>;
14864 return?: TailEventHandler<Return>;
14865 attributes?: TailEventHandler<Attributes>;
14866 };
14867 type TailEventHandlerType = TailEventHandler | TailEventHandlerObject;
14868}
14869// Copyright (c) 2022-2023 Cloudflare, Inc.
14870// Licensed under the Apache 2.0 license found in the LICENSE file or at:
14871// https://opensource.org/licenses/Apache-2.0
14872/**
14873 * Data types supported for holding vector metadata.
14874 */
14875type VectorizeVectorMetadataValue = string | number | boolean | string[];
14876/**
14877 * Additional information to associate with a vector.
14878 */
14879type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record<string, VectorizeVectorMetadataValue>;
14880type VectorFloatArray = Float32Array | Float64Array;
14881interface VectorizeError {
14882 code?: number;
14883 error: string;
14884}
14885/**
14886 * Comparison logic/operation to use for metadata filtering.
14887 *
14888 * This list is expected to grow as support for more operations are released.
14889 */
14890type VectorizeVectorMetadataFilterOp = '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte';
14891type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin';
14892/**
14893 * Filter criteria for vector metadata used to limit the retrieved query result set.
14894 */
14895type VectorizeVectorMetadataFilter = {
14896 [field: string]: Exclude<VectorizeVectorMetadataValue, string[]> | null | {
14897 [Op in VectorizeVectorMetadataFilterOp]?: Exclude<VectorizeVectorMetadataValue, string[]> | null;
14898 } | {
14899 [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude<VectorizeVectorMetadataValue, string[]>[];
14900 };
14901};
14902/**
14903 * Supported distance metrics for an index.
14904 * Distance metrics determine how other "similar" vectors are determined.
14905 */
14906type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product";
14907/**
14908 * Metadata return levels for a Vectorize query.
14909 *
14910 * Default to "none".
14911 *
14912 * @property all Full metadata for the vector return set, including all fields (including those un-indexed) without truncation. This is a more expensive retrieval, as it requires additional fetching & reading of un-indexed data.
14913 * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings).
14914 * @property none No indexed metadata will be returned.
14915 */
14916type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none";
14917interface VectorizeQueryOptions {
14918 topK?: number;
14919 namespace?: string;
14920 returnValues?: boolean;
14921 returnMetadata?: boolean | VectorizeMetadataRetrievalLevel;
14922 filter?: VectorizeVectorMetadataFilter;
14923}
14924/**
14925 * Information about the configuration of an index.
14926 */
14927type VectorizeIndexConfig = {
14928 dimensions: number;
14929 metric: VectorizeDistanceMetric;
14930} | {
14931 preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity
14932};
14933/**
14934 * Metadata about an existing index.
14935 *
14936 * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.
14937 * See {@link VectorizeIndexInfo} for its post-beta equivalent.
14938 */
14939interface VectorizeIndexDetails {
14940 /** The unique ID of the index */
14941 readonly id: string;
14942 /** The name of the index. */
14943 name: string;
14944 /** (optional) A human readable description for the index. */
14945 description?: string;
14946 /** The index configuration, including the dimension size and distance metric. */
14947 config: VectorizeIndexConfig;
14948 /** The number of records containing vectors within the index. */
14949 vectorsCount: number;
14950}
14951/**
14952 * Metadata about an existing index.
14953 */
14954interface VectorizeIndexInfo {
14955 /** The number of records containing vectors within the index. */
14956 vectorCount: number;
14957 /** Number of dimensions the index has been configured for. */
14958 dimensions: number;
14959 /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */
14960 processedUpToDatetime: number;
14961 /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */
14962 processedUpToMutation: number;
14963}
14964/**
14965 * Represents a single vector value set along with its associated metadata.
14966 */
14967interface VectorizeVector {
14968 /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */
14969 id: string;
14970 /** The vector values */
14971 values: VectorFloatArray | number[];
14972 /** The namespace this vector belongs to. */
14973 namespace?: string;
14974 /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */
14975 metadata?: Record<string, VectorizeVectorMetadata>;
14976}
14977/**
14978 * Represents a matched vector for a query along with its score and (if specified) the matching vector information.
14979 */
14980type VectorizeMatch = Pick<Partial<VectorizeVector>, "values"> & Omit<VectorizeVector, "values"> & {
14981 /** The score or rank for similarity, when returned as a result */
14982 score: number;
14983};
14984/**
14985 * A set of matching {@link VectorizeMatch} for a particular query.
14986 */
14987interface VectorizeMatches {
14988 matches: VectorizeMatch[];
14989 count: number;
14990}
14991/**
14992 * Results of an operation that performed a mutation on a set of vectors.
14993 * Here, `ids` is a list of vectors that were successfully processed.
14994 *
14995 * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.
14996 * See {@link VectorizeAsyncMutation} for its post-beta equivalent.
14997 */
14998interface VectorizeVectorMutation {
14999 /* List of ids of vectors that were successfully processed. */
15000 ids: string[];
15001 /* Total count of the number of processed vectors. */
15002 count: number;
15003}
15004/**
15005 * Result type indicating a mutation on the Vectorize Index.
15006 * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation.
15007 */
15008interface VectorizeAsyncMutation {
15009 /** The unique identifier for the async mutation operation containing the changeset. */
15010 mutationId: string;
15011}
15012/**
15013 * A Vectorize Vector Search Index for querying vectors/embeddings.
15014 *
15015 * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.
15016 * See {@link Vectorize} for its new implementation.
15017 */
15018declare abstract class VectorizeIndex {
15019 /**
15020 * Get information about the currently bound index.
15021 * @returns A promise that resolves with information about the current index.
15022 */
15023 public describe(): Promise<VectorizeIndexDetails>;
15024 /**
15025 * Use the provided vector to perform a similarity search across the index.
15026 * @param vector Input vector that will be used to drive the similarity search.
15027 * @param options Configuration options to massage the returned data.
15028 * @returns A promise that resolves with matched and scored vectors.
15029 */
15030 public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;
15031 /**
15032 * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.
15033 * @param vectors List of vectors that will be inserted.
15034 * @returns A promise that resolves with the ids & count of records that were successfully processed.
15035 */
15036 public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;
15037 /**
15038 * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.
15039 * @param vectors List of vectors that will be upserted.
15040 * @returns A promise that resolves with the ids & count of records that were successfully processed.
15041 */
15042 public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;
15043 /**
15044 * Delete a list of vectors with a matching id.
15045 * @param ids List of vector ids that should be deleted.
15046 * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted).
15047 */
15048 public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>;
15049 /**
15050 * Get a list of vectors with a matching id.
15051 * @param ids List of vector ids that should be returned.
15052 * @returns A promise that resolves with the raw unscored vectors matching the id set.
15053 */
15054 public getByIds(ids: string[]): Promise<VectorizeVector[]>;
15055}
15056/**
15057 * A Vectorize Vector Search Index for querying vectors/embeddings.
15058 *
15059 * Mutations in this version are async, returning a mutation id.
15060 */
15061declare abstract class Vectorize {
15062 /**
15063 * Get information about the currently bound index.
15064 * @returns A promise that resolves with information about the current index.
15065 */
15066 public describe(): Promise<VectorizeIndexInfo>;
15067 /**
15068 * Use the provided vector to perform a similarity search across the index.
15069 * @param vector Input vector that will be used to drive the similarity search.
15070 * @param options Configuration options to massage the returned data.
15071 * @returns A promise that resolves with matched and scored vectors.
15072 */
15073 public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;
15074 /**
15075 * Use the provided vector-id to perform a similarity search across the index.
15076 * @param vectorId Id for a vector in the index against which the index should be queried.
15077 * @param options Configuration options to massage the returned data.
15078 * @returns A promise that resolves with matched and scored vectors.
15079 */
15080 public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise<VectorizeMatches>;
15081 /**
15082 * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.
15083 * @param vectors List of vectors that will be inserted.
15084 * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset.
15085 */
15086 public insert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;
15087 /**
15088 * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.
15089 * @param vectors List of vectors that will be upserted.
15090 * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset.
15091 */
15092 public upsert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;
15093 /**
15094 * Delete a list of vectors with a matching id.
15095 * @param ids List of vector ids that should be deleted.
15096 * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset.
15097 */
15098 public deleteByIds(ids: string[]): Promise<VectorizeAsyncMutation>;
15099 /**
15100 * Get a list of vectors with a matching id.
15101 * @param ids List of vector ids that should be returned.
15102 * @returns A promise that resolves with the raw unscored vectors matching the id set.
15103 */
15104 public getByIds(ids: string[]): Promise<VectorizeVector[]>;
15105}
15106/**
15107 * The interface for "version_metadata" binding
15108 * providing metadata about the Worker Version using this binding.
15109 */
15110type WorkerVersionMetadata = {
15111 /** The ID of the Worker Version using this binding */
15112 id: string;
15113 /** The tag of the Worker Version using this binding */
15114 tag: string;
15115 /** The timestamp of when the Worker Version was uploaded */
15116 timestamp: string;
15117};
15118// ============ Web Search Request Types ============
15119/**
15120 * Options for a Web Search query.
15121 */
15122type WebSearchSearchOptions = {
15123 /** The search query. */
15124 query: string;
15125 /**
15126 * Maximum number of results to return. Defaults to 10, capped at 20.
15127 * The actual count may be lower if fewer matches exist.
15128 */
15129 limit?: number;
15130};
15131// ============ Web Search Response Types ============
15132/**
15133 * A single Web Search result.
15134 *
15135 * Web Search is discovery-only -- results carry catalog metadata about a page
15136 * but never the page body. To read a result's content the caller invokes the
15137 * global `fetch()` API against the result's `url`, at which point the
15138 * destination's own access controls apply (including Cloudflare Pay-per-Crawl).
15139 */
15140type WebSearchResult = {
15141 /** Canonical URL. */
15142 url: string;
15143 /** Page title. */
15144 title: string;
15145 /** Page-level description. May be absent. */
15146 description?: string;
15147 /**
15148 * Last-modified date for the page, when known. Naive (no timezone)
15149 * ISO-8601 datetime, e.g. `"2025-11-30T04:39:48"`.
15150 */
15151 lastModifiedDate?: string;
15152 /**
15153 * Page meta image URL (typically the `og:image`). May be absent.
15154 */
15155 imageUrl?: string;
15156 /** Optional favicon URL for UI hints. */
15157 faviconUrl?: string;
15158};
15159/**
15160 * Per-response metadata for a Web Search query. Carries operational
15161 * fields useful for support and debugging.
15162 */
15163type WebSearchResponseMetadata = {
15164 /** The query that was executed. */
15165 query: string;
15166 /** Opaque request identifier used for support and debugging. */
15167 requestId: string;
15168 /** End-to-end latency for this search request, in milliseconds. */
15169 latencyMs: number;
15170};
15171/**
15172 * Response from a Web Search query.
15173 */
15174type WebSearchSearchResponse = {
15175 items: WebSearchResult[];
15176 metadata: WebSearchResponseMetadata;
15177};
15178// ============ Web Search Binding Class ============
15179/**
15180 * Cloudflare Web Search binding.
15181 *
15182 * Discovery-only primitive for agents and Workers. Returns URLs and catalog
15183 * metadata for a query; never returns page content or excerpts. To read a
15184 * result's body, fetch the URL with the global `fetch()` API.
15185 *
15186 * Declared in wrangler with a single object (there is exactly one corpus, the
15187 * public web, so there is no name, namespace, or instance to specify):
15188 *
15189 * ```jsonc
15190 * { "web_search": { "binding": "WEBSEARCH" } }
15191 * ```
15192 *
15193 * @example
15194 * ```ts
15195 * const { items, metadata } = await env.WEBSEARCH.search({
15196 * query: "Cloudflare Workers",
15197 * });
15198 *
15199 * const top = items[0];
15200 * console.log(top.url, top.title, metadata.latencyMs);
15201 *
15202 * // Read content yourself; pay-per-crawl and other publisher
15203 * // controls apply at the fetch site, not at search time.
15204 * const page = await fetch(top.url);
15205 * ```
15206 */
15207declare abstract class WebSearch {
15208 /**
15209 * Run a Web Search query.
15210 * @param options Search options. Only `query` is required.
15211 * @returns The matching results plus per-response metadata.
15212 */
15213 search(options: WebSearchSearchOptions): Promise<WebSearchSearchResponse>;
15214}
15215interface DynamicDispatchLimits {
15216 /**
15217 * Limit CPU time in milliseconds.
15218 */
15219 cpuMs?: number;
15220 /**
15221 * Limit number of subrequests.
15222 */
15223 subRequests?: number;
15224}
15225interface DynamicDispatchOptions {
15226 /**
15227 * Limit resources of invoked Worker script.
15228 */
15229 limits?: DynamicDispatchLimits;
15230 /**
15231 * Arguments for outbound Worker script, if configured.
15232 */
15233 outbound?: {
15234 [key: string]: any;
15235 };
15236}
15237interface DispatchNamespace {
15238 /**
15239 * @param name Name of the Worker script.
15240 * @param args Arguments to Worker script.
15241 * @param options Options for Dynamic Dispatch invocation.
15242 * @returns A Fetcher object that allows you to send requests to the Worker script.
15243 * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown.
15244 */
15245 get(name: string, args?: {
15246 [key: string]: any;
15247 }, options?: DynamicDispatchOptions): Fetcher;
15248}
15249declare module 'cloudflare:workflows' {
15250 /**
15251 * NonRetryableError allows for a user to throw a fatal error
15252 * that makes a Workflow instance fail immediately without triggering a retry
15253 */
15254 export class NonRetryableError extends Error {
15255 public constructor(message: string, name?: string);
15256 }
15257}
15258declare abstract class Workflow<PARAMS = unknown> {
15259 /**
15260 * Get a handle to an existing instance of the Workflow.
15261 * @param id Id for the instance of this Workflow
15262 * @returns A promise that resolves with a handle for the Instance
15263 */
15264 public get(id: string): Promise<WorkflowInstance>;
15265 /**
15266 * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown.
15267 * @param options Options when creating an instance including id and params
15268 * @returns A promise that resolves with a handle for the Instance
15269 */
15270 public create(options?: WorkflowInstanceCreateOptions<PARAMS>): Promise<WorkflowInstance>;
15271 /**
15272 * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown.
15273 * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached.
15274 * @param batch List of Options when creating an instance including name and params
15275 * @returns A promise that resolves with a list of handles for the created instances.
15276 */
15277 public createBatch(batch: WorkflowInstanceCreateOptions<PARAMS>[]): Promise<WorkflowInstance[]>;
15278 /**
15279 * Delete a batch of Workflow instances and their stored state.
15280 * `deleteBatch` is limited to 100 instances at a time. Duplicate IDs are deleted once.
15281 * The result contains one entry for each input position; IDs that do not exist are returned as per-instance errors.
15282 * @param instanceIds IDs of the Workflow instances to delete
15283 * @returns A promise that resolves with the successfully deleted instances and any per-instance errors.
15284 */
15285 public deleteBatch(instanceIds: string[]): Promise<WorkflowBatchDeleteResult>;
15286}
15287type WorkflowBatchDeleteResult = {
15288 deleted: {
15289 id: string;
15290 }[];
15291 errors: {
15292 id: string;
15293 code: number;
15294 message: string;
15295 }[];
15296};
15297type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
15298type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;
15299type WorkflowRetentionDuration = WorkflowSleepDuration;
15300/** Geographic regions supported when creating a Workflow instance.
15301 * Location hints are best-effort placement preferences. */
15302type WorkflowInstanceLocationHint = 'wnam' | 'enam' | 'sam' | 'weur' | 'eeur' | 'apac' | 'apac-ne' | 'apac-se' | 'oc' | 'afr' | 'me';
15303interface WorkflowInstanceCreateOptions<PARAMS = unknown> {
15304 /**
15305 * An id for your Workflow instance. Must be unique within the Workflow.
15306 */
15307 id?: string;
15308 /**
15309 * The event payload the Workflow instance is triggered with
15310 */
15311 params?: PARAMS;
15312 /**
15313 * The retention policy for Workflow instance.
15314 * Defaults to the maximum retention period available for the owner's account.
15315 */
15316 retention?: {
15317 successRetention?: WorkflowRetentionDuration;
15318 errorRetention?: WorkflowRetentionDuration;
15319 };
15320 /** A best-effort geographic placement preference for the Workflow instance.
15321 * See `WorkflowInstanceLocationHint` for supported regions. */
15322 locationHint?: WorkflowInstanceLocationHint;
15323}
15324type InstanceStatus = {
15325 status: 'queued' // means that instance is waiting to be started (see concurrency limits)
15326 | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running
15327 | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish
15328 | 'waitingForPause' // instance is finishing the current work to pause
15329 | 'unknown';
15330 error?: {
15331 name: string;
15332 message: string;
15333 };
15334 output?: unknown;
15335};
15336interface WorkflowError {
15337 code?: number;
15338 message: string;
15339}
15340interface WorkflowInstanceTerminateOptions {
15341 /**
15342 * If true, run registered rollback handlers before terminating the instance.
15343 * Only steps that registered rollback handlers are rolled back.
15344 */
15345 rollback?: boolean;
15346}
15347interface WorkflowInstanceRestartOptions {
15348 /**
15349 * Restart from a specific step. If omitted, the instance restarts from the beginning.
15350 * The step must exist in the instance's execution history.
15351 */
15352 from?: {
15353 /**
15354 * The step name as defined in your workflow code.
15355 */
15356 name: string;
15357 /**
15358 * 1-indexed occurrence of this step name. Use when the same step name appears multiple times (e.g. in a loop).
15359 * @default 1
15360 */
15361 count?: number;
15362 /**
15363 * Step type filter. Use when different step types share the same name.
15364 */
15365 type?: 'do' | 'sleep' | 'waitForEvent';
15366 };
15367}
15368declare abstract class WorkflowInstance {
15369 public id: string;
15370 /**
15371 * Pause the instance.
15372 */
15373 public pause(): Promise<void>;
15374 /**
15375 * Resume the instance. If it is already running, an error will be thrown.
15376 */
15377 public resume(): Promise<void>;
15378 /**
15379 * Terminate the instance. If it is errored, terminated or complete, an error will be thrown.
15380 * @param options Options for termination, including whether registered rollback handlers should run.
15381 */
15382 public terminate(options?: WorkflowInstanceTerminateOptions): Promise<void>;
15383 /**
15384 * Restart the instance. Optionally restart from a specific step, preserving
15385 * cached results for all steps before it.
15386 * @param options Options for the restart, including an optional step to restart from.
15387 */
15388 public restart(options?: WorkflowInstanceRestartOptions): Promise<void>;
15389 /**
15390 * Delete the instance and its stored state.
15391 */
15392 public delete(): Promise<void>;
15393 /**
15394 * Returns the current status of the instance.
15395 */
15396 public status(): Promise<InstanceStatus>;
15397 /**
15398 * Send an event to this instance.
15399 */
15400 public sendEvent({ type, payload, }: {
15401 type: string;
15402 payload: unknown;
15403 }): Promise<void>;
15404}