diff options
| author | akiyamn | 2023-09-24 23:22:21 +1000 |
|---|---|---|
| committer | akiyamn | 2023-09-24 23:22:21 +1000 |
| commit | 4e87195739f2a5d9a05451b48773c8afdc680765 (patch) | |
| tree | 9cba501844a4a11dcbdffc4050ed8189561c55ed /node_modules/@cloudflare | |
| download | price-tracker-worker-4e87195739f2a5d9a05451b48773c8afdc680765.tar.gz price-tracker-worker-4e87195739f2a5d9a05451b48773c8afdc680765.zip | |
Initial commit (by create-cloudflare CLI)
Diffstat (limited to 'node_modules/@cloudflare')
53 files changed, 75522 insertions, 0 deletions
diff --git a/node_modules/@cloudflare/kv-asset-handler/LICENSE_APACHE b/node_modules/@cloudflare/kv-asset-handler/LICENSE_APACHE new file mode 100644 index 0000000..a7e77cb --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/LICENSE_APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS
\ No newline at end of file diff --git a/node_modules/@cloudflare/kv-asset-handler/LICENSE_MIT b/node_modules/@cloudflare/kv-asset-handler/LICENSE_MIT new file mode 100644 index 0000000..abf2bc7 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/LICENSE_MIT @@ -0,0 +1,25 @@ +Copyright (c) 2018 Ashley Williams <ashley666ashley@gmail.com> + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE.
\ No newline at end of file diff --git a/node_modules/@cloudflare/kv-asset-handler/README.md b/node_modules/@cloudflare/kv-asset-handler/README.md new file mode 100644 index 0000000..d5baa0a --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/README.md @@ -0,0 +1,329 @@ +# @cloudflare/kv-asset-handler + +[](https://www.npmjs.com/package/@cloudflare/kv-asset-handler) +[](https://github.com/cloudflare/kv-asset-handler/actions/workflows/test.yml) +[](https://github.com/cloudflare/kv-asset-handler/actions/workflows/lint.yml) + +`kv-asset-handler` is an open-source library for managing the retrieval of static assets from [Workers KV](https://developers.cloudflare.com/workers/runtime-apis/kv) inside of a [Cloudflare Workers](https://workers.dev) function. `kv-asset-handler` is designed for use with [Workers Sites](https://developers.cloudflare.com/workers/platform/sites), a feature included in [Wrangler](https://github.com/cloudflare/wrangler), our command-line tool for deploying Workers projects. + +`kv-asset-handler` runs as part of a Cloudflare Workers function, so it allows you to customize _how_ and _when_ your static assets are loaded, as well as customize how those assets behave before they're sent to the client. + +Most users and sites will not need these customizations, and just want to serve their statically built applications. For that simple use-case, you can check out [Cloudflare Pages](https://pages.cloudflare.com), our batteries-included approach to deploying static sites on Cloudflare's edge network. Workers Sites was designed as a precursor to Cloudflare Pages, so check out Pages if you just want to deploy your static site without any special customizations! + +For users who _do_ want to customize their assets, and want to build complex experiences on top of their static assets, `kv-asset-handler` (and the default [Workers Sites template](https://github.com/cloudflare/worker-sites-template), which is provided for use with Wrangler + Workers Sites) allows you to customize caching behavior, headers, and anything else about how your Workers function loads the static assets for your site stored in Workers KV. + +The Cloudflare Workers Discord server is an active place where Workers users get help, share feedback, and collaborate on making our platform better. The `#workers-sites` channel in particular is a great place to chat about `kv-asset-handler`, and building cool experiences for your users using these tools! If you have questions, want to share what you're working on, or give feedback, [join us in Discord and say hello](https://discord.gg/cloudflaredev)! + +- [Installation](#installation) +- [Usage](#usage) +- [`getAssetFromKV`](#-getassetfromkv) + - [Example](#example) + * [Return](#return) + * [Optional Arguments](#optional-arguments) + - [`mapRequestToAsset`](#-maprequesttoasset) + - [Example](#example-1) + - [`cacheControl`](#-cachecontrol) + - [`browserTTL`](#browserttl) + - [`edgeTTL`](#edgettl) + - [`bypassCache`](#bypasscache) + - [`ASSET_NAMESPACE` (required for ES Modules)](#asset_namespace-required-for-es-modules) + - [`ASSET_MANIFEST` (required for ES Modules)](#asset_manifest-required-for-es-modules) + +* [Helper functions](#helper-functions) + - [`mapRequestToAsset`](#maprequesttoasset-1) + - [`serveSinglePageApp`](#servesinglepageapp) +* [Cache revalidation and etags](#cache-revalidation-and-etags) + +## Installation + +Add this package to your `package.json` by running this in the root of your +project's directory: + +``` +npm i @cloudflare/kv-asset-handler +``` + +## Usage + +This package was designed to work with [Worker Sites](https://workers.cloudflare.com/sites). + +## `getAssetFromKV` + +getAssetFromKV(Evt) => Promise<Response> + +`getAssetFromKV` is an async function that takes an `Evt` object (containing a `Request` and a [`waitUntil`](https://developers.cloudflare.com/workers/runtime-apis/fetch-event#waituntil)) and returns a `Response` object if the request matches an asset in KV, otherwise it will throw a `KVError`. + +#### Example + +This example checks for the existence of a value in KV, and returns it if it's there, and returns a 404 if it is not. It also serves index.html from `/`. + +### Return + +`getAssetFromKV` returns a `Promise<Response>` with `Response` being the body of the asset requested. + +Known errors to be thrown are: + +- MethodNotAllowedError +- NotFoundError +- InternalError + +#### ES Modules + +```js +import { getAssetFromKV, NotFoundError, MethodNotAllowedError } from '@cloudflare/kv-asset-handler' +import manifestJSON from '__STATIC_CONTENT_MANIFEST' +const assetManifest = JSON.parse(manifestJSON) + +export default { + async fetch(request, env, ctx) { + if (request.url.includes('/docs')) { + try { + return await getAssetFromKV( + { + request, + waitUntil(promise) { + return ctx.waitUntil(promise) + }, + }, + { + ASSET_NAMESPACE: env.__STATIC_CONTENT, + ASSET_MANIFEST: assetManifest, + }, + ) + } catch (e) { + if (e instanceof NotFoundError) { + // ... + } else if (e instanceof MethodNotAllowedError) { + // ... + } else { + return new Response('An unexpected error occurred', { status: 500 }) + } + } + } else return fetch(request) + }, +} +``` + +#### Service Worker + +```js +import { getAssetFromKV, NotFoundError, MethodNotAllowedError } from '@cloudflare/kv-asset-handler' + +addEventListener('fetch', (event) => { + event.respondWith(handleEvent(event)) +}) + +async function handleEvent(event) { + if (event.request.url.includes('/docs')) { + try { + return await getAssetFromKV(event) + } catch (e) { + if (e instanceof NotFoundError) { + // ... + } else if (e instanceof MethodNotAllowedError) { + // ... + } else { + return new Response('An unexpected error occurred', { status: 500 }) + } + } + } else return fetch(event.request) +} +``` + +### Optional Arguments + +You can customize the behavior of `getAssetFromKV` by passing the following properties as an object into the second argument. + +``` +getAssetFromKV(event, { mapRequestToAsset: ... }) +``` + +#### `mapRequestToAsset` + +mapRequestToAsset(Request) => Request + +Maps the incoming request to the value that will be looked up in Cloudflare's KV + +By default, mapRequestToAsset is set to the exported function [`mapRequestToAsset`](#maprequesttoasset-1). This works for most static site generators, but you can customize this behavior by passing your own function as `mapRequestToAsset`. The function should take a `Request` object as its only argument, and return a new `Request` object with an updated path to be looked up in the asset manifest/KV. + +For SPA mapping pass in the [`serveSinglePageApp`](#servesinglepageapp) function + +#### Example + +Strip `/docs` from any incoming request before looking up an asset in Cloudflare's KV. + +```js +import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler' +... +const customKeyModifier = request => { + let url = request.url + //custom key mapping optional + url = url.replace('/docs', '').replace(/^\/+/, '') + return mapRequestToAsset(new Request(url, request)) +} +let asset = await getAssetFromKV(event, { mapRequestToAsset: customKeyModifier }) +``` + +#### `cacheControl` + +type: object + +`cacheControl` allows you to configure options for both the Cloudflare Cache accessed by your Worker, and the browser cache headers sent along with your Workers' responses. The default values are as follows: + +```javascript +let cacheControl = { + browserTTL: null, // do not set cache control ttl on responses + edgeTTL: 2 * 60 * 60 * 24, // 2 days + bypassCache: false, // do not bypass Cloudflare's cache +} +``` + +##### `browserTTL` + +type: number | null +nullable: true + +Sets the `Cache-Control: max-age` header on the response returned from the Worker. By default set to `null` which will not add the header at all. + +##### `edgeTTL` + +type: number | null +nullable: true + +Sets the `Cache-Control: max-age` header on the response used as the edge cache key. By default set to 2 days (`2 * 60 * 60 * 24`). When null will not cache on the edge at all. + +##### `bypassCache` + +type: boolean + +Determines whether to cache requests on Cloudflare's edge cache. By default set to `false` (recommended for production builds). Useful for development when you need to eliminate the cache's effect on testing. + +#### `ASSET_NAMESPACE` (required for ES Modules) + +type: KV Namespace Binding + +The binding name to the KV Namespace populated with key/value entries of files for the Worker to serve. By default, Workers Sites uses a [binding to a Workers KV Namespace](https://developers.cloudflare.com/workers/reference/storage/api/#namespaces) named `__STATIC_CONTENT`. + +It is further assumed that this namespace consists of static assets such as HTML, CSS, JavaScript, or image files, keyed off of a relative path that roughly matches the assumed URL pathname of the incoming request. + +In ES Modules format, this argument is required, and can be gotten from `env`. + +##### ES Module + +```js +return getAssetFromKV( + { + request, + waitUntil(promise) { + return ctx.waitUntil(promise) + }, + }, + { + ASSET_NAMESPACE: env.__STATIC_CONTENT, + }, +) +``` + +##### Service Worker + +``` +return getAssetFromKV(event, { ASSET_NAMESPACE: MY_NAMESPACE }) +``` + +#### `ASSET_MANIFEST` (required for ES Modules) + +type: text blob (JSON formatted) or object + +The mapping of requested file path to the key stored on Cloudflare. + +Workers Sites with Wrangler bundles up a text blob that maps request paths to content-hashed keys that are generated by Wrangler as a cache-busting measure. If this option/binding is not present, the function will fallback to using the raw pathname to look up your asset in KV. If, for whatever reason, you have rolled your own implementation of this, you can include your own by passing a stringified JSON object where the keys are expected paths, and the values are the expected keys in your KV namespace. + +In ES Modules format, this argument is required, and can be imported. + +##### ES Module + +```js +import manifestJSON from '__STATIC_CONTENT_MANIFEST' +let manifest = JSON.parse(manifestJSON) +manifest['index.html'] = 'index.special.html' + +return getAssetFromKV( + { + request, + waitUntil(promise) { + return ctx.waitUntil(promise) + }, + }, + { + ASSET_MANIFEST: manifest, + // ... + }, +) +``` + +##### Service Worker + +``` +let assetManifest = { "index.html": "index.special.html" } +return getAssetFromKV(event, { ASSET_MANIFEST: assetManifest }) +``` + +#### `defaultMimeType` (optional) + +type: string + +This is the mime type that will be used for files with unrecognized or missing extensions. The default value is `'text/plain'`. + +If you are serving a static site and would like to use extensionless HTML files instead of index.html files, set this to `'text/html'`. + +#### `defaultDocument` (optional) + +type: string + +This is the default document that will be concatenated for requests ends in `'/'` or without a valid mime type like `'/about'` or `'/about.me'`. The default value is `'index.html'`. + +# Helper functions + +## `mapRequestToAsset` + +mapRequestToAsset(Request) => Request + +The default function for mapping incoming requests to keys in Cloudflare's KV. + +Takes any path that ends in `/` or evaluates to an HTML file and appends `index.html` or `/index.html` for lookup in your Workers KV namespace. + +## `serveSinglePageApp` + +serveSinglePageApp(Request) => Request + +A custom handler for mapping requests to a single root: `index.html`. The most common use case is single-page applications - frameworks with in-app routing - such as React Router, VueJS, etc. It takes zero arguments. + +```js +import { getAssetFromKV, serveSinglePageApp } from '@cloudflare/kv-asset-handler' +... +let asset = await getAssetFromKV(event, { mapRequestToAsset: serveSinglePageApp }) +``` + +# Cache revalidation and etags + +All responses served from cache (including those with `cf-cache-status: MISS`) include an `etag` response header that identifies the version of the resource. The `etag` value is identical to the path key used in the `ASSET_MANIFEST`. It is updated each time an asset changes and looks like this: `etag: <filename>.<hash of file contents>.<extension>` (ex. `etag: index.54321.html`). + +Resources served with an `etag` allow browsers to use the `if-none-match` request header to make conditional requests for that resource in the future. This has two major benefits: + +- When a request's `if-none-match` value matches the `etag` of the resource in Cloudflare cache, Cloudflare will send a `304 Not Modified` response without a body, saving bandwidth. +- Changes to a file on the server are immediately reflected in the browser - even when the cache control directive `max-age` is unexpired. + +#### Disable the `etag` + +To turn `etags` **off**, you must bypass cache: + +```js +/* Turn etags off */ +let cacheControl = { + bypassCache: true, +} +``` + +#### Syntax and comparison context + +`kv-asset-handler` sets and evaluates etags as [strong validators](https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests#Strong_validation). To preserve `etag` integrity, the format of the value deviates from the [RFC2616 recommendation to enclose the `etag` with quotation marks](https://tools.ietf.org/html/rfc2616#section-3.11). This is intentional. Cloudflare cache applies the `W/` prefix to all `etags` that use quoted-strings -- a process that converts the `etag` to a "weak validator" when served to a client. diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/index.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/index.d.ts new file mode 100644 index 0000000..7820e62 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/index.d.ts @@ -0,0 +1,36 @@ +import { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError } from './types'; +declare global { + var __STATIC_CONTENT: any, __STATIC_CONTENT_MANIFEST: string; +} +/** + * maps the path of incoming request to the request pathKey to look up + * in bucket and in cache + * e.g. for a path '/' returns '/index.html' which serves + * the content of bucket/index.html + * @param {Request} request incoming request + */ +declare const mapRequestToAsset: (request: Request, options?: Partial<Options>) => Request; +/** + * maps the path of incoming request to /index.html if it evaluates to + * any HTML file. + * @param {Request} request incoming request + */ +declare function serveSinglePageApp(request: Request, options?: Partial<Options>): Request; +/** + * takes the path of the incoming request, gathers the appropriate content from KV, and returns + * the response + * + * @param {FetchEvent} event the fetch event of the triggered request + * @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options + * @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser + * @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up + * @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references + * @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV + * */ +declare type Evt = { + request: Request; + waitUntil: (promise: Promise<any>) => void; +}; +declare const getAssetFromKV: (event: Evt, options?: Partial<Options>) => Promise<Response>; +export { getAssetFromKV, mapRequestToAsset, serveSinglePageApp }; +export { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError }; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/index.js b/node_modules/@cloudflare/kv-asset-handler/dist/index.js new file mode 100644 index 0000000..5f80b5e --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/index.js @@ -0,0 +1,267 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InternalError = exports.NotFoundError = exports.MethodNotAllowedError = exports.serveSinglePageApp = exports.mapRequestToAsset = exports.getAssetFromKV = void 0; +const mime = require("mime"); +const types_1 = require("./types"); +Object.defineProperty(exports, "MethodNotAllowedError", { enumerable: true, get: function () { return types_1.MethodNotAllowedError; } }); +Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return types_1.NotFoundError; } }); +Object.defineProperty(exports, "InternalError", { enumerable: true, get: function () { return types_1.InternalError; } }); +const defaultCacheControl = { + browserTTL: null, + edgeTTL: 2 * 60 * 60 * 24, + bypassCache: false, // do not bypass Cloudflare's cache +}; +const parseStringAsObject = (maybeString) => typeof maybeString === 'string' ? JSON.parse(maybeString) : maybeString; +const getAssetFromKVDefaultOptions = { + ASSET_NAMESPACE: typeof __STATIC_CONTENT !== 'undefined' ? __STATIC_CONTENT : undefined, + ASSET_MANIFEST: typeof __STATIC_CONTENT_MANIFEST !== 'undefined' + ? parseStringAsObject(__STATIC_CONTENT_MANIFEST) + : {}, + cacheControl: defaultCacheControl, + defaultMimeType: 'text/plain', + defaultDocument: 'index.html', + pathIsEncoded: false, +}; +function assignOptions(options) { + // Assign any missing options passed in to the default + // options.mapRequestToAsset is handled manually later + return Object.assign({}, getAssetFromKVDefaultOptions, options); +} +/** + * maps the path of incoming request to the request pathKey to look up + * in bucket and in cache + * e.g. for a path '/' returns '/index.html' which serves + * the content of bucket/index.html + * @param {Request} request incoming request + */ +const mapRequestToAsset = (request, options) => { + options = assignOptions(options); + const parsedUrl = new URL(request.url); + let pathname = parsedUrl.pathname; + if (pathname.endsWith('/')) { + // If path looks like a directory append options.defaultDocument + // e.g. If path is /about/ -> /about/index.html + pathname = pathname.concat(options.defaultDocument); + } + else if (!mime.getType(pathname)) { + // If path doesn't look like valid content + // e.g. /about.me -> /about.me/index.html + pathname = pathname.concat('/' + options.defaultDocument); + } + parsedUrl.pathname = pathname; + return new Request(parsedUrl.toString(), request); +}; +exports.mapRequestToAsset = mapRequestToAsset; +/** + * maps the path of incoming request to /index.html if it evaluates to + * any HTML file. + * @param {Request} request incoming request + */ +function serveSinglePageApp(request, options) { + options = assignOptions(options); + // First apply the default handler, which already has logic to detect + // paths that should map to HTML files. + request = mapRequestToAsset(request, options); + const parsedUrl = new URL(request.url); + // Detect if the default handler decided to map to + // a HTML file in some specific directory. + if (parsedUrl.pathname.endsWith('.html')) { + // If expected HTML file was missing, just return the root index.html (or options.defaultDocument) + return new Request(`${parsedUrl.origin}/${options.defaultDocument}`, request); + } + else { + // The default handler decided this is not an HTML page. It's probably + // an image, CSS, or JS file. Leave it as-is. + return request; + } +} +exports.serveSinglePageApp = serveSinglePageApp; +const getAssetFromKV = async (event, options) => { + options = assignOptions(options); + const request = event.request; + const ASSET_NAMESPACE = options.ASSET_NAMESPACE; + const ASSET_MANIFEST = parseStringAsObject(options.ASSET_MANIFEST); + if (typeof ASSET_NAMESPACE === 'undefined') { + throw new types_1.InternalError(`there is no KV namespace bound to the script`); + } + const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, ''); // strip any preceding /'s + let pathIsEncoded = options.pathIsEncoded; + let requestKey; + // if options.mapRequestToAsset is explicitly passed in, always use it and assume user has own intentions + // otherwise handle request as normal, with default mapRequestToAsset below + if (options.mapRequestToAsset) { + requestKey = options.mapRequestToAsset(request); + } + else if (ASSET_MANIFEST[rawPathKey]) { + requestKey = request; + } + else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) { + pathIsEncoded = true; + requestKey = request; + } + else { + const mappedRequest = mapRequestToAsset(request); + const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace(/^\/+/, ''); + if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) { + pathIsEncoded = true; + requestKey = mappedRequest; + } + else { + // use default mapRequestToAsset + requestKey = mapRequestToAsset(request, options); + } + } + const SUPPORTED_METHODS = ['GET', 'HEAD']; + if (!SUPPORTED_METHODS.includes(requestKey.method)) { + throw new types_1.MethodNotAllowedError(`${requestKey.method} is not a valid request method`); + } + const parsedUrl = new URL(requestKey.url); + const pathname = pathIsEncoded ? decodeURIComponent(parsedUrl.pathname) : parsedUrl.pathname; // decode percentage encoded path only when necessary + // pathKey is the file path to look up in the manifest + let pathKey = pathname.replace(/^\/+/, ''); // remove prepended / + // @ts-ignore + const cache = caches.default; + let mimeType = mime.getType(pathKey) || options.defaultMimeType; + if (mimeType.startsWith('text') || mimeType === 'application/javascript') { + mimeType += '; charset=utf-8'; + } + let shouldEdgeCache = false; // false if storing in KV by raw file path i.e. no hash + // check manifest for map from file path to hash + if (typeof ASSET_MANIFEST !== 'undefined') { + if (ASSET_MANIFEST[pathKey]) { + pathKey = ASSET_MANIFEST[pathKey]; + // if path key is in asset manifest, we can assume it contains a content hash and can be cached + shouldEdgeCache = true; + } + } + // TODO this excludes search params from cache, investigate ideal behavior + let cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request); + // if argument passed in for cacheControl is a function then + // evaluate that function. otherwise return the Object passed in + // or default Object + const evalCacheOpts = (() => { + switch (typeof options.cacheControl) { + case 'function': + return options.cacheControl(request); + case 'object': + return options.cacheControl; + default: + return defaultCacheControl; + } + })(); + // formats the etag depending on the response context. if the entityId + // is invalid, returns an empty string (instead of null) to prevent the + // the potentially disastrous scenario where the value of the Etag resp + // header is "null". Could be modified in future to base64 encode etc + const formatETag = (entityId = pathKey, validatorType = 'strong') => { + if (!entityId) { + return ''; + } + switch (validatorType) { + case 'weak': + if (!entityId.startsWith('W/')) { + return `W/${entityId}`; + } + return entityId; + case 'strong': + if (entityId.startsWith(`W/"`)) { + entityId = entityId.replace('W/', ''); + } + if (!entityId.endsWith(`"`)) { + entityId = `"${entityId}"`; + } + return entityId; + default: + return ''; + } + }; + options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts); + // override shouldEdgeCache if options say to bypassCache + if (options.cacheControl.bypassCache || + options.cacheControl.edgeTTL === null || + request.method == 'HEAD') { + shouldEdgeCache = false; + } + // only set max-age if explicitly passed in a number as an arg + const shouldSetBrowserCache = typeof options.cacheControl.browserTTL === 'number'; + let response = null; + if (shouldEdgeCache) { + response = await cache.match(cacheKey); + } + if (response) { + if (response.status > 300 && response.status < 400) { + if (response.body && 'cancel' in Object.getPrototypeOf(response.body)) { + // Body exists and environment supports readable streams + response.body.cancel(); + } + else { + // Environment doesnt support readable streams, or null repsonse body. Nothing to do + } + response = new Response(null, response); + } + else { + // fixes #165 + let opts = { + headers: new Headers(response.headers), + status: 0, + statusText: '', + }; + opts.headers.set('cf-cache-status', 'HIT'); + if (response.status) { + opts.status = response.status; + opts.statusText = response.statusText; + } + else if (opts.headers.has('Content-Range')) { + opts.status = 206; + opts.statusText = 'Partial Content'; + } + else { + opts.status = 200; + opts.statusText = 'OK'; + } + response = new Response(response.body, opts); + } + } + else { + const body = await ASSET_NAMESPACE.get(pathKey, 'arrayBuffer'); + if (body === null) { + throw new types_1.NotFoundError(`could not find ${pathKey} in your content namespace`); + } + response = new Response(body); + if (shouldEdgeCache) { + response.headers.set('Accept-Ranges', 'bytes'); + response.headers.set('Content-Length', body.length); + // set etag before cache insertion + if (!response.headers.has('etag')) { + response.headers.set('etag', formatETag(pathKey, 'strong')); + } + // determine Cloudflare cache behavior + response.headers.set('Cache-Control', `max-age=${options.cacheControl.edgeTTL}`); + event.waitUntil(cache.put(cacheKey, response.clone())); + response.headers.set('CF-Cache-Status', 'MISS'); + } + } + response.headers.set('Content-Type', mimeType); + if (response.status === 304) { + let etag = formatETag(response.headers.get('etag'), 'strong'); + let ifNoneMatch = cacheKey.headers.get('if-none-match'); + let proxyCacheStatus = response.headers.get('CF-Cache-Status'); + if (etag) { + if (ifNoneMatch && ifNoneMatch === etag && proxyCacheStatus === 'MISS') { + response.headers.set('CF-Cache-Status', 'EXPIRED'); + } + else { + response.headers.set('CF-Cache-Status', 'REVALIDATED'); + } + response.headers.set('etag', formatETag(etag, 'weak')); + } + } + if (shouldSetBrowserCache) { + response.headers.set('Cache-Control', `max-age=${options.cacheControl.browserTTL}`); + } + else { + response.headers.delete('Cache-Control'); + } + return response; +}; +exports.getAssetFromKV = getAssetFromKV; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/mocks.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/mocks.d.ts new file mode 100644 index 0000000..f829335 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/mocks.d.ts @@ -0,0 +1,14 @@ +export declare const getEvent: (request: Request) => any; +export declare const mockKV: (store: any) => { + get: (path: string) => any; +}; +export declare const mockManifest: () => string; +export declare const mockCaches: () => { + default: { + match(key: any): Promise<any>; + put(key: any, val: Response): Promise<void>; + }; +}; +export declare function mockRequestScope(): void; +export declare function mockGlobalScope(): void; +export declare const sleep: (milliseconds: number) => Promise<unknown>; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/mocks.js b/node_modules/@cloudflare/kv-asset-handler/dist/mocks.js new file mode 100644 index 0000000..0f7a338 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/mocks.js @@ -0,0 +1,146 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sleep = exports.mockGlobalScope = exports.mockRequestScope = exports.mockCaches = exports.mockManifest = exports.mockKV = exports.getEvent = void 0; +const makeServiceWorkerEnv = require('service-worker-mock'); +const HASH = '123HASHBROWN'; +const getEvent = (request) => { + const waitUntil = async (callback) => { + await callback; + }; + return { + request, + waitUntil, + }; +}; +exports.getEvent = getEvent; +const store = { + 'key1.123HASHBROWN.txt': 'val1', + 'key1.123HASHBROWN.png': 'val1', + 'index.123HASHBROWN.html': 'index.html', + 'cache.123HASHBROWN.html': 'cache me if you can', + '测试.123HASHBROWN.html': 'My filename is non-ascii', + '%not-really-percent-encoded.123HASHBROWN.html': 'browser percent encoded', + '%2F.123HASHBROWN.html': 'user percent encoded', + '你好.123HASHBROWN.html': 'I shouldnt be served', + '%E4%BD%A0%E5%A5%BD.123HASHBROWN.html': 'Im important', + 'nohash.txt': 'no hash but still got some result', + 'sub/blah.123HASHBROWN.png': 'picturedis', + 'sub/index.123HASHBROWN.html': 'picturedis', + 'client.123HASHBROWN': 'important file', + 'client.123HASHBROWN/index.html': 'Im here but serve my big bro above', + 'image.123HASHBROWN.png': 'imagepng', + 'image.123HASHBROWN.webp': 'imagewebp', + '你好/index.123HASHBROWN.html': 'My path is non-ascii', +}; +const mockKV = (store) => { + return { + get: (path) => store[path] || null, + }; +}; +exports.mockKV = mockKV; +const mockManifest = () => { + return JSON.stringify({ + 'key1.txt': `key1.${HASH}.txt`, + 'key1.png': `key1.${HASH}.png`, + 'cache.html': `cache.${HASH}.html`, + '测试.html': `测试.${HASH}.html`, + '你好.html': `你好.${HASH}.html`, + '%not-really-percent-encoded.html': `%not-really-percent-encoded.${HASH}.html`, + '%2F.html': `%2F.${HASH}.html`, + '%E4%BD%A0%E5%A5%BD.html': `%E4%BD%A0%E5%A5%BD.${HASH}.html`, + 'index.html': `index.${HASH}.html`, + 'sub/blah.png': `sub/blah.${HASH}.png`, + 'sub/index.html': `sub/index.${HASH}.html`, + client: `client.${HASH}`, + 'client/index.html': `client.${HASH}`, + 'image.png': `image.${HASH}.png`, + 'image.webp': `image.${HASH}.webp`, + '你好/index.html': `你好/index.${HASH}.html`, + }); +}; +exports.mockManifest = mockManifest; +let cacheStore = new Map(); +const mockCaches = () => { + return { + default: { + async match(key) { + let cacheKey = { + url: key.url, + headers: {}, + }; + let response; + if (key.headers.has('if-none-match')) { + let makeStrongEtag = key.headers.get('if-none-match').replace('W/', ''); + Reflect.set(cacheKey.headers, 'etag', makeStrongEtag); + response = cacheStore.get(JSON.stringify(cacheKey)); + } + else { + // if client doesn't send if-none-match, we need to iterate through these keys + // and just test the URL + const activeCacheKeys = Array.from(cacheStore.keys()); + for (const cacheStoreKey of activeCacheKeys) { + if (JSON.parse(cacheStoreKey).url === key.url) { + response = cacheStore.get(cacheStoreKey); + } + } + } + // TODO: write test to accomodate for rare scenarios with where range requests accomodate etags + if (response && !key.headers.has('if-none-match')) { + // this appears overly verbose, but is necessary to document edge cache behavior + // The Range request header triggers the response header Content-Range ... + const range = key.headers.get('range'); + if (range) { + response.headers.set('content-range', `bytes ${range.split('=').pop()}/${response.headers.get('content-length')}`); + } + // ... which we are using in this repository to set status 206 + if (response.headers.has('content-range')) { + response.status = 206; + } + else { + response.status = 200; + } + let etag = response.headers.get('etag'); + if (etag && !etag.includes('W/')) { + response.headers.set('etag', `W/${etag}`); + } + } + return response; + }, + async put(key, val) { + let headers = new Headers(val.headers); + let url = new URL(key.url); + let resWithBody = new Response(val.body, { headers, status: 200 }); + let resNoBody = new Response(null, { headers, status: 304 }); + let cacheKey = { + url: key.url, + headers: { + etag: `"${url.pathname.replace('/', '')}"`, + }, + }; + cacheStore.set(JSON.stringify(cacheKey), resNoBody); + cacheKey.headers = {}; + cacheStore.set(JSON.stringify(cacheKey), resWithBody); + return; + }, + }, + }; +}; +exports.mockCaches = mockCaches; +// mocks functionality used inside worker request +function mockRequestScope() { + Object.assign(global, makeServiceWorkerEnv()); + Object.assign(global, { __STATIC_CONTENT_MANIFEST: (0, exports.mockManifest)() }); + Object.assign(global, { __STATIC_CONTENT: (0, exports.mockKV)(store) }); + Object.assign(global, { caches: (0, exports.mockCaches)() }); +} +exports.mockRequestScope = mockRequestScope; +// mocks functionality used on global isolate scope. such as the KV namespace bind +function mockGlobalScope() { + Object.assign(global, { __STATIC_CONTENT_MANIFEST: (0, exports.mockManifest)() }); + Object.assign(global, { __STATIC_CONTENT: (0, exports.mockKV)(store) }); +} +exports.mockGlobalScope = mockGlobalScope; +const sleep = (milliseconds) => { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); +}; +exports.sleep = sleep; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.js b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.js new file mode 100644 index 0000000..83838ad --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ava_1 = require("ava"); +const mocks_1 = require("../mocks"); +(0, mocks_1.mockGlobalScope)(); +// manually reset manifest global, to test optional behaviour +Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined }); +const index_1 = require("../index"); +(0, ava_1.default)('getAssetFromKV return correct val from KV without manifest', async (t) => { + (0, mocks_1.mockRequestScope)(); + // manually reset manifest global, to test optional behaviour + Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined }); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/key1.123HASHBROWN.txt')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'val1'); + t.true(res.headers.get('content-type').includes('text')); + } + else { + t.fail('Response was undefined'); + } +}); diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js new file mode 100644 index 0000000..724c1d1 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js @@ -0,0 +1,446 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ava_1 = require("ava"); +const mocks_1 = require("../mocks"); +(0, mocks_1.mockGlobalScope)(); +const index_1 = require("../index"); +(0, ava_1.default)('getAssetFromKV return correct val from KV and default caching', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/key1.txt')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(res.headers.get('cache-control'), null); + t.is(res.headers.get('cf-cache-status'), 'MISS'); + t.is(await res.text(), 'val1'); + t.true(res.headers.get('content-type').includes('text')); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV evaluated the file matching the extensionless path first /client/ -> client', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/client/`)); + const res = await (0, index_1.getAssetFromKV)(event); + t.is(await res.text(), 'important file'); + t.true(res.headers.get('content-type').includes('text')); +}); +(0, ava_1.default)('getAssetFromKV evaluated the file matching the extensionless path first /client -> client', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/client`)); + const res = await (0, index_1.getAssetFromKV)(event); + t.is(await res.text(), 'important file'); + t.true(res.headers.get('content-type').includes('text')); +}); +(0, ava_1.default)('getAssetFromKV if not in asset manifest still returns nohash.txt', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/nohash.txt')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'no hash but still got some result'); + t.true(res.headers.get('content-type').includes('text')); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV if no asset manifest /client -> client fails', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/client`)); + const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event, { ASSET_MANIFEST: {} })); + t.is(error.status, 404); +}); +(0, ava_1.default)('getAssetFromKV if sub/ -> sub/index.html served', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/sub`)); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'picturedis'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV gets index.html by default for / requests', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'index.html'); + t.true(res.headers.get('content-type').includes('html')); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV non ASCII path support', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/测试.html')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'My filename is non-ascii'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV supports browser percent encoded URLs', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://example.com/%not-really-percent-encoded.html')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'browser percent encoded'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV supports user percent encoded URLs', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/%2F.html')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'user percent encoded'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV only decode URL when necessary', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event1 = (0, mocks_1.getEvent)(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD.html')); + const event2 = (0, mocks_1.getEvent)(new Request('https://blah.com/你好.html')); + const res1 = await (0, index_1.getAssetFromKV)(event1); + const res2 = await (0, index_1.getAssetFromKV)(event2); + if (res1 && res2) { + t.is(await res1.text(), 'Im important'); + t.is(await res2.text(), 'Im important'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV Support for user decode url path', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event1 = (0, mocks_1.getEvent)(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD/')); + const event2 = (0, mocks_1.getEvent)(new Request('https://blah.com/你好/')); + const res1 = await (0, index_1.getAssetFromKV)(event1); + const res2 = await (0, index_1.getAssetFromKV)(event2); + if (res1 && res2) { + t.is(await res1.text(), 'My path is non-ascii'); + t.is(await res2.text(), 'My path is non-ascii'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV custom key modifier', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/docs/sub/blah.png')); + const customRequestMapper = (request) => { + let defaultModifiedRequest = (0, index_1.mapRequestToAsset)(request); + let url = new URL(defaultModifiedRequest.url); + url.pathname = url.pathname.replace('/docs', ''); + return new Request(url.toString(), request); + }; + const res = await (0, index_1.getAssetFromKV)(event, { mapRequestToAsset: customRequestMapper }); + if (res) { + t.is(await res.text(), 'picturedis'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV request override with existing manifest file', async (t) => { + // see https://github.com/cloudflare/kv-asset-handler/pull/159 for more info + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/image.png')); // real file in manifest + const customRequestMapper = (request) => { + let defaultModifiedRequest = (0, index_1.mapRequestToAsset)(request); + let url = new URL(defaultModifiedRequest.url); + url.pathname = '/image.webp'; // other different file in manifest + return new Request(url.toString(), request); + }; + const res = await (0, index_1.getAssetFromKV)(event, { mapRequestToAsset: customRequestMapper }); + if (res) { + t.is(await res.text(), 'imagewebp'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV when setting browser caching', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const res = await (0, index_1.getAssetFromKV)(event, { cacheControl: { browserTTL: 22 } }); + if (res) { + t.is(res.headers.get('cache-control'), 'max-age=22'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV when setting custom cache setting', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event1 = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const event2 = (0, mocks_1.getEvent)(new Request('https://blah.com/key1.png?blah=34')); + const cacheOnlyPngs = (req) => { + if (new URL(req.url).pathname.endsWith('.png')) + return { + browserTTL: 720, + edgeTTL: 720, + }; + else + return { + bypassCache: true, + }; + }; + const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: cacheOnlyPngs }); + const res2 = await (0, index_1.getAssetFromKV)(event2, { cacheControl: cacheOnlyPngs }); + if (res1 && res2) { + t.is(res1.headers.get('cache-control'), null); + t.true(res2.headers.get('content-type').includes('png')); + t.is(res2.headers.get('cache-control'), 'max-age=720'); + t.is(res2.headers.get('cf-cache-status'), 'MISS'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV caches on two sequential requests', async (t) => { + (0, mocks_1.mockRequestScope)(); + const resourceKey = 'cache.html'; + const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey]; + const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`)); + const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + })); + const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720, browserTTL: 720 } }); + await (0, mocks_1.sleep)(1); + const res2 = await (0, index_1.getAssetFromKV)(event2); + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS'); + t.is(res1.headers.get('cache-control'), 'max-age=720'); + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV does not store max-age on two sequential requests', async (t) => { + (0, mocks_1.mockRequestScope)(); + const resourceKey = 'cache.html'; + const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey]; + const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`)); + const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + })); + const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720 } }); + await (0, mocks_1.sleep)(100); + const res2 = await (0, index_1.getAssetFromKV)(event2); + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS'); + t.is(res1.headers.get('cache-control'), null); + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED'); + t.is(res2.headers.get('cache-control'), null); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV does not cache on Cloudflare when bypass cache set', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const res = await (0, index_1.getAssetFromKV)(event, { cacheControl: { bypassCache: true } }); + if (res) { + t.is(res.headers.get('cache-control'), null); + t.is(res.headers.get('cf-cache-status'), null); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV with no trailing slash on root', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'index.html'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV with no trailing slash on a subdirectory', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/sub/blah.png')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'picturedis'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV no result throws an error', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/random')); + const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event)); + t.is(error.status, 404); +}); +(0, ava_1.default)('getAssetFromKV TTls set to null should not cache on browser or edge', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { browserTTL: null, edgeTTL: null } }); + await (0, mocks_1.sleep)(100); + const res2 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { browserTTL: null, edgeTTL: null } }); + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), null); + t.is(res1.headers.get('cache-control'), null); + t.is(res2.headers.get('cf-cache-status'), null); + t.is(res2.headers.get('cache-control'), null); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV passing in a custom NAMESPACE serves correct asset', async (t) => { + (0, mocks_1.mockRequestScope)(); + let CUSTOM_NAMESPACE = (0, mocks_1.mockKV)({ + 'key1.123HASHBROWN.txt': 'val1', + }); + Object.assign(global, { CUSTOM_NAMESPACE }); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'index.html'); + t.true(res.headers.get('content-type').includes('html')); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV when custom namespace without the asset should fail', async (t) => { + (0, mocks_1.mockRequestScope)(); + let CUSTOM_NAMESPACE = (0, mocks_1.mockKV)({ + 'key5.123HASHBROWN.txt': 'customvalu', + }); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com')); + const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event, { ASSET_NAMESPACE: CUSTOM_NAMESPACE })); + t.is(error.status, 404); +}); +(0, ava_1.default)('getAssetFromKV when namespace not bound fails', async (t) => { + (0, mocks_1.mockRequestScope)(); + var MY_CUSTOM_NAMESPACE = undefined; + Object.assign(global, { MY_CUSTOM_NAMESPACE }); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event, { ASSET_NAMESPACE: MY_CUSTOM_NAMESPACE })); + t.is(error.status, 500); +}); +(0, ava_1.default)('getAssetFromKV when if-none-match === active resource version, should revalidate', async (t) => { + (0, mocks_1.mockRequestScope)(); + const resourceKey = 'key1.png'; + const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey]; + const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`)); + const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `W/"${resourceVersion}"`, + }, + })); + const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720 } }); + await (0, mocks_1.sleep)(100); + const res2 = await (0, index_1.getAssetFromKV)(event2); + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS'); + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV when if-none-match equals etag of stale resource then should bypass cache', async (t) => { + (0, mocks_1.mockRequestScope)(); + const resourceKey = 'key1.png'; + const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey]; + const req1 = new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + }); + const req2 = new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}-another-version"`, + }, + }); + const event = (0, mocks_1.getEvent)(req1); + const event2 = (0, mocks_1.getEvent)(req2); + const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { edgeTTL: 720 } }); + const res2 = await (0, index_1.getAssetFromKV)(event); + const res3 = await (0, index_1.getAssetFromKV)(event2); + if (res1 && res2 && res3) { + t.is(res1.headers.get('cf-cache-status'), 'MISS'); + t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`); + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED'); + t.not(res3.headers.get('etag'), req2.headers.get('if-none-match')); + t.is(res3.headers.get('cf-cache-status'), 'MISS'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV when resource in cache, etag should be weakened before returned to eyeball', async (t) => { + (0, mocks_1.mockRequestScope)(); + const resourceKey = 'key1.png'; + const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey]; + const req1 = new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + }); + const event = (0, mocks_1.getEvent)(req1); + const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { edgeTTL: 720 } }); + const res2 = await (0, index_1.getAssetFromKV)(event); + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS'); + t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV if-none-match not sent but resource in cache, should return cache hit 200 OK', async (t) => { + const resourceKey = 'cache.html'; + const event = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`)); + const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { edgeTTL: 720 } }); + await (0, mocks_1.sleep)(1); + const res2 = await (0, index_1.getAssetFromKV)(event); + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS'); + t.is(res1.headers.get('cache-control'), null); + t.is(res2.status, 200); + t.is(res2.headers.get('cf-cache-status'), 'HIT'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV if range request submitted and resource in cache, request fulfilled', async (t) => { + const resourceKey = 'cache.html'; + const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`)); + const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, { headers: { range: 'bytes=0-10' } })); + const res1 = (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720 } }); + await res1; + await (0, mocks_1.sleep)(2); + const res2 = await (0, index_1.getAssetFromKV)(event2); + if (res2.headers.has('content-range')) { + t.is(res2.status, 206); + } + else { + t.fail('Response was undefined'); + } +}); +ava_1.default.todo('getAssetFromKV when body not empty, should invoke .cancel()'); diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js b/node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js new file mode 100644 index 0000000..11be912 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ava_1 = require("ava"); +const mocks_1 = require("../mocks"); +(0, mocks_1.mockGlobalScope)(); +const index_1 = require("../index"); +(0, ava_1.default)('mapRequestToAsset() correctly changes /about -> /about/index.html', async (t) => { + (0, mocks_1.mockRequestScope)(); + let path = '/about'; + let request = new Request(`https://foo.com${path}`); + let newRequest = (0, index_1.mapRequestToAsset)(request); + t.is(newRequest.url, request.url + '/index.html'); +}); +(0, ava_1.default)('mapRequestToAsset() correctly changes /about/ -> /about/index.html', async (t) => { + (0, mocks_1.mockRequestScope)(); + let path = '/about/'; + let request = new Request(`https://foo.com${path}`); + let newRequest = (0, index_1.mapRequestToAsset)(request); + t.is(newRequest.url, request.url + 'index.html'); +}); +(0, ava_1.default)('mapRequestToAsset() correctly changes /about.me/ -> /about.me/index.html', async (t) => { + (0, mocks_1.mockRequestScope)(); + let path = '/about.me/'; + let request = new Request(`https://foo.com${path}`); + let newRequest = (0, index_1.mapRequestToAsset)(request); + t.is(newRequest.url, request.url + 'index.html'); +}); +(0, ava_1.default)('mapRequestToAsset() correctly changes /about -> /about/default.html', async (t) => { + (0, mocks_1.mockRequestScope)(); + let path = '/about'; + let request = new Request(`https://foo.com${path}`); + let newRequest = (0, index_1.mapRequestToAsset)(request, { defaultDocument: 'default.html' }); + t.is(newRequest.url, request.url + '/default.html'); +}); diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js b/node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js new file mode 100644 index 0000000..8ee0bfb --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ava_1 = require("ava"); +const mocks_1 = require("../mocks"); +(0, mocks_1.mockGlobalScope)(); +const index_1 = require("../index"); +function testRequest(path) { + (0, mocks_1.mockRequestScope)(); + let url = new URL('https://example.com'); + url.pathname = path; + let request = new Request(url.toString()); + return request; +} +(0, ava_1.default)('serveSinglePageApp returns root asset path when request path ends in .html', async (t) => { + let path = '/foo/thing.html'; + let request = testRequest(path); + let expected_request = testRequest('/index.html'); + let actual_request = (0, index_1.serveSinglePageApp)(request); + t.deepEqual(expected_request, actual_request); +}); +(0, ava_1.default)('serveSinglePageApp returns root asset path when request path does not have extension', async (t) => { + let path = '/foo/thing'; + let request = testRequest(path); + let expected_request = testRequest('/index.html'); + let actual_request = (0, index_1.serveSinglePageApp)(request); + t.deepEqual(expected_request, actual_request); +}); +(0, ava_1.default)('serveSinglePageApp returns requested asset when request path has non-html extension', async (t) => { + let path = '/foo/thing.js'; + let request = testRequest(path); + let expected_request = request; + let actual_request = (0, index_1.serveSinglePageApp)(request); + t.deepEqual(expected_request, actual_request); +}); diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/types.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/types.d.ts new file mode 100644 index 0000000..eef1bff --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/types.d.ts @@ -0,0 +1,28 @@ +export declare type CacheControl = { + browserTTL: number; + edgeTTL: number; + bypassCache: boolean; +}; +export declare type AssetManifestType = Record<string, string>; +export declare type Options = { + cacheControl: ((req: Request) => Partial<CacheControl>) | Partial<CacheControl>; + ASSET_NAMESPACE: any; + ASSET_MANIFEST: AssetManifestType | string; + mapRequestToAsset?: (req: Request, options?: Partial<Options>) => Request; + defaultMimeType: string; + defaultDocument: string; + pathIsEncoded: boolean; +}; +export declare class KVError extends Error { + constructor(message?: string, status?: number); + status: number; +} +export declare class MethodNotAllowedError extends KVError { + constructor(message?: string, status?: number); +} +export declare class NotFoundError extends KVError { + constructor(message?: string, status?: number); +} +export declare class InternalError extends KVError { + constructor(message?: string, status?: number); +} diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/types.js b/node_modules/@cloudflare/kv-asset-handler/dist/types.js new file mode 100644 index 0000000..ba08c1b --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/types.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InternalError = exports.NotFoundError = exports.MethodNotAllowedError = exports.KVError = void 0; +class KVError extends Error { + constructor(message, status = 500) { + super(message); + // see: typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html + Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain + this.name = KVError.name; // stack traces display correctly now + this.status = status; + } +} +exports.KVError = KVError; +class MethodNotAllowedError extends KVError { + constructor(message = `Not a valid request method`, status = 405) { + super(message, status); + } +} +exports.MethodNotAllowedError = MethodNotAllowedError; +class NotFoundError extends KVError { + constructor(message = `Not Found`, status = 404) { + super(message, status); + } +} +exports.NotFoundError = NotFoundError; +class InternalError extends KVError { + constructor(message = `Internal Error in KV Asset Handler`, status = 500) { + super(message, status); + } +} +exports.InternalError = InternalError; diff --git a/node_modules/@cloudflare/kv-asset-handler/package.json b/node_modules/@cloudflare/kv-asset-handler/package.json new file mode 100644 index 0000000..3ec9c42 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/package.json @@ -0,0 +1,52 @@ +{ + "name": "@cloudflare/kv-asset-handler", + "version": "0.2.0", + "description": "Routes requests to KV assets", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "prepack": "npm run build", + "build": "tsc -d", + "format": "prettier --write \"**/*.{js,ts,json,md}\"", + "pretest": "npm run build", + "lint:code": "prettier --check \"**/*.{js,ts,json,md}\"", + "lint:markdown": "markdownlint \"**/*.md\" --ignore node_modules", + "test": "ava dist/test/*.js --verbose" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/cloudflare/kv-asset-handler.git" + }, + "keywords": [ + "kv", + "cloudflare", + "workers", + "wrangler", + "assets" + ], + "files": [ + "src", + "dist", + "LICENSE_APACHE", + "LICENSE_MIT" + ], + "author": "wrangler@cloudflare.com", + "license": "MIT OR Apache-2.0", + "bugs": { + "url": "https://github.com/cloudflare/kv-asset-handler/issues" + }, + "homepage": "https://github.com/cloudflare/kv-asset-handler#readme", + "dependencies": { + "mime": "^3.0.0" + }, + "devDependencies": { + "@ava/typescript": "^3.0.0", + "@cloudflare/workers-types": "^3.0.0", + "@types/mime": "^2.0.3", + "@types/node": "^15.14.9", + "ava": "^3.15.0", + "prettier": "^2.4.1", + "service-worker-mock": "^2.0.5", + "typescript": "^4.4.4" + } +} diff --git a/node_modules/@cloudflare/kv-asset-handler/src/index.ts b/node_modules/@cloudflare/kv-asset-handler/src/index.ts new file mode 100644 index 0000000..5a91b68 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/index.ts @@ -0,0 +1,312 @@ +import * as mime from 'mime' +import { + Options, + CacheControl, + MethodNotAllowedError, + NotFoundError, + InternalError, + AssetManifestType, +} from './types' + +declare global { + var __STATIC_CONTENT: any, __STATIC_CONTENT_MANIFEST: string +} + +const defaultCacheControl: CacheControl = { + browserTTL: null, + edgeTTL: 2 * 60 * 60 * 24, // 2 days + bypassCache: false, // do not bypass Cloudflare's cache +} + +const parseStringAsObject = <T>(maybeString: string | T): T => + typeof maybeString === 'string' ? (JSON.parse(maybeString) as T) : maybeString + +const getAssetFromKVDefaultOptions: Partial<Options> = { + ASSET_NAMESPACE: typeof __STATIC_CONTENT !== 'undefined' ? __STATIC_CONTENT : undefined, + ASSET_MANIFEST: + typeof __STATIC_CONTENT_MANIFEST !== 'undefined' + ? parseStringAsObject<AssetManifestType>(__STATIC_CONTENT_MANIFEST) + : {}, + cacheControl: defaultCacheControl, + defaultMimeType: 'text/plain', + defaultDocument: 'index.html', + pathIsEncoded: false, +} + +function assignOptions(options?: Partial<Options>): Options { + // Assign any missing options passed in to the default + // options.mapRequestToAsset is handled manually later + return <Options>Object.assign({}, getAssetFromKVDefaultOptions, options) +} + +/** + * maps the path of incoming request to the request pathKey to look up + * in bucket and in cache + * e.g. for a path '/' returns '/index.html' which serves + * the content of bucket/index.html + * @param {Request} request incoming request + */ +const mapRequestToAsset = (request: Request, options?: Partial<Options>) => { + options = assignOptions(options) + + const parsedUrl = new URL(request.url) + let pathname = parsedUrl.pathname + + if (pathname.endsWith('/')) { + // If path looks like a directory append options.defaultDocument + // e.g. If path is /about/ -> /about/index.html + pathname = pathname.concat(options.defaultDocument) + } else if (!mime.getType(pathname)) { + // If path doesn't look like valid content + // e.g. /about.me -> /about.me/index.html + pathname = pathname.concat('/' + options.defaultDocument) + } + + parsedUrl.pathname = pathname + return new Request(parsedUrl.toString(), request) +} + +/** + * maps the path of incoming request to /index.html if it evaluates to + * any HTML file. + * @param {Request} request incoming request + */ +function serveSinglePageApp(request: Request, options?: Partial<Options>): Request { + options = assignOptions(options) + + // First apply the default handler, which already has logic to detect + // paths that should map to HTML files. + request = mapRequestToAsset(request, options) + + const parsedUrl = new URL(request.url) + + // Detect if the default handler decided to map to + // a HTML file in some specific directory. + if (parsedUrl.pathname.endsWith('.html')) { + // If expected HTML file was missing, just return the root index.html (or options.defaultDocument) + return new Request(`${parsedUrl.origin}/${options.defaultDocument}`, request) + } else { + // The default handler decided this is not an HTML page. It's probably + // an image, CSS, or JS file. Leave it as-is. + return request + } +} + +/** + * takes the path of the incoming request, gathers the appropriate content from KV, and returns + * the response + * + * @param {FetchEvent} event the fetch event of the triggered request + * @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options + * @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser + * @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up + * @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references + * @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV + * */ + +type Evt = { + request: Request + waitUntil: (promise: Promise<any>) => void +} + +const getAssetFromKV = async (event: Evt, options?: Partial<Options>): Promise<Response> => { + options = assignOptions(options) + + const request = event.request + const ASSET_NAMESPACE = options.ASSET_NAMESPACE + const ASSET_MANIFEST = parseStringAsObject<AssetManifestType>(options.ASSET_MANIFEST) + + if (typeof ASSET_NAMESPACE === 'undefined') { + throw new InternalError(`there is no KV namespace bound to the script`) + } + + const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, '') // strip any preceding /'s + let pathIsEncoded = options.pathIsEncoded + let requestKey + // if options.mapRequestToAsset is explicitly passed in, always use it and assume user has own intentions + // otherwise handle request as normal, with default mapRequestToAsset below + if (options.mapRequestToAsset) { + requestKey = options.mapRequestToAsset(request) + } else if (ASSET_MANIFEST[rawPathKey]) { + requestKey = request + } else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) { + pathIsEncoded = true + requestKey = request + } else { + const mappedRequest = mapRequestToAsset(request) + const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace(/^\/+/, '') + if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) { + pathIsEncoded = true + requestKey = mappedRequest + } else { + // use default mapRequestToAsset + requestKey = mapRequestToAsset(request, options) + } + } + + const SUPPORTED_METHODS = ['GET', 'HEAD'] + if (!SUPPORTED_METHODS.includes(requestKey.method)) { + throw new MethodNotAllowedError(`${requestKey.method} is not a valid request method`) + } + + const parsedUrl = new URL(requestKey.url) + const pathname = pathIsEncoded ? decodeURIComponent(parsedUrl.pathname) : parsedUrl.pathname // decode percentage encoded path only when necessary + + // pathKey is the file path to look up in the manifest + let pathKey = pathname.replace(/^\/+/, '') // remove prepended / + + // @ts-ignore + const cache = caches.default + let mimeType = mime.getType(pathKey) || options.defaultMimeType + if (mimeType.startsWith('text') || mimeType === 'application/javascript') { + mimeType += '; charset=utf-8' + } + + let shouldEdgeCache = false // false if storing in KV by raw file path i.e. no hash + // check manifest for map from file path to hash + if (typeof ASSET_MANIFEST !== 'undefined') { + if (ASSET_MANIFEST[pathKey]) { + pathKey = ASSET_MANIFEST[pathKey] + // if path key is in asset manifest, we can assume it contains a content hash and can be cached + shouldEdgeCache = true + } + } + + // TODO this excludes search params from cache, investigate ideal behavior + let cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request) + + // if argument passed in for cacheControl is a function then + // evaluate that function. otherwise return the Object passed in + // or default Object + const evalCacheOpts = (() => { + switch (typeof options.cacheControl) { + case 'function': + return options.cacheControl(request) + case 'object': + return options.cacheControl + default: + return defaultCacheControl + } + })() + + // formats the etag depending on the response context. if the entityId + // is invalid, returns an empty string (instead of null) to prevent the + // the potentially disastrous scenario where the value of the Etag resp + // header is "null". Could be modified in future to base64 encode etc + const formatETag = (entityId: any = pathKey, validatorType: string = 'strong') => { + if (!entityId) { + return '' + } + switch (validatorType) { + case 'weak': + if (!entityId.startsWith('W/')) { + return `W/${entityId}` + } + return entityId + case 'strong': + if (entityId.startsWith(`W/"`)) { + entityId = entityId.replace('W/', '') + } + if (!entityId.endsWith(`"`)) { + entityId = `"${entityId}"` + } + return entityId + default: + return '' + } + } + + options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts) + + // override shouldEdgeCache if options say to bypassCache + if ( + options.cacheControl.bypassCache || + options.cacheControl.edgeTTL === null || + request.method == 'HEAD' + ) { + shouldEdgeCache = false + } + // only set max-age if explicitly passed in a number as an arg + const shouldSetBrowserCache = typeof options.cacheControl.browserTTL === 'number' + + let response = null + if (shouldEdgeCache) { + response = await cache.match(cacheKey) + } + + if (response) { + if (response.status > 300 && response.status < 400) { + if (response.body && 'cancel' in Object.getPrototypeOf(response.body)) { + // Body exists and environment supports readable streams + response.body.cancel() + } else { + // Environment doesnt support readable streams, or null repsonse body. Nothing to do + } + response = new Response(null, response) + } else { + // fixes #165 + let opts = { + headers: new Headers(response.headers), + status: 0, + statusText: '', + } + + opts.headers.set('cf-cache-status', 'HIT') + + if (response.status) { + opts.status = response.status + opts.statusText = response.statusText + } else if (opts.headers.has('Content-Range')) { + opts.status = 206 + opts.statusText = 'Partial Content' + } else { + opts.status = 200 + opts.statusText = 'OK' + } + response = new Response(response.body, opts) + } + } else { + const body = await ASSET_NAMESPACE.get(pathKey, 'arrayBuffer') + if (body === null) { + throw new NotFoundError(`could not find ${pathKey} in your content namespace`) + } + response = new Response(body) + + if (shouldEdgeCache) { + response.headers.set('Accept-Ranges', 'bytes') + response.headers.set('Content-Length', body.length) + // set etag before cache insertion + if (!response.headers.has('etag')) { + response.headers.set('etag', formatETag(pathKey, 'strong')) + } + // determine Cloudflare cache behavior + response.headers.set('Cache-Control', `max-age=${options.cacheControl.edgeTTL}`) + event.waitUntil(cache.put(cacheKey, response.clone())) + response.headers.set('CF-Cache-Status', 'MISS') + } + } + response.headers.set('Content-Type', mimeType) + + if (response.status === 304) { + let etag = formatETag(response.headers.get('etag'), 'strong') + let ifNoneMatch = cacheKey.headers.get('if-none-match') + let proxyCacheStatus = response.headers.get('CF-Cache-Status') + if (etag) { + if (ifNoneMatch && ifNoneMatch === etag && proxyCacheStatus === 'MISS') { + response.headers.set('CF-Cache-Status', 'EXPIRED') + } else { + response.headers.set('CF-Cache-Status', 'REVALIDATED') + } + response.headers.set('etag', formatETag(etag, 'weak')) + } + } + if (shouldSetBrowserCache) { + response.headers.set('Cache-Control', `max-age=${options.cacheControl.browserTTL}`) + } else { + response.headers.delete('Cache-Control') + } + return response +} + +export { getAssetFromKV, mapRequestToAsset, serveSinglePageApp } +export { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError } diff --git a/node_modules/@cloudflare/kv-asset-handler/src/mocks.ts b/node_modules/@cloudflare/kv-asset-handler/src/mocks.ts new file mode 100644 index 0000000..b42fb74 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/mocks.ts @@ -0,0 +1,148 @@ +const makeServiceWorkerEnv = require('service-worker-mock') + +const HASH = '123HASHBROWN' + +export const getEvent = (request: Request): any => { + const waitUntil = async (callback: any) => { + await callback + } + return { + request, + waitUntil, + } +} +const store: any = { + 'key1.123HASHBROWN.txt': 'val1', + 'key1.123HASHBROWN.png': 'val1', + 'index.123HASHBROWN.html': 'index.html', + 'cache.123HASHBROWN.html': 'cache me if you can', + '测试.123HASHBROWN.html': 'My filename is non-ascii', + '%not-really-percent-encoded.123HASHBROWN.html': 'browser percent encoded', + '%2F.123HASHBROWN.html': 'user percent encoded', + '你好.123HASHBROWN.html': 'I shouldnt be served', + '%E4%BD%A0%E5%A5%BD.123HASHBROWN.html': 'Im important', + 'nohash.txt': 'no hash but still got some result', + 'sub/blah.123HASHBROWN.png': 'picturedis', + 'sub/index.123HASHBROWN.html': 'picturedis', + 'client.123HASHBROWN': 'important file', + 'client.123HASHBROWN/index.html': 'Im here but serve my big bro above', + 'image.123HASHBROWN.png': 'imagepng', + 'image.123HASHBROWN.webp': 'imagewebp', + '你好/index.123HASHBROWN.html': 'My path is non-ascii', +} +export const mockKV = (store: any) => { + return { + get: (path: string) => store[path] || null, + } +} + +export const mockManifest = () => { + return JSON.stringify({ + 'key1.txt': `key1.${HASH}.txt`, + 'key1.png': `key1.${HASH}.png`, + 'cache.html': `cache.${HASH}.html`, + '测试.html': `测试.${HASH}.html`, + '你好.html': `你好.${HASH}.html`, + '%not-really-percent-encoded.html': `%not-really-percent-encoded.${HASH}.html`, + '%2F.html': `%2F.${HASH}.html`, + '%E4%BD%A0%E5%A5%BD.html': `%E4%BD%A0%E5%A5%BD.${HASH}.html`, + 'index.html': `index.${HASH}.html`, + 'sub/blah.png': `sub/blah.${HASH}.png`, + 'sub/index.html': `sub/index.${HASH}.html`, + client: `client.${HASH}`, + 'client/index.html': `client.${HASH}`, + 'image.png': `image.${HASH}.png`, + 'image.webp': `image.${HASH}.webp`, + '你好/index.html': `你好/index.${HASH}.html`, + }) +} + +let cacheStore: any = new Map() +interface CacheKey { + url: object + headers: object +} +export const mockCaches = () => { + return { + default: { + async match(key: any) { + let cacheKey: CacheKey = { + url: key.url, + headers: {}, + } + let response + if (key.headers.has('if-none-match')) { + let makeStrongEtag = key.headers.get('if-none-match').replace('W/', '') + Reflect.set(cacheKey.headers, 'etag', makeStrongEtag) + response = cacheStore.get(JSON.stringify(cacheKey)) + } else { + // if client doesn't send if-none-match, we need to iterate through these keys + // and just test the URL + const activeCacheKeys: Array<string> = Array.from(cacheStore.keys()) + for (const cacheStoreKey of activeCacheKeys) { + if (JSON.parse(cacheStoreKey).url === key.url) { + response = cacheStore.get(cacheStoreKey) + } + } + } + // TODO: write test to accomodate for rare scenarios with where range requests accomodate etags + if (response && !key.headers.has('if-none-match')) { + // this appears overly verbose, but is necessary to document edge cache behavior + // The Range request header triggers the response header Content-Range ... + const range = key.headers.get('range') + if (range) { + response.headers.set( + 'content-range', + `bytes ${range.split('=').pop()}/${response.headers.get('content-length')}`, + ) + } + // ... which we are using in this repository to set status 206 + if (response.headers.has('content-range')) { + response.status = 206 + } else { + response.status = 200 + } + let etag = response.headers.get('etag') + if (etag && !etag.includes('W/')) { + response.headers.set('etag', `W/${etag}`) + } + } + return response + }, + async put(key: any, val: Response) { + let headers = new Headers(val.headers) + let url = new URL(key.url) + let resWithBody = new Response(val.body, { headers, status: 200 }) + let resNoBody = new Response(null, { headers, status: 304 }) + let cacheKey: CacheKey = { + url: key.url, + headers: { + etag: `"${url.pathname.replace('/', '')}"`, + }, + } + cacheStore.set(JSON.stringify(cacheKey), resNoBody) + cacheKey.headers = {} + cacheStore.set(JSON.stringify(cacheKey), resWithBody) + return + }, + }, + } +} + +// mocks functionality used inside worker request +export function mockRequestScope() { + Object.assign(global, makeServiceWorkerEnv()) + Object.assign(global, { __STATIC_CONTENT_MANIFEST: mockManifest() }) + Object.assign(global, { __STATIC_CONTENT: mockKV(store) }) + Object.assign(global, { caches: mockCaches() }) +} + +// mocks functionality used on global isolate scope. such as the KV namespace bind +export function mockGlobalScope() { + Object.assign(global, { __STATIC_CONTENT_MANIFEST: mockManifest() }) + Object.assign(global, { __STATIC_CONTENT: mockKV(store) }) +} + +export const sleep = (milliseconds: number) => { + return new Promise((resolve) => setTimeout(resolve, milliseconds)) +} diff --git a/node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV-optional.ts b/node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV-optional.ts new file mode 100644 index 0000000..9740b7d --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV-optional.ts @@ -0,0 +1,24 @@ +import test from 'ava' +import { mockRequestScope, mockGlobalScope, getEvent, sleep, mockKV, mockManifest } from '../mocks' +mockGlobalScope() + +// manually reset manifest global, to test optional behaviour +Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined }) + +import { getAssetFromKV, mapRequestToAsset } from '../index' + +test('getAssetFromKV return correct val from KV without manifest', async (t) => { + mockRequestScope() + // manually reset manifest global, to test optional behaviour + Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined }) + + const event = getEvent(new Request('https://blah.com/key1.123HASHBROWN.txt')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(await res.text(), 'val1') + t.true(res.headers.get('content-type').includes('text')) + } else { + t.fail('Response was undefined') + } +}) diff --git a/node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts b/node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts new file mode 100644 index 0000000..425d622 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts @@ -0,0 +1,488 @@ +import test from 'ava' +import { mockRequestScope, mockGlobalScope, getEvent, sleep, mockKV, mockManifest } from '../mocks' +mockGlobalScope() + +import { getAssetFromKV, mapRequestToAsset } from '../index' +import { KVError } from '../types' + +test('getAssetFromKV return correct val from KV and default caching', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/key1.txt')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(res.headers.get('cache-control'), null) + t.is(res.headers.get('cf-cache-status'), 'MISS') + t.is(await res.text(), 'val1') + t.true(res.headers.get('content-type').includes('text')) + } else { + t.fail('Response was undefined') + } +}) +test('getAssetFromKV evaluated the file matching the extensionless path first /client/ -> client', async (t) => { + mockRequestScope() + const event = getEvent(new Request(`https://foo.com/client/`)) + const res = await getAssetFromKV(event) + t.is(await res.text(), 'important file') + t.true(res.headers.get('content-type').includes('text')) +}) +test('getAssetFromKV evaluated the file matching the extensionless path first /client -> client', async (t) => { + mockRequestScope() + const event = getEvent(new Request(`https://foo.com/client`)) + const res = await getAssetFromKV(event) + t.is(await res.text(), 'important file') + t.true(res.headers.get('content-type').includes('text')) +}) + +test('getAssetFromKV if not in asset manifest still returns nohash.txt', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/nohash.txt')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(await res.text(), 'no hash but still got some result') + t.true(res.headers.get('content-type').includes('text')) + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV if no asset manifest /client -> client fails', async (t) => { + mockRequestScope() + const event = getEvent(new Request(`https://foo.com/client`)) + const error: KVError = await t.throwsAsync(getAssetFromKV(event, { ASSET_MANIFEST: {} })) + t.is(error.status, 404) +}) + +test('getAssetFromKV if sub/ -> sub/index.html served', async (t) => { + mockRequestScope() + const event = getEvent(new Request(`https://foo.com/sub`)) + const res = await getAssetFromKV(event) + if (res) { + t.is(await res.text(), 'picturedis') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV gets index.html by default for / requests', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(await res.text(), 'index.html') + t.true(res.headers.get('content-type').includes('html')) + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV non ASCII path support', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/测试.html')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(await res.text(), 'My filename is non-ascii') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV supports browser percent encoded URLs', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://example.com/%not-really-percent-encoded.html')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(await res.text(), 'browser percent encoded') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV supports user percent encoded URLs', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/%2F.html')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(await res.text(), 'user percent encoded') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV only decode URL when necessary', async (t) => { + mockRequestScope() + const event1 = getEvent(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD.html')) + const event2 = getEvent(new Request('https://blah.com/你好.html')) + const res1 = await getAssetFromKV(event1) + const res2 = await getAssetFromKV(event2) + + if (res1 && res2) { + t.is(await res1.text(), 'Im important') + t.is(await res2.text(), 'Im important') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV Support for user decode url path', async (t) => { + mockRequestScope() + const event1 = getEvent(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD/')) + const event2 = getEvent(new Request('https://blah.com/你好/')) + const res1 = await getAssetFromKV(event1) + const res2 = await getAssetFromKV(event2) + + if (res1 && res2) { + t.is(await res1.text(), 'My path is non-ascii') + t.is(await res2.text(), 'My path is non-ascii') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV custom key modifier', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/docs/sub/blah.png')) + + const customRequestMapper = (request: Request) => { + let defaultModifiedRequest = mapRequestToAsset(request) + + let url = new URL(defaultModifiedRequest.url) + url.pathname = url.pathname.replace('/docs', '') + return new Request(url.toString(), request) + } + + const res = await getAssetFromKV(event, { mapRequestToAsset: customRequestMapper }) + + if (res) { + t.is(await res.text(), 'picturedis') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV request override with existing manifest file', async (t) => { + // see https://github.com/cloudflare/kv-asset-handler/pull/159 for more info + mockRequestScope() + const event = getEvent(new Request('https://blah.com/image.png')) // real file in manifest + + const customRequestMapper = (request: Request) => { + let defaultModifiedRequest = mapRequestToAsset(request) + + let url = new URL(defaultModifiedRequest.url) + url.pathname = '/image.webp' // other different file in manifest + return new Request(url.toString(), request) + } + + const res = await getAssetFromKV(event, { mapRequestToAsset: customRequestMapper }) + + if (res) { + t.is(await res.text(), 'imagewebp') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV when setting browser caching', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/')) + + const res = await getAssetFromKV(event, { cacheControl: { browserTTL: 22 } }) + + if (res) { + t.is(res.headers.get('cache-control'), 'max-age=22') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV when setting custom cache setting', async (t) => { + mockRequestScope() + const event1 = getEvent(new Request('https://blah.com/')) + const event2 = getEvent(new Request('https://blah.com/key1.png?blah=34')) + const cacheOnlyPngs = (req: Request) => { + if (new URL(req.url).pathname.endsWith('.png')) + return { + browserTTL: 720, + edgeTTL: 720, + } + else + return { + bypassCache: true, + } + } + + const res1 = await getAssetFromKV(event1, { cacheControl: cacheOnlyPngs }) + const res2 = await getAssetFromKV(event2, { cacheControl: cacheOnlyPngs }) + + if (res1 && res2) { + t.is(res1.headers.get('cache-control'), null) + t.true(res2.headers.get('content-type').includes('png')) + t.is(res2.headers.get('cache-control'), 'max-age=720') + t.is(res2.headers.get('cf-cache-status'), 'MISS') + } else { + t.fail('Response was undefined') + } +}) +test('getAssetFromKV caches on two sequential requests', async (t) => { + mockRequestScope() + const resourceKey = 'cache.html' + const resourceVersion = JSON.parse(mockManifest())[resourceKey] + const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`)) + const event2 = getEvent( + new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + }), + ) + + const res1 = await getAssetFromKV(event1, { cacheControl: { edgeTTL: 720, browserTTL: 720 } }) + await sleep(1) + const res2 = await getAssetFromKV(event2) + + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS') + t.is(res1.headers.get('cache-control'), 'max-age=720') + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED') + } else { + t.fail('Response was undefined') + } +}) +test('getAssetFromKV does not store max-age on two sequential requests', async (t) => { + mockRequestScope() + const resourceKey = 'cache.html' + const resourceVersion = JSON.parse(mockManifest())[resourceKey] + const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`)) + const event2 = getEvent( + new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + }), + ) + + const res1 = await getAssetFromKV(event1, { cacheControl: { edgeTTL: 720 } }) + await sleep(100) + const res2 = await getAssetFromKV(event2) + + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS') + t.is(res1.headers.get('cache-control'), null) + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED') + t.is(res2.headers.get('cache-control'), null) + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV does not cache on Cloudflare when bypass cache set', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/')) + + const res = await getAssetFromKV(event, { cacheControl: { bypassCache: true } }) + + if (res) { + t.is(res.headers.get('cache-control'), null) + t.is(res.headers.get('cf-cache-status'), null) + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV with no trailing slash on root', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com')) + const res = await getAssetFromKV(event) + if (res) { + t.is(await res.text(), 'index.html') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV with no trailing slash on a subdirectory', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/sub/blah.png')) + const res = await getAssetFromKV(event) + if (res) { + t.is(await res.text(), 'picturedis') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV no result throws an error', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/random')) + const error: KVError = await t.throwsAsync(getAssetFromKV(event)) + t.is(error.status, 404) +}) +test('getAssetFromKV TTls set to null should not cache on browser or edge', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/')) + + const res1 = await getAssetFromKV(event, { cacheControl: { browserTTL: null, edgeTTL: null } }) + await sleep(100) + const res2 = await getAssetFromKV(event, { cacheControl: { browserTTL: null, edgeTTL: null } }) + + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), null) + t.is(res1.headers.get('cache-control'), null) + t.is(res2.headers.get('cf-cache-status'), null) + t.is(res2.headers.get('cache-control'), null) + } else { + t.fail('Response was undefined') + } +}) +test('getAssetFromKV passing in a custom NAMESPACE serves correct asset', async (t) => { + mockRequestScope() + let CUSTOM_NAMESPACE = mockKV({ + 'key1.123HASHBROWN.txt': 'val1', + }) + Object.assign(global, { CUSTOM_NAMESPACE }) + const event = getEvent(new Request('https://blah.com/')) + const res = await getAssetFromKV(event) + if (res) { + t.is(await res.text(), 'index.html') + t.true(res.headers.get('content-type').includes('html')) + } else { + t.fail('Response was undefined') + } +}) +test('getAssetFromKV when custom namespace without the asset should fail', async (t) => { + mockRequestScope() + let CUSTOM_NAMESPACE = mockKV({ + 'key5.123HASHBROWN.txt': 'customvalu', + }) + + const event = getEvent(new Request('https://blah.com')) + const error: KVError = await t.throwsAsync( + getAssetFromKV(event, { ASSET_NAMESPACE: CUSTOM_NAMESPACE }), + ) + t.is(error.status, 404) +}) +test('getAssetFromKV when namespace not bound fails', async (t) => { + mockRequestScope() + var MY_CUSTOM_NAMESPACE = undefined + Object.assign(global, { MY_CUSTOM_NAMESPACE }) + + const event = getEvent(new Request('https://blah.com/')) + const error: KVError = await t.throwsAsync( + getAssetFromKV(event, { ASSET_NAMESPACE: MY_CUSTOM_NAMESPACE }), + ) + t.is(error.status, 500) +}) + +test('getAssetFromKV when if-none-match === active resource version, should revalidate', async (t) => { + mockRequestScope() + const resourceKey = 'key1.png' + const resourceVersion = JSON.parse(mockManifest())[resourceKey] + const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`)) + const event2 = getEvent( + new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `W/"${resourceVersion}"`, + }, + }), + ) + + const res1 = await getAssetFromKV(event1, { cacheControl: { edgeTTL: 720 } }) + await sleep(100) + const res2 = await getAssetFromKV(event2) + + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS') + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV when if-none-match equals etag of stale resource then should bypass cache', async (t) => { + mockRequestScope() + const resourceKey = 'key1.png' + const resourceVersion = JSON.parse(mockManifest())[resourceKey] + const req1 = new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + }) + const req2 = new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}-another-version"`, + }, + }) + const event = getEvent(req1) + const event2 = getEvent(req2) + const res1 = await getAssetFromKV(event, { cacheControl: { edgeTTL: 720 } }) + const res2 = await getAssetFromKV(event) + const res3 = await getAssetFromKV(event2) + if (res1 && res2 && res3) { + t.is(res1.headers.get('cf-cache-status'), 'MISS') + t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`) + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED') + t.not(res3.headers.get('etag'), req2.headers.get('if-none-match')) + t.is(res3.headers.get('cf-cache-status'), 'MISS') + } else { + t.fail('Response was undefined') + } +}) +test('getAssetFromKV when resource in cache, etag should be weakened before returned to eyeball', async (t) => { + mockRequestScope() + const resourceKey = 'key1.png' + const resourceVersion = JSON.parse(mockManifest())[resourceKey] + const req1 = new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + }) + const event = getEvent(req1) + const res1 = await getAssetFromKV(event, { cacheControl: { edgeTTL: 720 } }) + const res2 = await getAssetFromKV(event) + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS') + t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`) + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV if-none-match not sent but resource in cache, should return cache hit 200 OK', async (t) => { + const resourceKey = 'cache.html' + const event = getEvent(new Request(`https://blah.com/${resourceKey}`)) + const res1 = await getAssetFromKV(event, { cacheControl: { edgeTTL: 720 } }) + await sleep(1) + const res2 = await getAssetFromKV(event) + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS') + t.is(res1.headers.get('cache-control'), null) + t.is(res2.status, 200) + t.is(res2.headers.get('cf-cache-status'), 'HIT') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV if range request submitted and resource in cache, request fulfilled', async (t) => { + const resourceKey = 'cache.html' + const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`)) + const event2 = getEvent( + new Request(`https://blah.com/${resourceKey}`, { headers: { range: 'bytes=0-10' } }), + ) + const res1 = getAssetFromKV(event1, { cacheControl: { edgeTTL: 720 } }) + await res1 + await sleep(2) + const res2 = await getAssetFromKV(event2) + if (res2.headers.has('content-range')) { + t.is(res2.status, 206) + } else { + t.fail('Response was undefined') + } +}) + +test.todo('getAssetFromKV when body not empty, should invoke .cancel()') diff --git a/node_modules/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts b/node_modules/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts new file mode 100644 index 0000000..422165e --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts @@ -0,0 +1,37 @@ +import test from 'ava' +import { mockRequestScope, mockGlobalScope } from '../mocks' +mockGlobalScope() + +import { mapRequestToAsset } from '../index' + +test('mapRequestToAsset() correctly changes /about -> /about/index.html', async (t) => { + mockRequestScope() + let path = '/about' + let request = new Request(`https://foo.com${path}`) + let newRequest = mapRequestToAsset(request) + t.is(newRequest.url, request.url + '/index.html') +}) + +test('mapRequestToAsset() correctly changes /about/ -> /about/index.html', async (t) => { + mockRequestScope() + let path = '/about/' + let request = new Request(`https://foo.com${path}`) + let newRequest = mapRequestToAsset(request) + t.is(newRequest.url, request.url + 'index.html') +}) + +test('mapRequestToAsset() correctly changes /about.me/ -> /about.me/index.html', async (t) => { + mockRequestScope() + let path = '/about.me/' + let request = new Request(`https://foo.com${path}`) + let newRequest = mapRequestToAsset(request) + t.is(newRequest.url, request.url + 'index.html') +}) + +test('mapRequestToAsset() correctly changes /about -> /about/default.html', async (t) => { + mockRequestScope() + let path = '/about' + let request = new Request(`https://foo.com${path}`) + let newRequest = mapRequestToAsset(request, { defaultDocument: 'default.html' }) + t.is(newRequest.url, request.url + '/default.html') +}) diff --git a/node_modules/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts b/node_modules/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts new file mode 100644 index 0000000..6c634c8 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts @@ -0,0 +1,44 @@ +import test from 'ava' +import { mockRequestScope, mockGlobalScope } from '../mocks' +mockGlobalScope() + +import { serveSinglePageApp } from '../index' + +function testRequest(path: string) { + mockRequestScope() + let url = new URL('https://example.com') + url.pathname = path + let request = new Request(url.toString()) + + return request +} + +test('serveSinglePageApp returns root asset path when request path ends in .html', async (t) => { + let path = '/foo/thing.html' + let request = testRequest(path) + + let expected_request = testRequest('/index.html') + let actual_request = serveSinglePageApp(request) + + t.deepEqual(expected_request, actual_request) +}) + +test('serveSinglePageApp returns root asset path when request path does not have extension', async (t) => { + let path = '/foo/thing' + let request = testRequest(path) + + let expected_request = testRequest('/index.html') + let actual_request = serveSinglePageApp(request) + + t.deepEqual(expected_request, actual_request) +}) + +test('serveSinglePageApp returns requested asset when request path has non-html extension', async (t) => { + let path = '/foo/thing.js' + let request = testRequest(path) + + let expected_request = request + let actual_request = serveSinglePageApp(request) + + t.deepEqual(expected_request, actual_request) +}) diff --git a/node_modules/@cloudflare/kv-asset-handler/src/types.ts b/node_modules/@cloudflare/kv-asset-handler/src/types.ts new file mode 100644 index 0000000..c806076 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/types.ts @@ -0,0 +1,43 @@ +export type CacheControl = { + browserTTL: number + edgeTTL: number + bypassCache: boolean +} + +export type AssetManifestType = Record<string, string> + +export type Options = { + cacheControl: ((req: Request) => Partial<CacheControl>) | Partial<CacheControl> + ASSET_NAMESPACE: any + ASSET_MANIFEST: AssetManifestType | string + mapRequestToAsset?: (req: Request, options?: Partial<Options>) => Request + defaultMimeType: string + defaultDocument: string + pathIsEncoded: boolean +} + +export class KVError extends Error { + constructor(message?: string, status: number = 500) { + super(message) + // see: typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html + Object.setPrototypeOf(this, new.target.prototype) // restore prototype chain + this.name = KVError.name // stack traces display correctly now + this.status = status + } + status: number +} +export class MethodNotAllowedError extends KVError { + constructor(message: string = `Not a valid request method`, status: number = 405) { + super(message, status) + } +} +export class NotFoundError extends KVError { + constructor(message: string = `Not Found`, status: number = 404) { + super(message, status) + } +} +export class InternalError extends KVError { + constructor(message: string = `Internal Error in KV Asset Handler`, status: number = 500) { + super(message, status) + } +} diff --git a/node_modules/@cloudflare/workerd-linux-64/README.md b/node_modules/@cloudflare/workerd-linux-64/README.md new file mode 100644 index 0000000..edbebe8 --- /dev/null +++ b/node_modules/@cloudflare/workerd-linux-64/README.md @@ -0,0 +1,6 @@ +# 👷 `workerd` for Linux 64-bit, Cloudflare's JavaScript/Wasm Runtime + +`workerd` is a JavaScript / Wasm server runtime based on the same code that powers +[Cloudflare Workers](https://workers.dev). + +See https://github.com/cloudflare/workerd for details. diff --git a/node_modules/@cloudflare/workerd-linux-64/bin/workerd b/node_modules/@cloudflare/workerd-linux-64/bin/workerd Binary files differnew file mode 100755 index 0000000..70c93ec --- /dev/null +++ b/node_modules/@cloudflare/workerd-linux-64/bin/workerd diff --git a/node_modules/@cloudflare/workerd-linux-64/package.json b/node_modules/@cloudflare/workerd-linux-64/package.json new file mode 100644 index 0000000..879451b --- /dev/null +++ b/node_modules/@cloudflare/workerd-linux-64/package.json @@ -0,0 +1,17 @@ +{ + "name": "@cloudflare/workerd-linux-64", + "description": "👷 workerd for Linux 64-bit, Cloudflare's JavaScript/Wasm Runtime", + "repository": "https://github.com/cloudflare/workerd", + "license": "Apache-2.0", + "preferUnplugged": false, + "engines": { + "node": ">=16" + }, + "os": [ + "linux" + ], + "cpu": [ + "x64" + ], + "version": "1.20230904.0" +} diff --git a/node_modules/@cloudflare/workers-types/2021-11-03/index.d.ts b/node_modules/@cloudflare/workers-types/2021-11-03/index.d.ts new file mode 100755 index 0000000..3fc670f --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2021-11-03/index.d.ts @@ -0,0 +1,3305 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +declare function btoa(data: string): string; +declare function atob(data: string): string; +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearTimeout(timeoutId: number | null): void; +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearInterval(timeoutId: number | null): void; +declare function queueMicrotask(task: Function): void; +declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +declare type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +declare interface Performance { + readonly timeOrigin: number; + now(): number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +declare interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +declare interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +declare interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. */ + readonly eventPhase: number; + /** Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. */ + readonly composed: boolean; + /** Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. */ + readonly bubbles: boolean; + /** Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. */ + readonly cancelable: boolean; + /** Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. */ + readonly defaultPrevented: boolean; + /** @deprecated */ + readonly returnValue: boolean; + /** Returns the object whose event listener's callback is currently being invoked. */ + readonly currentTarget?: EventTarget; + /** @deprecated */ + readonly srcElement?: EventTarget; + /** Returns the event's timestamp as the number of milliseconds measured relative to the time origin. */ + readonly timeStamp: number; + /** Returns true if event was dispatched by the user agent, and false otherwise. */ + readonly isTrusted: boolean; + cancelBubble: boolean; + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +declare interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** Returns the AbortSignal object associated with this object. */ + readonly signal: AbortSignal; + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. */ + readonly aborted: boolean; + readonly reason: any; + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + readonly size: number; + readonly type: string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + readonly name: string; + readonly lastModified: number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** Available only in secure contexts. */ + readonly subtle: SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise<ArrayBuffer>; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; +} +declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + readonly encoding: string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + readonly status: number; + readonly statusText: string; + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly url: string; + readonly webSocket: WebSocket | null; + readonly cf?: any; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + /** Returns request's HTTP method, which is "GET" by default. */ + readonly method: string; + /** Returns the URL of request as a string. */ + readonly url: string; + /** Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. */ + readonly headers: Headers; + /** Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. */ + readonly redirect: string; + readonly fetcher: Fetcher | null; + /** Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. */ + readonly signal: AbortSignal; + readonly cf?: Cf; + /** Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] */ + readonly integrity: string; + /** Returns a boolean indicating whether or not request can outlive the global in which it was created. */ + readonly keepalive: boolean; +} +declare interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +declare interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; +} +declare interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +declare interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +declare interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +declare interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +declare interface ReadableStream<R = any> { + readonly locked: boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + readonly closed: Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + readonly closed: Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +declare interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +declare interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +declare interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +declare interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +declare interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +declare interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +declare interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + readonly locked: boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + readonly closed: Promise<void>; + readonly ready: Promise<void>; + readonly desiredSize: number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + readonly readable: ReadableStream<O>; + readonly writable: WritableStream<I>; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream<string, Uint8Array> { + constructor(); +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + href: string; + readonly origin: string; + protocol: string; + username: string; + password: string; + host: string; + hostname: string; + port: string; + pathname: string; + search: string; + readonly searchParams: URLSearchParams; + hash: string; + toString(): string; + toJSON(): string; +} +declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record<string, string> + | [key: string, value: string][] + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +declare interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + /** Returns the state of the WebSocket object's connection. It can have the values described below. */ + readonly readyState: number; + /** Returns the URL that was used to establish the WebSocket connection. */ + readonly url: string | null; + /** Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. */ + readonly protocol: string | null; + /** Returns the extensions selected by the server, if any. */ + readonly extensions: string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare 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 */ +/** ISO 3166-1 Alpha-2 codes */ +declare 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"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +declare interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params<P extends string = any> = Record<P, string | string[]>; +declare type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +declare type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +declare type 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>; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +declare type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2021-11-03/index.ts b/node_modules/@cloudflare/workers-types/2021-11-03/index.ts new file mode 100755 index 0000000..c8f7d7a --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2021-11-03/index.ts @@ -0,0 +1,3293 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +export declare function btoa(data: string): string; +export declare function atob(data: string): string; +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearTimeout(timeoutId: number | null): void; +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearInterval(timeoutId: number | null): void; +export declare function queueMicrotask(task: Function): void; +export declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +export declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +export type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +export interface Performance { + readonly timeOrigin: number; + now(): number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +export interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +export interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +export interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. */ + readonly eventPhase: number; + /** Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. */ + readonly composed: boolean; + /** Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. */ + readonly bubbles: boolean; + /** Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. */ + readonly cancelable: boolean; + /** Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. */ + readonly defaultPrevented: boolean; + /** @deprecated */ + readonly returnValue: boolean; + /** Returns the object whose event listener's callback is currently being invoked. */ + readonly currentTarget?: EventTarget; + /** @deprecated */ + readonly srcElement?: EventTarget; + /** Returns the event's timestamp as the number of milliseconds measured relative to the time origin. */ + readonly timeStamp: number; + /** Returns true if event was dispatched by the user agent, and false otherwise. */ + readonly isTrusted: boolean; + cancelBubble: boolean; + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +export interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +export declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** Returns the AbortSignal object associated with this object. */ + readonly signal: AbortSignal; + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. */ + readonly aborted: boolean; + readonly reason: any; + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + readonly size: number; + readonly type: string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + readonly name: string; + readonly lastModified: number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** Available only in secure contexts. */ + readonly subtle: SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +export declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise<ArrayBuffer>; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; +} +export declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + readonly encoding: string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + readonly status: number; + readonly statusText: string; + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly url: string; + readonly webSocket: WebSocket | null; + readonly cf?: any; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + /** Returns request's HTTP method, which is "GET" by default. */ + readonly method: string; + /** Returns the URL of request as a string. */ + readonly url: string; + /** Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. */ + readonly headers: Headers; + /** Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. */ + readonly redirect: string; + readonly fetcher: Fetcher | null; + /** Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. */ + readonly signal: AbortSignal; + readonly cf?: Cf; + /** Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] */ + readonly integrity: string; + /** Returns a boolean indicating whether or not request can outlive the global in which it was created. */ + readonly keepalive: boolean; +} +export interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +export interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +export interface QueueSendOptions { + contentType?: QueueContentType; +} +export interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +export interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +export interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +export declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +export interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +export interface ReadableStream<R = any> { + readonly locked: boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +export declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + readonly closed: Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + readonly closed: Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +export interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +export interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +export interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +export interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +export interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +export interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +export interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +export declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + readonly locked: boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +export declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + readonly closed: Promise<void>; + readonly ready: Promise<void>; + readonly desiredSize: number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +export declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + readonly readable: ReadableStream<O>; + readonly writable: WritableStream<I>; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + href: string; + readonly origin: string; + protocol: string; + username: string; + password: string; + host: string; + hostname: string; + port: string; + pathname: string; + search: string; + readonly searchParams: URLSearchParams; + hash: string; + toString(): string; + toJSON(): string; +} +export declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record<string, string> + | [key: string, value: string][] + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +export interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + /** Returns the state of the WebSocket object's connection. It can have the values described below. */ + readonly readyState: number; + /** Returns the URL that was used to establish the WebSocket connection. */ + readonly url: string | null; + /** Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. */ + readonly protocol: string | null; + /** Returns the extensions selected by the server, if any. */ + readonly extensions: string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export 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 */ +/** ISO 3166-1 Alpha-2 codes */ +export 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"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +export interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params<P extends string = any> = Record<P, string | string[]>; +export type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +export type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +export type 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>; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +export type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-01-31/index.d.ts b/node_modules/@cloudflare/workers-types/2022-01-31/index.d.ts new file mode 100755 index 0000000..b489144 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-01-31/index.d.ts @@ -0,0 +1,3291 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +declare function btoa(data: string): string; +declare function atob(data: string): string; +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearTimeout(timeoutId: number | null): void; +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearInterval(timeoutId: number | null): void; +declare function queueMicrotask(task: Function): void; +declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +declare type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +declare interface Performance { + readonly timeOrigin: number; + now(): number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +declare interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +declare interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +declare interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +declare interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +declare interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +declare interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; +} +declare interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +declare interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +declare interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +declare interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +declare interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +declare interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +declare interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +declare interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +declare interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +declare interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +declare interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +declare interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream<string, Uint8Array> { + constructor(); +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + get href(): string; + set href(value: string); + get origin(): string; + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get searchParams(): URLSearchParams; + get hash(): string; + set hash(value: string); + toString(): string; + toJSON(): string; +} +declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record<string, string> + | [key: string, value: string][] + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +declare interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare 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 */ +/** ISO 3166-1 Alpha-2 codes */ +declare 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"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +declare interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params<P extends string = any> = Record<P, string | string[]>; +declare type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +declare type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +declare type 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>; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +declare type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-01-31/index.ts b/node_modules/@cloudflare/workers-types/2022-01-31/index.ts new file mode 100755 index 0000000..4945a34 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-01-31/index.ts @@ -0,0 +1,3279 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +export declare function btoa(data: string): string; +export declare function atob(data: string): string; +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearTimeout(timeoutId: number | null): void; +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearInterval(timeoutId: number | null): void; +export declare function queueMicrotask(task: Function): void; +export declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +export declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +export type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +export interface Performance { + readonly timeOrigin: number; + now(): number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +export interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +export interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +export interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +export interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +export declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +export declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +export interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +export interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +export interface QueueSendOptions { + contentType?: QueueContentType; +} +export interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +export interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +export interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +export declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +export interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +export interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +export declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +export interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +export interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +export interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +export interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +export interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +export interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +export interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +export declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +export declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +export declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + get href(): string; + set href(value: string); + get origin(): string; + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get searchParams(): URLSearchParams; + get hash(): string; + set hash(value: string); + toString(): string; + toJSON(): string; +} +export declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record<string, string> + | [key: string, value: string][] + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +export interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export 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 */ +/** ISO 3166-1 Alpha-2 codes */ +export 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"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +export interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params<P extends string = any> = Record<P, string | string[]>; +export type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +export type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +export type 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>; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +export type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-03-21/index.d.ts b/node_modules/@cloudflare/workers-types/2022-03-21/index.d.ts new file mode 100755 index 0000000..c5ef6b7 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-03-21/index.d.ts @@ -0,0 +1,3297 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +declare function btoa(data: string): string; +declare function atob(data: string): string; +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearTimeout(timeoutId: number | null): void; +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearInterval(timeoutId: number | null): void; +declare function queueMicrotask(task: Function): void; +declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +declare type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +declare interface Performance { + readonly timeOrigin: number; + now(): number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +declare interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +declare interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +declare interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +declare interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +declare interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +declare interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; +} +declare interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +declare interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +declare interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +declare interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +declare interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +declare interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +declare interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +declare interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +declare interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +declare interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +declare interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +declare interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream<string, Uint8Array> { + constructor(); +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + get href(): string; + set href(value: string); + get origin(): string; + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get searchParams(): URLSearchParams; + get hash(): string; + set hash(value: string); + toString(): string; + toJSON(): string; +} +declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record<string, string> + | [key: string, value: string][] + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +declare interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare 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 */ +/** ISO 3166-1 Alpha-2 codes */ +declare 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"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +declare interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params<P extends string = any> = Record<P, string | string[]>; +declare type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +declare type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +declare type 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>; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +declare type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-03-21/index.ts b/node_modules/@cloudflare/workers-types/2022-03-21/index.ts new file mode 100755 index 0000000..210b2e4 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-03-21/index.ts @@ -0,0 +1,3285 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +export declare function btoa(data: string): string; +export declare function atob(data: string): string; +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearTimeout(timeoutId: number | null): void; +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearInterval(timeoutId: number | null): void; +export declare function queueMicrotask(task: Function): void; +export declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +export declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +export type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +export declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +export interface Performance { + readonly timeOrigin: number; + now(): number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +export interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +export interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +export interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +export interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +export declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +export declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +export interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +export interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +export interface QueueSendOptions { + contentType?: QueueContentType; +} +export interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +export interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +export interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +export declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +export interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +export interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +export declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +export interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +export interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +export interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +export interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +export interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +export interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +export interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +export declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +export declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +export declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + get href(): string; + set href(value: string); + get origin(): string; + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get searchParams(): URLSearchParams; + get hash(): string; + set hash(value: string); + toString(): string; + toJSON(): string; +} +export declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record<string, string> + | [key: string, value: string][] + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +export interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export 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 */ +/** ISO 3166-1 Alpha-2 codes */ +export 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"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +export interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params<P extends string = any> = Record<P, string | string[]>; +export type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +export type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +export type 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>; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +export type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-08-04/index.d.ts b/node_modules/@cloudflare/workers-types/2022-08-04/index.d.ts new file mode 100755 index 0000000..7f60383 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-08-04/index.d.ts @@ -0,0 +1,3298 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +declare function btoa(data: string): string; +declare function atob(data: string): string; +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearTimeout(timeoutId: number | null): void; +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearInterval(timeoutId: number | null): void; +declare function queueMicrotask(task: Function): void; +declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +declare type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +declare interface Performance { + readonly timeOrigin: number; + now(): number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +declare interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +declare interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +declare interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +declare interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +declare interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +declare interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; +} +declare interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +declare interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +declare interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +declare interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +declare interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +declare interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +declare interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +declare interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +declare interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +declare interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +declare interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +declare interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream<string, Uint8Array> { + constructor(); +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + get href(): string; + set href(value: string); + get origin(): string; + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get searchParams(): URLSearchParams; + get hash(): string; + set hash(value: string); + toString(): string; + toJSON(): string; +} +declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record<string, string> + | [key: string, value: string][] + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +declare interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare 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 */ +/** ISO 3166-1 Alpha-2 codes */ +declare 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"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +declare interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params<P extends string = any> = Record<P, string | string[]>; +declare type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +declare type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +declare type 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>; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +declare type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-08-04/index.ts b/node_modules/@cloudflare/workers-types/2022-08-04/index.ts new file mode 100755 index 0000000..ee1ac9d --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-08-04/index.ts @@ -0,0 +1,3286 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +export declare function btoa(data: string): string; +export declare function atob(data: string): string; +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearTimeout(timeoutId: number | null): void; +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearInterval(timeoutId: number | null): void; +export declare function queueMicrotask(task: Function): void; +export declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +export declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +export type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +export declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +export interface Performance { + readonly timeOrigin: number; + now(): number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +export interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +export interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +export interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +export interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +export declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +export declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +export interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +export interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +export interface QueueSendOptions { + contentType?: QueueContentType; +} +export interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +export interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +export interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +export declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +export interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +export interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +export declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +export interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +export interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +export interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +export interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +export interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +export interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +export interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +export declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +export declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +export declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + get href(): string; + set href(value: string); + get origin(): string; + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get searchParams(): URLSearchParams; + get hash(): string; + set hash(value: string); + toString(): string; + toJSON(): string; +} +export declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record<string, string> + | [key: string, value: string][] + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +export interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export 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 */ +/** ISO 3166-1 Alpha-2 codes */ +export 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"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +export interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params<P extends string = any> = Record<P, string | string[]>; +export type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +export type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +export type 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>; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +export type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-10-31/index.d.ts b/node_modules/@cloudflare/workers-types/2022-10-31/index.d.ts new file mode 100755 index 0000000..680dfb8 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-10-31/index.d.ts @@ -0,0 +1,3295 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +declare function btoa(data: string): string; +declare function atob(data: string): string; +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearTimeout(timeoutId: number | null): void; +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearInterval(timeoutId: number | null): void; +declare function queueMicrotask(task: Function): void; +declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +declare type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +declare interface Performance { + readonly timeOrigin: number; + now(): number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +declare interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +declare interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +declare interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +declare interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +declare interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +declare interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; +} +declare interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +declare interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +declare interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +declare interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +declare interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +declare interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +declare interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +declare interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +declare interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +declare interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +declare interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +declare interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream<string, Uint8Array> { + constructor(); +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + get origin(): string; + get href(): string; + set href(value: string); + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get hash(): string; + set hash(value: string); + get searchParams(): URLSearchParams; + toJSON(): string; + toString(): string; + static canParse(url: string, base?: string): boolean; +} +declare class URLSearchParams { + constructor( + init?: Iterable<Iterable<string>> | Record<string, string> | string + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +declare interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare 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 */ +/** ISO 3166-1 Alpha-2 codes */ +declare 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"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +declare interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params<P extends string = any> = Record<P, string | string[]>; +declare type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +declare type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +declare type 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>; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +declare type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-10-31/index.ts b/node_modules/@cloudflare/workers-types/2022-10-31/index.ts new file mode 100755 index 0000000..9212375 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-10-31/index.ts @@ -0,0 +1,3283 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +export declare function btoa(data: string): string; +export declare function atob(data: string): string; +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearTimeout(timeoutId: number | null): void; +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearInterval(timeoutId: number | null): void; +export declare function queueMicrotask(task: Function): void; +export declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +export declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +export type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +export declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +export interface Performance { + readonly timeOrigin: number; + now(): number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +export interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +export interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +export interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +export interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +export declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +export declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +export interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +export interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +export interface QueueSendOptions { + contentType?: QueueContentType; +} +export interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +export interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +export interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +export declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +export interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +export interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +export declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +export interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +export interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +export interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +export interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +export interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +export interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +export interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +export declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +export declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +export declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + get origin(): string; + get href(): string; + set href(value: string); + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get hash(): string; + set hash(value: string); + get searchParams(): URLSearchParams; + toJSON(): string; + toString(): string; + static canParse(url: string, base?: string): boolean; +} +export declare class URLSearchParams { + constructor( + init?: Iterable<Iterable<string>> | Record<string, string> | string + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +export interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export 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 */ +/** ISO 3166-1 Alpha-2 codes */ +export 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"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +export interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params<P extends string = any> = Record<P, string | string[]>; +export type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +export type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +export type 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>; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +export type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-11-30/index.d.ts b/node_modules/@cloudflare/workers-types/2022-11-30/index.d.ts new file mode 100755 index 0000000..8c854a1 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-11-30/index.d.ts @@ -0,0 +1,3298 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +declare function btoa(data: string): string; +declare function atob(data: string): string; +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearTimeout(timeoutId: number | null): void; +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearInterval(timeoutId: number | null): void; +declare function queueMicrotask(task: Function): void; +declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +declare type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +declare interface Performance { + readonly timeOrigin: number; + now(): number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +declare interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +declare interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +declare interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +declare interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +declare interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +declare interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; +} +declare interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +declare interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +declare interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +declare interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +declare interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +declare interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +declare abstract class ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +declare abstract class ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +declare abstract class ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +declare abstract class WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +declare interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +declare interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream<string, Uint8Array> { + constructor(); +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + get origin(): string; + get href(): string; + set href(value: string); + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get hash(): string; + set hash(value: string); + get searchParams(): URLSearchParams; + toJSON(): string; + toString(): string; + static canParse(url: string, base?: string): boolean; +} +declare class URLSearchParams { + constructor( + init?: Iterable<Iterable<string>> | Record<string, string> | string + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +declare interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare 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 */ +/** ISO 3166-1 Alpha-2 codes */ +declare 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"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +declare interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params<P extends string = any> = Record<P, string | string[]>; +declare type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +declare type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +declare type 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>; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +declare type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2022-11-30/index.ts b/node_modules/@cloudflare/workers-types/2022-11-30/index.ts new file mode 100755 index 0000000..94d705c --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2022-11-30/index.ts @@ -0,0 +1,3286 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +export declare function btoa(data: string): string; +export declare function atob(data: string): string; +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearTimeout(timeoutId: number | null): void; +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearInterval(timeoutId: number | null): void; +export declare function queueMicrotask(task: Function): void; +export declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +export declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +export type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +export declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +export interface Performance { + readonly timeOrigin: number; + now(): number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +export interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +export interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +export interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +export interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +export declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +export declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +export interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +export interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +export interface QueueSendOptions { + contentType?: QueueContentType; +} +export interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +export interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +export interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +export declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +export interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +export interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +export declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +export interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +export declare abstract class ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +export declare abstract class ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +export declare abstract class ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +export declare abstract class WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +export interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +export interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +export declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +export declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +export declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + get origin(): string; + get href(): string; + set href(value: string); + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get hash(): string; + set hash(value: string); + get searchParams(): URLSearchParams; + toJSON(): string; + toString(): string; + static canParse(url: string, base?: string): boolean; +} +export declare class URLSearchParams { + constructor( + init?: Iterable<Iterable<string>> | Record<string, string> | string + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +export interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export 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 */ +/** ISO 3166-1 Alpha-2 codes */ +export 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"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +export interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params<P extends string = any> = Record<P, string | string[]>; +export type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +export type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +export type 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>; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +export type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2023-03-01/index.d.ts b/node_modules/@cloudflare/workers-types/2023-03-01/index.d.ts new file mode 100755 index 0000000..a16b91a --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2023-03-01/index.d.ts @@ -0,0 +1,3299 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +declare function btoa(data: string): string; +declare function atob(data: string): string; +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearTimeout(timeoutId: number | null): void; +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearInterval(timeoutId: number | null): void; +declare function queueMicrotask(task: Function): void; +declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +declare type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +declare interface Performance { + readonly timeOrigin: number; + now(): number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +declare interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +declare interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +declare interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +declare interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + getSetCookie(): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +declare interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +declare interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; +} +declare interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +declare interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +declare interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +declare interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +declare interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +declare interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +declare abstract class ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +declare abstract class ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +declare abstract class ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +declare abstract class WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +declare interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +declare interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream<string, Uint8Array> { + constructor(); +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + get origin(): string; + get href(): string; + set href(value: string); + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get hash(): string; + set hash(value: string); + get searchParams(): URLSearchParams; + toJSON(): string; + toString(): string; + static canParse(url: string, base?: string): boolean; +} +declare class URLSearchParams { + constructor( + init?: Iterable<Iterable<string>> | Record<string, string> | string + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +declare interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare 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 */ +/** ISO 3166-1 Alpha-2 codes */ +declare 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"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +declare interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params<P extends string = any> = Record<P, string | string[]>; +declare type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +declare type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +declare type 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>; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +declare type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2023-03-01/index.ts b/node_modules/@cloudflare/workers-types/2023-03-01/index.ts new file mode 100755 index 0000000..9c6b736 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2023-03-01/index.ts @@ -0,0 +1,3287 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +export declare function btoa(data: string): string; +export declare function atob(data: string): string; +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearTimeout(timeoutId: number | null): void; +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearInterval(timeoutId: number | null): void; +export declare function queueMicrotask(task: Function): void; +export declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +export declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +export type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +export declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +export interface Performance { + readonly timeOrigin: number; + now(): number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +export interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +export interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +export interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +export interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +export declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +export declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + getSetCookie(): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +export interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +export interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +export interface QueueSendOptions { + contentType?: QueueContentType; +} +export interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +export interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +export interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +export declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +export interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +export interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +export declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +export interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +export declare abstract class ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +export declare abstract class ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +export declare abstract class ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +export declare abstract class WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +export interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +export interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +export declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +export declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +export declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + get origin(): string; + get href(): string; + set href(value: string); + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get hash(): string; + set hash(value: string); + get searchParams(): URLSearchParams; + toJSON(): string; + toString(): string; + static canParse(url: string, base?: string): boolean; +} +export declare class URLSearchParams { + constructor( + init?: Iterable<Iterable<string>> | Record<string, string> | string + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +export interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export 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 */ +/** ISO 3166-1 Alpha-2 codes */ +export 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"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +export interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params<P extends string = any> = Record<P, string | string[]>; +export type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +export type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +export type 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>; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +export type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2023-07-01/index.d.ts b/node_modules/@cloudflare/workers-types/2023-07-01/index.d.ts new file mode 100755 index 0000000..0f14b53 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2023-07-01/index.d.ts @@ -0,0 +1,3299 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +declare function btoa(data: string): string; +declare function atob(data: string): string; +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearTimeout(timeoutId: number | null): void; +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearInterval(timeoutId: number | null): void; +declare function queueMicrotask(task: Function): void; +declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +declare type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +declare interface Performance { + readonly timeOrigin: number; + now(): number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +declare interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +declare interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +declare interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +declare interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + getSetCookie(): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +declare interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +declare interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; +} +declare interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +declare interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +declare interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +declare interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +declare interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +declare interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +declare abstract class ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +declare abstract class ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +declare abstract class ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +declare abstract class WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +declare interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +declare interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream<string, Uint8Array> { + constructor(); +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + get origin(): string; + get href(): string; + set href(value: string); + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get hash(): string; + set hash(value: string); + get searchParams(): URLSearchParams; + toJSON(): string; + toString(): string; + static canParse(url: string, base?: string): boolean; +} +declare class URLSearchParams { + constructor( + init?: Iterable<Iterable<string>> | Record<string, string> | string + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string, value?: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string, value?: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +declare interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare 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 */ +/** ISO 3166-1 Alpha-2 codes */ +declare 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"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +declare interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params<P extends string = any> = Record<P, string | string[]>; +declare type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +declare type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +declare type 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>; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +declare type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/2023-07-01/index.ts b/node_modules/@cloudflare/workers-types/2023-07-01/index.ts new file mode 100755 index 0000000..844b74e --- /dev/null +++ b/node_modules/@cloudflare/workers-types/2023-07-01/index.ts @@ -0,0 +1,3287 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +export declare function btoa(data: string): string; +export declare function atob(data: string): string; +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearTimeout(timeoutId: number | null): void; +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearInterval(timeoutId: number | null): void; +export declare function queueMicrotask(task: Function): void; +export declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +export declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +export type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +export declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +export interface Performance { + readonly timeOrigin: number; + now(): number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +export interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +export interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +export interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +export interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +export declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +export declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + getSetCookie(): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +export interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +export interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +export interface QueueSendOptions { + contentType?: QueueContentType; +} +export interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +export interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +export interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +export declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +export interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +export interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +export declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +export interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +export declare abstract class ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +export declare abstract class ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +export declare abstract class ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +export declare abstract class WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +export interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +export interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +export declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +export declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +export declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + get origin(): string; + get href(): string; + set href(value: string); + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get hash(): string; + set hash(value: string); + get searchParams(): URLSearchParams; + toJSON(): string; + toString(): string; + static canParse(url: string, base?: string): boolean; +} +export declare class URLSearchParams { + constructor( + init?: Iterable<Iterable<string>> | Record<string, string> | string + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string, value?: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string, value?: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +export interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export 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 */ +/** ISO 3166-1 Alpha-2 codes */ +export 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"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +export interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params<P extends string = any> = Record<P, string | string[]>; +export type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +export type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +export type 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>; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +export type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/README.md b/node_modules/@cloudflare/workers-types/README.md new file mode 100644 index 0000000..3945d8e --- /dev/null +++ b/node_modules/@cloudflare/workers-types/README.md @@ -0,0 +1,131 @@ +# Cloudflare Workers Types + +> :warning: If you're upgrading from version 2, make sure to remove `webworker` from the `lib` array in your +> `tsconfig.json`. These types are now included in `@cloudflare/workers-types`. + +## Install + +```bash +npm install -D @cloudflare/workers-types +-- Or +yarn add -D @cloudflare/workers-types +``` + +## Usage + +The following is a minimal `tsconfig.json` for use alongside this package: + +**`tsconfig.json`** + +```json +{ + "compilerOptions": { + "target": "esnext", + "module": "esnext", + "lib": ["esnext"], + "types": ["@cloudflare/workers-types"] + } +} +``` + +### Compatibility dates + + + +The Cloudflare Workers runtime manages backwards compatibility through the use of [Compatibility Dates](https://developers.cloudflare.com/workers/platform/compatibility-dates/). Using different compatibility dates affects the runtime types available to your Worker, and so it's important you specify the correct entrypoint to the `workers-types` package to match your compatibility date (which is usually set in your `wrangler.toml` configuration file). `workers-types` currently exposes the following entrypoints to choose from: + +- `@cloudflare/workers-types` + + The default entrypoint exposes the runtime types for a compatibility date before `2021-11-03`. + +- `@cloudflare/workers-types/2021-11-03` + + This entrypoint exposes the runtime types for a compatibility date between `2021-11-03` and `2022-01-31`. + +- `@cloudflare/workers-types/2022-01-31` + + This entrypoint exposes the runtime types for a compatibility date between `2022-01-31` and `2022-03-21`. + +- `@cloudflare/workers-types/2022-03-21` + + This entrypoint exposes the runtime types for a compatibility date between `2022-03-21` and `2022-08-04`. + +- `@cloudflare/workers-types/2022-08-04` + + This entrypoint exposes the runtime types for a compatibility date between `2022-08-04` and `2022-10-31`. + +- `@cloudflare/workers-types/2022-10-31` + + This entrypoint exposes the runtime types for a compatibility date between `2022-10-31` and `2022-11-30`. + +- `@cloudflare/workers-types/2022-11-30` + + This entrypoint exposes the runtime types for a compatibility date between `2022-11-30` and `2023-03-01`. + +- `@cloudflare/workers-types/2023-03-01` + + This entrypoint exposes the runtime types for a compatibility date between `2023-03-01` and `2023-07-01`. + +- `@cloudflare/workers-types/2023-07-01` + + This entrypoint exposes the runtime types for a compatibility date after `2023-07-01`. + +- `@cloudflare/workers-types/experimental` + + This entrypoint exposes the runtime types for the latest compatibility date. The types exposed by this entrypoint will change over time to always reflect the latest version of the Workers runtime. + +To use one of these entrypoints, you need to specify them in your `tsconfig.json`. For example, this is a sample `tsconfig.json` for using the `2022-08-04` entrypoint. + +```json +{ + "compilerOptions": { + "target": "esnext", + "module": "esnext", + "lib": ["esnext"], + "types": ["@cloudflare/workers-types/2022-08-04"] + } +} +``` + +### Importable Types + +It's not always possible (or desirable) to modify the `tsconfig.json` settings for a project to include all the Cloudflare Workers types. For use cases like that, this package provides importable versions of its types, which are usable with no additional `tsconfig.json` setup. For example: + +```ts +import type { Request as WorkerRequest, ExecutionContext } from "@cloudflare/workers-types/experimental" + +export default { + fetch(request: WorkerRequest, env: unknown, ctx: ExecutionContext) { + return new Response("OK") + } +} +``` + + +### Using bindings + +It's recommended that you create a type file for any bindings your Worker uses. Create a file named +`worker-configuration.d.ts` in your src directory. + +If you're using Module Workers, it should look like this: +```typescript +// worker-configuration.d.ts +interface Env { + MY_ENV_VAR: string; + MY_SECRET: string; + myKVNamespace: KVNamespace; +} +``` +For Service Workers, it should augment the global scope: +```typescript +// worker-configuration.d.ts +declare global { + const MY_ENV_VAR: string; + const MY_SECRET: string; + const myKVNamespace: KVNamespace; +} +export {} +``` + +Wrangler can also generate this for you automatically from your `wrangler.toml` configuration file, using the `wrangler types` command. + diff --git a/node_modules/@cloudflare/workers-types/entrypoints.svg b/node_modules/@cloudflare/workers-types/entrypoints.svg new file mode 100644 index 0000000..057a152 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/entrypoints.svg @@ -0,0 +1,53 @@ +<?xml version="1.0" encoding="utf-8"?> +<svg viewBox="0 0 540 280" width="540px" height="280px" xmlns="http://www.w3.org/2000/svg"> + <rect width="540" height="280" style="fill: rgb(255, 255, 255);"/> + <g transform="matrix(1, 0, 0, 1, 61.018997, -319.418854)"> + <rect x="128.981" y="349.42" width="340" height="30" style="fill: rgb(238, 238, 238);"/> + <text style="font-family: monospace; font-size: 14px; white-space: pre;" x="135.709" y="369.298">@cloudflare/workers-types</text> + </g> + <g transform="matrix(1, 0, 0, 1, 61.018997, -289.418793)"> + <rect x="128.981" y="349.42" width="340" height="30" style="fill: rgb(221, 221, 221);"/> + <text style="font-family: monospace; font-size: 14px; white-space: pre;"><tspan x="135.709" y="369.298">@cloudflare/workers-types/</tspan><tspan style="fill: rgb(0, 85, 220); font-weight: 700;">2021-11-03</tspan></text> + </g> + <g transform="matrix(1, 0, 0, 1, 61.018997, -259.418793)"> + <rect x="128.981" y="349.42" width="340" height="30" style="fill: rgb(238, 238, 238);"/> + <text style="font-family: monospace; font-size: 14px; white-space: pre;"><tspan x="135.709" y="369.298">@cloudflare/workers-types/</tspan><tspan style="fill: rgb(0, 54, 130); font-weight: 700;">2022-01-31</tspan></text> + </g> + <g transform="matrix(1, 0, 0, 1, 61.018997, -229.418869)"> + <rect x="128.981" y="349.42" width="340" height="30" style="fill: rgb(221, 221, 221);"/> + <text style="font-family: monospace; font-size: 14px; white-space: pre;"><tspan x="135.709" y="369.298">@cloudflare/workers-types/</tspan><tspan style="fill: rgb(0, 85, 220); font-weight: 700;">2022-03-21</tspan></text> + </g> + <g transform="matrix(1, 0, 0, 1, 61.018997, -199.418839)"> + <rect x="128.981" y="349.42" width="340" height="30" style="fill: rgb(238, 238, 238);"/> + <text style="font-family: monospace; font-size: 14px; white-space: pre;"><tspan x="135.709" y="369.298">@cloudflare/workers-types/</tspan><tspan style="fill: rgb(0, 54, 130); font-weight: 700;">2022-08-04</tspan></text> + </g> + <g transform="matrix(1, 0, 0, 1, 61.018997, -169.418839)"> + <rect x="128.981" y="349.42" width="340" height="30" style="fill: rgb(221, 221, 221);"/> + <text style="font-family: monospace; font-size: 14px; white-space: pre;"><tspan x="135.709" y="369.298">@cloudflare/workers-types/</tspan><tspan style="fill: rgb(0, 85, 220); font-weight: 700;">2022-10-31</tspan></text> + </g> + <g transform="matrix(1, 0, 0, 1, 61.017925, -139.418854)"> + <rect x="128.981" y="349.42" width="340" height="30" style="fill: rgb(238, 238, 238);"/> + <text style="font-family: monospace; font-size: 14px; white-space: pre;"><tspan x="135.709" y="369.298">@cloudflare/workers-types/</tspan><tspan style="fill: rgb(0, 54, 130); font-weight: 700;">2022-11-30</tspan></text> + </g> + <g transform="matrix(1, 0, 0, 1, 61.017925, -109.418816)"> + <rect x="128.981" y="349.42" width="340" height="30" style="fill: rgb(221, 221, 221);"/> + <text style="font-family: monospace; font-size: 14px; white-space: pre;" x="135.709" y="369.298">@cloudflare/workers-types/experimental</text> + </g> + <line style="fill: rgb(216, 216, 216); stroke: rgb(0, 0, 0);" x1="160" y1="60" x2="190" y2="60"/> + <line style="fill: rgb(216, 216, 216); stroke: rgb(0, 0, 0);" x1="160" y1="90" x2="190" y2="90"/> + <line style="fill: rgb(216, 216, 216); stroke: rgb(0, 0, 0);" x1="160" y1="120" x2="190" y2="120"/> + <line style="fill: rgb(216, 216, 216); stroke: rgb(0, 0, 0);" x1="160" y1="150" x2="190" y2="150"/> + <line style="fill: rgb(216, 216, 216); stroke: rgb(0, 0, 0);" x1="160" y1="180" x2="190" y2="180"/> + <line style="fill: rgb(216, 216, 216); stroke: rgb(0, 0, 0);" x1="160" y1="210" x2="190" y2="210"/> + <line style="fill: rgb(216, 216, 216); stroke: rgb(0, 0, 0);" x1="175" y1="60" x2="175" y2="240"/> + <line style="fill: rgb(216, 216, 216); stroke: rgb(0, 0, 0); stroke-dasharray: 2px;" x1="175" y1="30" x2="175" y2="60"/> + <line style="fill: rgb(216, 216, 216); stroke: rgb(0, 0, 0); stroke-dasharray: 2px;" x1="175" y1="240" x2="175" y2="270"/> + <text style="fill: rgb(51, 51, 51); font-family: monospace; font-size: 14px; font-weight: 700; text-anchor: middle; white-space: pre;" transform="matrix(1, 0, 0, 1, 307.347992, -77.253761)"><tspan x="52.652" y="98.052">types Entrypoint</tspan></text> + <text style="fill: rgb(51, 51, 51); font-family: monospace; font-size: 14px; font-weight: 700; text-anchor: end; white-space: pre;" x="157.185" y="20.798">compatibility_date</text> + <text style="fill: rgb(0, 85, 220); font-family: monospace; font-size: 14px; font-weight: 700; text-anchor: end; white-space: pre;" x="153.994" y="64.798">2021-11-03</text> + <text style="fill: rgb(0, 54, 130); font-family: monospace; font-size: 14px; font-weight: 700; text-anchor: end; white-space: pre;" x="153.994" y="94.798">2022-01-31</text> + <text style="fill: rgb(0, 85, 220); font-family: monospace; font-size: 14px; font-weight: 700; text-anchor: end; white-space: pre;" x="153.994" y="124.798">2022-03-21</text> + <text style="fill: rgb(0, 54, 130); font-family: monospace; font-size: 14px; font-weight: 700; text-anchor: end; white-space: pre;" x="153.994" y="154.798">2022-08-04</text> + <text style="fill: rgb(0, 85, 220); font-family: monospace; font-size: 14px; font-weight: 700; text-anchor: end; white-space: pre;" x="153.994" y="184.798">2022-10-31</text> + <text style="fill: rgb(0, 54, 130); font-family: monospace; font-size: 14px; font-weight: 700; text-anchor: end; white-space: pre;" x="153.994" y="214.798">2022-11-30</text> +</svg> diff --git a/node_modules/@cloudflare/workers-types/experimental/index.d.ts b/node_modules/@cloudflare/workers-types/experimental/index.d.ts new file mode 100755 index 0000000..bd7d9ef --- /dev/null +++ b/node_modules/@cloudflare/workers-types/experimental/index.d.ts @@ -0,0 +1,3356 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +declare function btoa(data: string): string; +declare function atob(data: string): string; +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearTimeout(timeoutId: number | null): void; +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearInterval(timeoutId: number | null): void; +declare function queueMicrotask(task: Function): void; +declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare const navigator: Navigator; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +declare type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +declare interface Performance { + readonly timeOrigin: number; + now(): number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +declare interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + getExisting( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + abort(reason?: string): void; +} +declare interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +declare interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + sql: SqlStorage; + transactionSync<T>(closure: () => T): T; + getCurrentBookmark(): Promise<string>; + getBookmarkForTime(timestamp: number | Date): Promise<string>; + onNextSessionRestoreBookmark(bookmark: string): Promise<string>; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +declare interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + getSetCookie(): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +declare interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; + queue( + queueName: string, + messages: ServiceBindingQueueMessage[] + ): Promise<FetcherQueueResult>; + scheduled(options?: FetcherScheduledOptions): Promise<FetcherScheduledResult>; +} +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface FetcherScheduledOptions { + scheduledTime?: Date; + cron?: string; +} +declare interface FetcherScheduledResult { + outcome: string; + noRetry: boolean; +} +declare interface FetcherQueueResult { + outcome: string; + retryAll: boolean; + ackAll: boolean; + explicitRetries: string[]; + explicitAcks: string[]; +} +declare type ServiceBindingQueueMessage<Body = unknown> = { + id: string; + timestamp: Date; +} & ( + | { + body: Body; + } + | { + serializedBody: ArrayBuffer | ArrayBufferView; + } +); +declare interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +declare interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; +} +declare interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +declare interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +declare interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +declare interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +declare interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +declare interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +declare abstract class ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +declare abstract class ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +declare abstract class ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +declare abstract class WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +declare interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +declare interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream<string, Uint8Array> { + constructor(); +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + get origin(): string; + get href(): string; + set href(value: string); + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get hash(): string; + set hash(value: string); + get searchParams(): URLSearchParams; + toJSON(): string; + toString(): string; + static canParse(url: string, base?: string): boolean; +} +declare class URLSearchParams { + constructor( + init?: Iterable<Iterable<string>> | Record<string, string> | string + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string, value?: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string, value?: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +declare interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface SqlStorage { + exec(query: string, ...bindings: any[]): SqlStorageCursor; + prepare(query: string): SqlStorageStatement; + get databaseSize(): number; + Cursor: typeof SqlStorageCursor; + Statement: typeof SqlStorageStatement; +} +declare abstract class SqlStorageStatement {} +declare abstract class SqlStorageCursor { + raw(): IterableIterator<((ArrayBuffer | string | number) | null)[]>; + get columnNames(): string[]; + get rowsRead(): number; + get rowsWritten(): number; + [Symbol.iterator](): IterableIterator< + Record<string, (ArrayBuffer | string | number) | null> + >; +} +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare 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 */ +/** ISO 3166-1 Alpha-2 codes */ +declare 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"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +declare interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params<P extends string = any> = Record<P, string | string[]>; +declare type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +declare type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +declare type 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>; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +declare type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/experimental/index.ts b/node_modules/@cloudflare/workers-types/experimental/index.ts new file mode 100755 index 0000000..bb551ca --- /dev/null +++ b/node_modules/@cloudflare/workers-types/experimental/index.ts @@ -0,0 +1,3344 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +export declare function btoa(data: string): string; +export declare function atob(data: string): string; +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearTimeout(timeoutId: number | null): void; +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearInterval(timeoutId: number | null): void; +export declare function queueMicrotask(task: Function): void; +export declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +export declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export declare const navigator: Navigator; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +export type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +export declare abstract class Navigator { + readonly userAgent: string; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +export interface Performance { + readonly timeOrigin: number; + now(): number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +export interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + getExisting( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + abort(reason?: string): void; +} +export interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +export interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + sql: SqlStorage; + transactionSync<T>(closure: () => T): T; + getCurrentBookmark(): Promise<string>; + getBookmarkForTime(timestamp: number | Date): Promise<string>; + onNextSessionRestoreBookmark(bookmark: string): Promise<string>; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + get type(): string; + get eventPhase(): number; + get composed(): boolean; + get bubbles(): boolean; + get cancelable(): boolean; + get defaultPrevented(): boolean; + get returnValue(): boolean; + get currentTarget(): EventTarget | undefined; + get srcElement(): EventTarget | undefined; + get timeStamp(): number; + get isTrusted(): boolean; + get cancelBubble(): boolean; + set cancelBubble(value: boolean); + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +export interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +export declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + get signal(): AbortSignal; + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + get aborted(): boolean; + get reason(): any; + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + get size(): number; + get type(): string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + get name(): string; + get lastModified(): number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + get subtle(): SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +export declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + get digest(): Promise<ArrayBuffer>; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +export declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + get encoding(): string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): (File | string) | null; + getAll(name: string): (File | string)[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: File | string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + getSetCookie(): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + get body(): ReadableStream | null; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + get status(): number; + get statusText(): string; + get headers(): Headers; + get ok(): boolean; + get redirected(): boolean; + get url(): string; + get webSocket(): WebSocket | null; + get cf(): any | undefined; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + get method(): string; + get url(): string; + get headers(): Headers; + get redirect(): string; + get fetcher(): Fetcher | null; + get signal(): AbortSignal; + get cf(): Cf | undefined; + get integrity(): string; + get keepalive(): boolean; +} +export interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; + queue( + queueName: string, + messages: ServiceBindingQueueMessage[] + ): Promise<FetcherQueueResult>; + scheduled(options?: FetcherScheduledOptions): Promise<FetcherScheduledResult>; +} +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface FetcherScheduledOptions { + scheduledTime?: Date; + cron?: string; +} +export interface FetcherScheduledResult { + outcome: string; + noRetry: boolean; +} +export interface FetcherQueueResult { + outcome: string; + retryAll: boolean; + ackAll: boolean; + explicitRetries: string[]; + explicitAcks: string[]; +} +export type ServiceBindingQueueMessage<Body = unknown> = { + id: string; + timestamp: Date; +} & ( + | { + body: Body; + } + | { + serializedBody: ArrayBuffer | ArrayBufferView; + } +); +export interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +export interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +export interface QueueSendOptions { + contentType?: QueueContentType; +} +export interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +export interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +export interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +export declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +export interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +export interface ReadableStream<R = any> { + get locked(): boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +export declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +export interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +export declare abstract class ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +export declare abstract class ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +export declare abstract class ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +export declare abstract class WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +export interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +export interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +export declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + get locked(): boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +export declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + get closed(): Promise<void>; + get ready(): Promise<void>; + get desiredSize(): number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +export declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + get readable(): ReadableStream<O>; + get writable(): WritableStream<I>; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + get origin(): string; + get href(): string; + set href(value: string); + get protocol(): string; + set protocol(value: string); + get username(): string; + set username(value: string); + get password(): string; + set password(value: string); + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get pathname(): string; + set pathname(value: string); + get search(): string; + set search(value: string); + get hash(): string; + set hash(value: string); + get searchParams(): URLSearchParams; + toJSON(): string; + toString(): string; + static canParse(url: string, base?: string): boolean; +} +export declare class URLSearchParams { + constructor( + init?: Iterable<Iterable<string>> | Record<string, string> | string + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string, value?: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string, value?: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +export interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + get readyState(): number; + get url(): string | null; + get protocol(): string | null; + get extensions(): string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface SqlStorage { + exec(query: string, ...bindings: any[]): SqlStorageCursor; + prepare(query: string): SqlStorageStatement; + get databaseSize(): number; + Cursor: typeof SqlStorageCursor; + Statement: typeof SqlStorageStatement; +} +export declare abstract class SqlStorageStatement {} +export declare abstract class SqlStorageCursor { + raw(): IterableIterator<((ArrayBuffer | string | number) | null)[]>; + get columnNames(): string[]; + get rowsRead(): number; + get rowsWritten(): number; + [Symbol.iterator](): IterableIterator< + Record<string, (ArrayBuffer | string | number) | null> + >; +} +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export 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 */ +/** ISO 3166-1 Alpha-2 codes */ +export 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"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +export interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params<P extends string = any> = Record<P, string | string[]>; +export type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +export type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +export type 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>; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +export type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/index.d.ts b/node_modules/@cloudflare/workers-types/index.d.ts new file mode 100755 index 0000000..32190da --- /dev/null +++ b/node_modules/@cloudflare/workers-types/index.d.ts @@ -0,0 +1,3305 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +declare function btoa(data: string): string; +declare function atob(data: string): string; +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearTimeout(timeoutId: number | null): void; +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearInterval(timeoutId: number | null): void; +declare function queueMicrotask(task: Function): void; +declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +declare type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +declare interface Performance { + readonly timeOrigin: number; + now(): number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +declare interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +declare interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +declare interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. */ + readonly eventPhase: number; + /** Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. */ + readonly composed: boolean; + /** Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. */ + readonly bubbles: boolean; + /** Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. */ + readonly cancelable: boolean; + /** Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. */ + readonly defaultPrevented: boolean; + /** @deprecated */ + readonly returnValue: boolean; + /** Returns the object whose event listener's callback is currently being invoked. */ + readonly currentTarget?: EventTarget; + /** @deprecated */ + readonly srcElement?: EventTarget; + /** Returns the event's timestamp as the number of milliseconds measured relative to the time origin. */ + readonly timeStamp: number; + /** Returns true if event was dispatched by the user agent, and false otherwise. */ + readonly isTrusted: boolean; + cancelBubble: boolean; + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +declare interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** Returns the AbortSignal object associated with this object. */ + readonly signal: AbortSignal; + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. */ + readonly aborted: boolean; + readonly reason: any; + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + readonly size: number; + readonly type: string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + readonly name: string; + readonly lastModified: number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** Available only in secure contexts. */ + readonly subtle: SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise<ArrayBuffer>; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; +} +declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + readonly encoding: string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + readonly status: number; + readonly statusText: string; + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly url: string; + readonly webSocket: WebSocket | null; + readonly cf?: any; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + /** Returns request's HTTP method, which is "GET" by default. */ + readonly method: string; + /** Returns the URL of request as a string. */ + readonly url: string; + /** Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. */ + readonly headers: Headers; + /** Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. */ + readonly redirect: string; + readonly fetcher: Fetcher | null; + /** Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. */ + readonly signal: AbortSignal; + readonly cf?: Cf; + /** Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] */ + readonly integrity: string; + /** Returns a boolean indicating whether or not request can outlive the global in which it was created. */ + readonly keepalive: boolean; +} +declare interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +declare interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; +} +declare interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +declare interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +declare interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +declare interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +declare interface ReadableStream<R = any> { + readonly locked: boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + readonly closed: Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + readonly closed: Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +declare interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +declare interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +declare interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +declare interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +declare interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +declare interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +declare interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + readonly locked: boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + readonly closed: Promise<void>; + readonly ready: Promise<void>; + readonly desiredSize: number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + readonly readable: ReadableStream<O>; + readonly writable: WritableStream<I>; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream<string, Uint8Array> { + constructor(); +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + href: string; + readonly origin: string; + protocol: string; + username: string; + password: string; + host: string; + hostname: string; + port: string; + pathname: string; + search: string; + readonly searchParams: URLSearchParams; + hash: string; + toString(): string; + toJSON(): string; +} +declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record<string, string> + | [key: string, value: string][] + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +declare interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + /** Returns the state of the WebSocket object's connection. It can have the values described below. */ + readonly readyState: number; + /** Returns the URL that was used to establish the WebSocket connection. */ + readonly url: string | null; + /** Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. */ + readonly protocol: string | null; + /** Returns the extensions selected by the server, if any. */ + readonly extensions: string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare 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 */ +/** ISO 3166-1 Alpha-2 codes */ +declare 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"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +declare interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params<P extends string = any> = Record<P, string | string[]>; +declare type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +declare type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +declare type 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>; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +declare type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/index.ts b/node_modules/@cloudflare/workers-types/index.ts new file mode 100755 index 0000000..6415834 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/index.ts @@ -0,0 +1,3293 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +export declare function btoa(data: string): string; +export declare function atob(data: string): string; +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearTimeout(timeoutId: number | null): void; +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearInterval(timeoutId: number | null): void; +export declare function queueMicrotask(task: Function): void; +export declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +export declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +export type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +export interface Performance { + readonly timeOrigin: number; + now(): number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +export interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +export interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +export interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. */ + readonly eventPhase: number; + /** Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. */ + readonly composed: boolean; + /** Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. */ + readonly bubbles: boolean; + /** Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. */ + readonly cancelable: boolean; + /** Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. */ + readonly defaultPrevented: boolean; + /** @deprecated */ + readonly returnValue: boolean; + /** Returns the object whose event listener's callback is currently being invoked. */ + readonly currentTarget?: EventTarget; + /** @deprecated */ + readonly srcElement?: EventTarget; + /** Returns the event's timestamp as the number of milliseconds measured relative to the time origin. */ + readonly timeStamp: number; + /** Returns true if event was dispatched by the user agent, and false otherwise. */ + readonly isTrusted: boolean; + cancelBubble: boolean; + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +export interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +export declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** Returns the AbortSignal object associated with this object. */ + readonly signal: AbortSignal; + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. */ + readonly aborted: boolean; + readonly reason: any; + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + readonly size: number; + readonly type: string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + readonly name: string; + readonly lastModified: number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** Available only in secure contexts. */ + readonly subtle: SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +export declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise<ArrayBuffer>; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; +} +export declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + readonly encoding: string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + readonly status: number; + readonly statusText: string; + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly url: string; + readonly webSocket: WebSocket | null; + readonly cf?: any; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + /** Returns request's HTTP method, which is "GET" by default. */ + readonly method: string; + /** Returns the URL of request as a string. */ + readonly url: string; + /** Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. */ + readonly headers: Headers; + /** Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. */ + readonly redirect: string; + readonly fetcher: Fetcher | null; + /** Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. */ + readonly signal: AbortSignal; + readonly cf?: Cf; + /** Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] */ + readonly integrity: string; + /** Returns a boolean indicating whether or not request can outlive the global in which it was created. */ + readonly keepalive: boolean; +} +export interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +export interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +export interface QueueSendOptions { + contentType?: QueueContentType; +} +export interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +export interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +export interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +export declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +export interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +export interface ReadableStream<R = any> { + readonly locked: boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +export declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + readonly closed: Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + readonly closed: Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +export interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +export interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +export interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +export interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +export interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +export interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +export interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +export declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + readonly locked: boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +export declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + readonly closed: Promise<void>; + readonly ready: Promise<void>; + readonly desiredSize: number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +export declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + readonly readable: ReadableStream<O>; + readonly writable: WritableStream<I>; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + href: string; + readonly origin: string; + protocol: string; + username: string; + password: string; + host: string; + hostname: string; + port: string; + pathname: string; + search: string; + readonly searchParams: URLSearchParams; + hash: string; + toString(): string; + toJSON(): string; +} +export declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record<string, string> + | [key: string, value: string][] + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +export interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + /** Returns the state of the WebSocket object's connection. It can have the values described below. */ + readonly readyState: number; + /** Returns the URL that was used to establish the WebSocket connection. */ + readonly url: string | null; + /** Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. */ + readonly protocol: string | null; + /** Returns the extensions selected by the server, if any. */ + readonly extensions: string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export 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 */ +/** ISO 3166-1 Alpha-2 codes */ +export 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"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +export interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params<P extends string = any> = Record<P, string | string[]>; +export type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +export type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +export type 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>; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +export type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/oldest/index.d.ts b/node_modules/@cloudflare/workers-types/oldest/index.d.ts new file mode 100755 index 0000000..32190da --- /dev/null +++ b/node_modules/@cloudflare/workers-types/oldest/index.d.ts @@ -0,0 +1,3305 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +declare type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +declare interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +declare const console: Console; +declare type BufferSource = ArrayBufferView | ArrayBuffer; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +declare interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +declare function btoa(data: string): string; +declare function atob(data: string): string; +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearTimeout(timeoutId: number | null): void; +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +declare function clearInterval(timeoutId: number | null): void; +declare function queueMicrotask(task: Function): void; +declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +declare const self: ServiceWorkerGlobalScope; +declare const crypto: Crypto; +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +declare const performance: Performance; +declare const origin: string; +declare interface TestController {} +declare interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +declare type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +declare type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +declare interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +declare interface Performance { + readonly timeOrigin: number; + now(): number; +} +declare interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +declare interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +declare interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +declare type DurableObjectJurisdiction = "eu" | "fedramp"; +declare interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +declare type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +declare interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +declare interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +declare interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +declare interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +declare interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +declare interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +declare interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +declare interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +declare interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +declare interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +declare class Event { + constructor(type: string, init?: EventInit); + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. */ + readonly eventPhase: number; + /** Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. */ + readonly composed: boolean; + /** Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. */ + readonly bubbles: boolean; + /** Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. */ + readonly cancelable: boolean; + /** Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. */ + readonly defaultPrevented: boolean; + /** @deprecated */ + readonly returnValue: boolean; + /** Returns the object whose event listener's callback is currently being invoked. */ + readonly currentTarget?: EventTarget; + /** @deprecated */ + readonly srcElement?: EventTarget; + /** Returns the event's timestamp as the number of milliseconds measured relative to the time origin. */ + readonly timeStamp: number; + /** Returns true if event was dispatched by the user agent, and false otherwise. */ + readonly isTrusted: boolean; + cancelBubble: boolean; + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +declare interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +declare type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +declare interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +declare type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +declare interface EventTargetEventListenerOptions { + capture?: boolean; +} +declare interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +declare interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +declare class AbortController { + constructor(); + /** Returns the AbortSignal object associated with this object. */ + readonly signal: AbortSignal; + abort(reason?: any): void; +} +declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. */ + readonly aborted: boolean; + readonly reason: any; + throwIfAborted(): void; +} +declare interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +declare interface SchedulerWaitOptions { + signal?: AbortSignal; +} +declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + readonly size: number; + readonly type: string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +declare interface BlobOptions { + type?: string; +} +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + readonly name: string; + readonly lastModified: number; +} +declare interface FileOptions { + type?: string; + lastModified?: number; +} +declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +declare interface CacheQueryOptions { + ignoreMethod?: boolean; +} +declare abstract class Crypto { + /** Available only in secure contexts. */ + readonly subtle: SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +declare interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +declare interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +declare interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +declare interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +declare interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +declare interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +declare interface SubtleCryptoHashAlgorithm { + name: string; +} +declare interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +declare interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +declare interface CryptoKeyKeyAlgorithm { + name: string; +} +declare interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +declare interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +declare interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +declare interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +declare interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise<ArrayBuffer>; +} +declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; +} +declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + readonly encoding: string; +} +declare interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +declare interface TextDecoderDecodeOptions { + stream: boolean; +} +declare interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +declare interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +declare interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +declare interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +declare interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +declare interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +declare interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +declare interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +declare interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +declare type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +declare abstract class Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + readonly status: number; + readonly statusText: string; + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly url: string; + readonly webSocket: WebSocket | null; + readonly cf?: any; +} +declare interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +declare type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + /** Returns request's HTTP method, which is "GET" by default. */ + readonly method: string; + /** Returns the URL of request as a string. */ + readonly url: string; + /** Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. */ + readonly headers: Headers; + /** Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. */ + readonly redirect: string; + readonly fetcher: Fetcher | null; + /** Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. */ + readonly signal: AbortSignal; + readonly cf?: Cf; + /** Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] */ + readonly integrity: string; + /** Returns a boolean indicating whether or not request can outlive the global in which it was created. */ + readonly keepalive: boolean; +} +declare interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +declare interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +declare interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +declare type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +declare interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +declare interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +declare interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +declare interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +declare interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +declare type QueueContentType = "text" | "bytes" | "json" | "v8"; +declare interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +declare interface QueueSendOptions { + contentType?: QueueContentType; +} +declare interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +declare interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +declare interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +declare interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +declare interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +declare interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +declare interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +declare interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +declare type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +declare interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +declare interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +declare interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +declare interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +declare interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +declare interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +declare interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +declare type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +declare interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +declare interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +declare interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +declare interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +declare interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +declare type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +declare interface ReadableStream<R = any> { + readonly locked: boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + readonly closed: Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + readonly closed: Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +declare interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +declare interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +declare interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +declare interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +declare interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +declare interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +declare interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + readonly locked: boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + readonly closed: Promise<void>; + readonly ready: Promise<void>; + readonly desiredSize: number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + readonly readable: ReadableStream<O>; + readonly writable: WritableStream<I>; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +declare interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +declare class TextEncoderStream extends TransformStream<string, Uint8Array> { + constructor(); +} +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +declare interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +declare interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +declare interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +declare interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +declare interface TraceItemCustomEventInfo {} +declare interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +declare interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +declare interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +declare interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +declare interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +declare interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +declare interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +declare interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +declare interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +declare interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +declare class URL { + constructor(url: string | URL, base?: string | URL); + href: string; + readonly origin: string; + protocol: string; + username: string; + password: string; + host: string; + hostname: string; + port: string; + pathname: string; + search: string; + readonly searchParams: URLSearchParams; + hash: string; + toString(): string; + toJSON(): string; +} +declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record<string, string> + | [key: string, value: string][] + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +declare interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +declare interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +declare interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +declare interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +declare interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +declare interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +declare type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + /** Returns the state of the WebSocket object's connection. It can have the values described below. */ + readonly readyState: number; + /** Returns the URL that was used to establish the WebSocket connection. */ + readonly url: string | null; + /** Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. */ + readonly protocol: string | null; + /** Returns the extensions selected by the server, if any. */ + readonly extensions: string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +declare interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +declare interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +declare interface SocketAddress { + hostname: string; + port: number; +} +declare interface TlsOptions { + expectedServerHostname?: string; +} +declare interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +declare interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +declare interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +declare interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +declare interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +declare interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +declare type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +declare interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +declare interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +declare interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +declare interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +declare interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +declare interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +declare interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +declare interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +declare interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +declare interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare 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 */ +/** ISO 3166-1 Alpha-2 codes */ +declare 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"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +declare type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +declare interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +declare interface D1ExecResult { + count: number; + duration: number; +} +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +declare interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +declare interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +declare interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +declare interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +declare type Params<P extends string = any> = Record<P, string | string[]>; +declare type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +declare type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +declare type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +declare type 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>; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +declare interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +declare interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +declare module "cloudflare:sockets" { + function _connect( + address: string | SocketAddress, + options?: SocketOptions + ): Socket; + export { _connect as connect }; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +declare type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +declare type VectorFloatArray = Float32Array | Float64Array; +declare interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +declare type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +declare type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +declare interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +declare type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +declare interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +declare interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +declare interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +declare interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +declare interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +declare interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +declare interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +declare interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/oldest/index.ts b/node_modules/@cloudflare/workers-types/oldest/index.ts new file mode 100755 index 0000000..6415834 --- /dev/null +++ b/node_modules/@cloudflare/workers-types/oldest/index.ts @@ -0,0 +1,3293 @@ +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +export declare class DOMException extends Error { + constructor(message?: string, name?: string); + readonly message: string; + readonly name: string; + readonly code: number; + readonly stack: any; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; +} +export type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +export declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> { + EventTarget: typeof EventTarget; +} +export interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + trace(...data: any[]): void; + warn(...data: any[]): void; +} +export declare const console: Console; +export type BufferSource = ArrayBufferView | ArrayBuffer; +export declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = + | "anyfunc" + | "externref" + | "f32" + | "f64" + | "i32" + | "i64" + | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record<string, ImportValue>; + type Imports = Record<string, ModuleImports>; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record<string, ExportValue>; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise<Instance>; + function validate(bytes: BufferSource): boolean; +} +/** This ServiceWorker API interface represents the global execution context of a service worker. */ +export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone<T>(value: T, options?: StructuredSerializeOptions): T; + fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> + ): Promise<Response>; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +export declare function addEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean +): void; +export declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap +>( + type: Type, + handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean +): void; +/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ +export declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] +): boolean; +export declare function btoa(data: string): string; +export declare function atob(data: string): string; +export declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setTimeout<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearTimeout(timeoutId: number | null): void; +export declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number +): number; +export declare function setInterval<Args extends any[]>( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +export declare function clearInterval(timeoutId: number | null): void; +export declare function queueMicrotask(task: Function): void; +export declare function structuredClone<T>( + value: T, + options?: StructuredSerializeOptions +): T; +export declare function fetch( + input: RequestInfo, + init?: RequestInit<RequestInitCfProperties> +): Promise<Response>; +export declare const self: ServiceWorkerGlobalScope; +export declare const crypto: Crypto; +export declare const caches: CacheStorage; +export declare const scheduler: Scheduler; +export declare const performance: Performance; +export declare const origin: string; +export interface TestController {} +export interface ExecutionContext { + waitUntil(promise: Promise<any>): void; + passThroughOnException(): void; +} +export type ExportedHandlerFetchHandler< + Env = unknown, + CfHostMetadata = unknown +> = ( + request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, + env: Env, + ctx: ExecutionContext +) => Response | Promise<Response>; +export type ExportedHandlerTailHandler<Env = unknown> = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTraceHandler<Env = unknown> = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerScheduledHandler<Env = unknown> = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = ( + batch: MessageBatch<Message>, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export type ExportedHandlerTestHandler<Env = unknown> = ( + controller: TestController, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown +> { + fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata>; + tail?: ExportedHandlerTailHandler<Env>; + trace?: ExportedHandlerTraceHandler<Env>; + scheduled?: ExportedHandlerScheduledHandler<Env>; + test?: ExportedHandlerTestHandler<Env>; + email?: EmailExportedHandler<Env>; + queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage>; +} +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export declare abstract class PromiseRejectionEvent extends Event { + readonly promise: Promise<any>; + readonly reason: any; +} +/** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ +export interface Performance { + readonly timeOrigin: number; + now(): number; +} +export interface DurableObject { + fetch(request: Request): Response | Promise<Response>; + alarm?(): void | Promise<void>; + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer + ): void | Promise<void>; + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean + ): void | Promise<void>; + webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>; +} +export interface DurableObjectStub extends Fetcher { + readonly id: DurableObjectId; + readonly name?: string; +} +export interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +export interface DurableObjectNamespace { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions + ): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions + ): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +export type DurableObjectJurisdiction = "eu" | "fedramp"; +export interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +export type DurableObjectLocationHint = + | "wnam" + | "enam" + | "sam" + | "weur" + | "eeur" + | "apac" + | "oc" + | "afr" + | "me"; +export interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +export interface DurableObjectState { + waitUntil(promise: Promise<any>): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; +} +export interface DurableObjectTransaction { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; +} +export interface DurableObjectStorage { + get<T = unknown>( + key: string, + options?: DurableObjectGetOptions + ): Promise<T | undefined>; + get<T = unknown>( + keys: string[], + options?: DurableObjectGetOptions + ): Promise<Map<string, T>>; + list<T = unknown>( + options?: DurableObjectListOptions + ): Promise<Map<string, T>>; + put<T>( + key: string, + value: T, + options?: DurableObjectPutOptions + ): Promise<void>; + put<T>( + entries: Record<string, T>, + options?: DurableObjectPutOptions + ): Promise<void>; + delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; + delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; + deleteAll(options?: DurableObjectPutOptions): Promise<void>; + transaction<T>( + closure: (txn: DurableObjectTransaction) => Promise<T> + ): Promise<T>; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>; + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions + ): Promise<void>; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>; + sync(): Promise<void>; + transactionSync<T>(closure: () => T): T; +} +export interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +export interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +export interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +export interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +export declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +export interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +export interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +export declare class Event { + constructor(type: string, init?: EventInit); + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. */ + readonly eventPhase: number; + /** Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. */ + readonly composed: boolean; + /** Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. */ + readonly bubbles: boolean; + /** Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. */ + readonly cancelable: boolean; + /** Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. */ + readonly defaultPrevented: boolean; + /** @deprecated */ + readonly returnValue: boolean; + /** Returns the object whose event listener's callback is currently being invoked. */ + readonly currentTarget?: EventTarget; + /** @deprecated */ + readonly srcElement?: EventTarget; + /** Returns the event's timestamp as the number of milliseconds measured relative to the time origin. */ + readonly timeStamp: number; + /** Returns true if event was dispatched by the user agent, and false otherwise. */ + readonly isTrusted: boolean; + cancelBubble: boolean; + stopImmediatePropagation(): void; + preventDefault(): void; + stopPropagation(): void; + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +export interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +export type EventListener<EventType extends Event = Event> = ( + event: EventType +) => void; +export interface EventListenerObject<EventType extends Event = Event> { + handleEvent(event: EventType): void; +} +export type EventListenerOrEventListenerObject< + EventType extends Event = Event +> = EventListener<EventType> | EventListenerObject<EventType>; +export declare class EventTarget< + EventMap extends Record<string, Event> = Record<string, Event> +> { + constructor(); + addEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetAddEventListenerOptions | boolean + ): void; + removeEventListener<Type extends keyof EventMap>( + type: Type, + handler: EventListenerOrEventListenerObject<EventMap[Type]>, + options?: EventTargetEventListenerOptions | boolean + ): void; + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +export interface EventTargetEventListenerOptions { + capture?: boolean; +} +export interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +export interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +export declare class AbortController { + constructor(); + /** Returns the AbortSignal object associated with this object. */ + readonly signal: AbortSignal; + abort(reason?: any): void; +} +export declare abstract class AbortSignal extends EventTarget { + static abort(reason?: any): AbortSignal; + static timeout(delay: number): AbortSignal; + static any(signals: AbortSignal[]): AbortSignal; + /** Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. */ + readonly aborted: boolean; + readonly reason: any; + throwIfAborted(): void; +} +export interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>; +} +export interface SchedulerWaitOptions { + signal?: AbortSignal; +} +export declare abstract class ExtendableEvent extends Event { + waitUntil(promise: Promise<any>): void; +} +export declare class Blob { + constructor( + bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions + ); + readonly size: number; + readonly type: string; + slice(start?: number, end?: number, type?: string): Blob; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + stream(): ReadableStream; +} +export interface BlobOptions { + type?: string; +} +export declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions + ); + readonly name: string; + readonly lastModified: number; +} +export interface FileOptions { + type?: string; + lastModified?: number; +} +export declare abstract class CacheStorage { + open(cacheName: string): Promise<Cache>; + readonly default: Cache; +} +export declare abstract class Cache { + delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>; + match( + request: RequestInfo, + options?: CacheQueryOptions + ): Promise<Response | undefined>; + put(request: RequestInfo, response: Response): Promise<void>; +} +export interface CacheQueryOptions { + ignoreMethod?: boolean; +} +export declare abstract class Crypto { + /** Available only in secure contexts. */ + readonly subtle: SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + >(buffer: T): T; + randomUUID(): string; + DigestStream: typeof DigestStream; +} +export declare abstract class SubtleCrypto { + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView + ): Promise<boolean>; + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView + ): Promise<ArrayBuffer>; + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey | CryptoKeyPair>; + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length: number | null + ): Promise<ArrayBuffer>; + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>; + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm + ): Promise<ArrayBuffer>; + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[] + ): Promise<CryptoKey>; + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView + ): boolean; +} +export declare abstract class CryptoKey { + readonly type: string; + readonly extractable: boolean; + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + readonly usages: string[]; +} +export interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +export interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +export interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +export interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer; +} +export interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer; + additionalData?: ArrayBuffer; + tagLength?: number; + counter?: ArrayBuffer; + length?: number; + label?: ArrayBuffer; +} +export interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer; + length?: number; + namedCurve?: string; +} +export interface SubtleCryptoHashAlgorithm { + name: string; +} +export interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +export interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +export interface CryptoKeyKeyAlgorithm { + name: string; +} +export interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +export interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +export interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer; + hash?: CryptoKeyKeyAlgorithm; +} +export interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +export interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +export declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise<ArrayBuffer>; +} +export declare class TextDecoder { + constructor(decoder?: string, options?: TextDecoderConstructorOptions); + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions + ): string; + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; +} +export declare class TextEncoder { + constructor(); + encode(input?: string): Uint8Array; + encodeInto( + input: string, + buffer: ArrayBuffer | ArrayBufferView + ): TextEncoderEncodeIntoResult; + readonly encoding: string; +} +export interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +export interface TextDecoderDecodeOptions { + stream: boolean; +} +export interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +export declare class FormData { + constructor(); + append(name: string, value: string): void; + append(name: string, value: Blob, filename?: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<File | string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: FormData + ) => void, + thisArg?: This + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export interface ContentOptions { + html?: boolean; +} +export declare class HTMLRewriter { + constructor(); + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers + ): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +export interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(element: Text): void | Promise<void>; +} +export interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise<void>; + comments?(comment: Comment): void | Promise<void>; + text?(text: Text): void | Promise<void>; + end?(end: DocumentEnd): void | Promise<void>; +} +export interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +export interface Element { + tagName: string; + readonly attributes: IterableIterator<string[]>; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string, options?: ContentOptions): Element; + after(content: string, options?: ContentOptions): Element; + prepend(content: string, options?: ContentOptions): Element; + append(content: string, options?: ContentOptions): Element; + replace(content: string, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise<void>): void; +} +export interface EndTag { + name: string; + before(content: string, options?: ContentOptions): EndTag; + after(content: string, options?: ContentOptions): EndTag; + remove(): EndTag; +} +export interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +export interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Text; + after(content: string, options?: ContentOptions): Text; + replace(content: string, options?: ContentOptions): Text; + remove(): Text; +} +export interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +export declare abstract class FetchEvent extends ExtendableEvent { + readonly request: Request; + respondWith(promise: Response | Promise<Response>): void; + passThroughOnException(): void; +} +export type HeadersInit = + | Headers + | Iterable<Iterable<string>> + | Record<string, string>; +export declare class Headers { + constructor(init?: HeadersInit); + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + append(name: string, value: string): void; + delete(name: string): void; + forEach<This = unknown>( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This + ): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export type BodyInit = + | ReadableStream<Uint8Array> + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData; +export declare abstract class Body { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + formData(): Promise<FormData>; + blob(): Promise<Blob>; +} +export declare class Response extends Body { + constructor(body?: BodyInit | null, init?: ResponseInit); + static redirect(url: string, status?: number): Response; + static json(any: any, maybeInit?: ResponseInit | Response): Response; + clone(): Response; + readonly status: number; + readonly statusText: string; + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly url: string; + readonly webSocket: WebSocket | null; + readonly cf?: any; +} +export interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: "automatic" | "manual"; +} +export type RequestInfo< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> = Request<CfHostMetadata, Cf> | string | URL; +export declare class Request< + CfHostMetadata = unknown, + Cf = CfProperties<CfHostMetadata> +> extends Body { + constructor(input: RequestInfo<CfProperties>, init?: RequestInit<Cf>); + clone(): Request<CfHostMetadata, Cf>; + /** Returns request's HTTP method, which is "GET" by default. */ + readonly method: string; + /** Returns the URL of request as a string. */ + readonly url: string; + /** Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. */ + readonly headers: Headers; + /** Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. */ + readonly redirect: string; + readonly fetcher: Fetcher | null; + /** Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. */ + readonly signal: AbortSignal; + readonly cf?: Cf; + /** Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] */ + readonly integrity: string; + /** Returns a boolean indicating whether or not request can outlive the global in which it was created. */ + readonly keepalive: boolean; +} +export interface RequestInit<Cf = CfProperties> { + /** A string to set request's method. */ + method?: string; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** 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. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; +} +export declare abstract class Fetcher { + fetch(input: RequestInfo, init?: RequestInit): Promise<Response>; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +} +export interface FetcherPutOptions { + expiration?: number; + expirationTtl?: number; +} +export interface KVNamespaceListKey<Metadata, Key extends string = string> { + name: Key; + expiration?: number; + metadata?: Metadata; +} +export type KVNamespaceListResult<Metadata, Key extends string = string> = + | { + list_complete: false; + keys: KVNamespaceListKey<Metadata, Key>[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey<Metadata, Key>[]; + cacheStatus: string | null; + }; +export interface KVNamespace<Key extends string = string> { + get( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<string | null>; + get(key: Key, type: "text"): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + type: "json" + ): Promise<ExpectedValue | null>; + get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>; + get(key: Key, type: "stream"): Promise<ReadableStream | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"text"> + ): Promise<string | null>; + get<ExpectedValue = unknown>( + key: Key, + options?: KVNamespaceGetOptions<"json"> + ): Promise<ExpectedValue | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<ArrayBuffer | null>; + get( + key: Key, + options?: KVNamespaceGetOptions<"stream"> + ): Promise<ReadableStream | null>; + list<Metadata = unknown>( + options?: KVNamespaceListOptions + ): Promise<KVNamespaceListResult<Metadata, Key>>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions + ): Promise<void>; + getWithMetadata<Metadata = unknown>( + key: Key, + options?: Partial<KVNamespaceGetOptions<undefined>> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "text" + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + type: "json" + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "arrayBuffer" + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + type: "stream" + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"text"> + ): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>; + getWithMetadata<ExpectedValue = unknown, Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"json"> + ): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"arrayBuffer"> + ): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>; + getWithMetadata<Metadata = unknown>( + key: Key, + options: KVNamespaceGetOptions<"stream"> + ): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>; + delete(key: Key): Promise<void>; +} +export interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +export interface KVNamespaceGetOptions<Type> { + type: Type; + cacheTtl?: number; +} +export interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +export interface KVNamespaceGetWithMetadataResult<Value, Metadata> { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +export type QueueContentType = "text" | "bytes" | "json" | "v8"; +export interface Queue<Body = unknown> { + send(message: Body, options?: QueueSendOptions): Promise<void>; + sendBatch(messages: Iterable<MessageSendRequest<Body>>): Promise<void>; +} +export interface QueueSendOptions { + contentType?: QueueContentType; +} +export interface MessageSendRequest<Body = unknown> { + body: Body; + contentType?: QueueContentType; +} +export interface Message<Body = unknown> { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + retry(): void; + ack(): void; +} +export interface QueueEvent<Body = unknown> extends ExtendableEvent { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface MessageBatch<Body = unknown> { + readonly messages: readonly Message<Body>[]; + readonly queue: string; + retryAll(): void; + ackAll(): void; +} +export interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +export interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; +} +export declare abstract class R2Bucket { + head(key: string): Promise<R2Object | null>; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2ObjectBody | R2Object | null>; + get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + } + ): Promise<R2Object | null>; + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions + ): Promise<R2Object>; + createMultipartUpload( + key: string, + options?: R2MultipartOptions + ): Promise<R2MultipartUpload>; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise<void>; + list(options?: R2ListOptions): Promise<R2Objects>; +} +export interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob + ): Promise<R2UploadedPart>; + abort(): Promise<void>; + complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>; +} +export interface R2UploadedPart { + partNumber: number; + etag: string; +} +export declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record<string, string>; + readonly range?: R2Range; + writeHttpMetadata(headers: Headers): void; +} +export interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise<ArrayBuffer>; + text(): Promise<string>; + json<T>(): Promise<T>; + blob(): Promise<Blob>; +} +export type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +export interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +export interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; +} +export interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; + md5?: ArrayBuffer | string; + sha1?: ArrayBuffer | string; + sha256?: ArrayBuffer | string; + sha384?: ArrayBuffer | string; + sha512?: ArrayBuffer | string; +} +export interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record<string, string>; +} +export interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +export interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +export interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +export type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +export declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +export interface QueuingStrategy<T = any> { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +export interface UnderlyingSink<W = any> { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise<void>; + write?: ( + chunk: W, + controller: WritableStreamDefaultController + ) => void | Promise<void>; + abort?: (reason: any) => void | Promise<void>; + close?: () => void | Promise<void>; +} +export interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise<void>; + pull?: (controller: ReadableByteStreamController) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface UnderlyingSource<R = any> { + type?: "" | undefined; + start?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + pull?: ( + controller: ReadableStreamDefaultController<R> + ) => void | Promise<void>; + cancel?: (reason: any) => void | Promise<void>; +} +export interface Transformer<I = any, O = any> { + readableType?: string; + writableType?: string; + start?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + transform?: ( + chunk: I, + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; + flush?: ( + controller: TransformStreamDefaultController<O> + ) => void | Promise<void>; +} +export interface StreamPipeOptions { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * 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. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +export type ReadableStreamReadResult<R = any> = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** This Streams API interface 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. */ +export interface ReadableStream<R = any> { + readonly locked: boolean; + cancel(reason?: any): Promise<void>; + getReader(): ReadableStreamDefaultReader<R>; + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + pipeThrough<T>( + transform: ReadableWritablePair<T, R>, + options?: StreamPipeOptions + ): ReadableStream<T>; + pipeTo( + destination: WritableStream<R>, + options?: StreamPipeOptions + ): Promise<void>; + tee(): [ReadableStream<R>, ReadableStream<R>]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>; + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions + ): AsyncIterableIterator<R>; +} +export declare const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy<Uint8Array> + ): ReadableStream<Uint8Array>; + new <R = any>( + underlyingSource?: UnderlyingSource<R>, + strategy?: QueuingStrategy<R> + ): ReadableStream<R>; +}; +export declare class ReadableStreamDefaultReader<R = any> { + constructor(stream: ReadableStream); + readonly closed: Promise<void>; + cancel(reason?: any): Promise<void>; + read(): Promise<ReadableStreamReadResult<R>>; + releaseLock(): void; +} +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + readonly closed: Promise<void>; + cancel(reason?: any): Promise<void>; + read<T extends ArrayBufferView>( + view: T + ): Promise<ReadableStreamReadResult<T>>; + releaseLock(): void; + readAtLeast<T extends ArrayBufferView>( + minElements: number, + view: T + ): Promise<ReadableStreamReadResult<T>>; +} +export interface ReadableStreamGetReaderOptions { + mode: "byob"; +} +export interface ReadableStreamBYOBRequest { + readonly view: Uint8Array | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + readonly atLeast: number | null; +} +export interface ReadableStreamDefaultController<R = any> { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(reason: any): void; +} +export interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + error(reason: any): void; +} +/** This Streams API interface 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. */ +export interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(reason?: any): void; +} +export interface TransformStreamDefaultController<O = any> { + get desiredSize(): number | null; + enqueue(chunk?: O): void; + error(reason: any): void; + terminate(): void; +} +export interface ReadableWritablePair<R = any, W = any> { + /** + * 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. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream<W>; + readable: ReadableStream<R>; +} +export declare class WritableStream<W = any> { + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy + ); + readonly locked: boolean; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + getWriter(): WritableStreamDefaultWriter<W>; +} +export declare class WritableStreamDefaultWriter<W = any> { + constructor(stream: WritableStream); + readonly closed: Promise<void>; + readonly ready: Promise<void>; + readonly desiredSize: number | null; + abort(reason?: any): Promise<void>; + close(): Promise<void>; + write(chunk?: W): Promise<void>; + releaseLock(): void; +} +export declare class TransformStream<I = any, O = any> { + constructor( + transformer?: Transformer<I, O>, + writableStrategy?: QueuingStrategy<I>, + readableStrategy?: QueuingStrategy<O> + ); + readonly readable: ReadableStream<O>; + readonly writable: WritableStream<I>; +} +export declare class FixedLengthStream extends IdentityTransformStream { + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy + ); +} +export declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +export interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +export interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +export declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +export declare class TextEncoderStream extends TransformStream< + string, + Uint8Array +> { + constructor(); +} +export declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); +} +export interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; +} +export declare class ByteLengthQueuingStrategy + implements QueuingStrategy<ArrayBufferView> +{ + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + get highWaterMark(): number; + get size(): (chunk?: any) => number; +} +export interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * 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. + */ + highWaterMark: number; +} +export declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +export interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemCustomEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly outcome: string; +} +export interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +export interface TraceItemCustomEventInfo {} +export interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +export interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +export interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +export interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record<string, string>; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +export interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +export interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +export interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; +} +export interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +export interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +export interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +export declare class URL { + constructor(url: string | URL, base?: string | URL); + href: string; + readonly origin: string; + protocol: string; + username: string; + password: string; + host: string; + hostname: string; + port: string; + pathname: string; + search: string; + readonly searchParams: URLSearchParams; + hash: string; + toString(): string; + toJSON(): string; +} +export declare class URLSearchParams { + constructor( + init?: + | URLSearchParams + | string + | Record<string, string> + | [key: string, value: string][] + ); + get size(): number; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + entries(): IterableIterator<[key: string, value: string]>; + keys(): IterableIterator<string>; + values(): IterableIterator<string>; + forEach<This = unknown>( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams + ) => void, + thisArg?: This + ): void; + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +export declare class URLPattern { + constructor(input?: string | URLPatternURLPatternInit, baseURL?: string); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternURLPatternInit, baseURL?: string): boolean; + exec( + input?: string | URLPatternURLPatternInit, + baseURL?: string + ): URLPatternURLPatternResult | null; +} +export interface URLPatternURLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +export interface URLPatternURLPatternComponentResult { + input: string; + groups: Record<string, string>; +} +export interface URLPatternURLPatternResult { + inputs: (string | URLPatternURLPatternInit)[]; + protocol: URLPatternURLPatternComponentResult; + username: URLPatternURLPatternComponentResult; + password: URLPatternURLPatternComponentResult; + hostname: URLPatternURLPatternComponentResult; + port: URLPatternURLPatternComponentResult; + pathname: URLPatternURLPatternComponentResult; + search: URLPatternURLPatternComponentResult; + hash: URLPatternURLPatternComponentResult; +} +export declare class CloseEvent extends Event { + constructor(type: string, initializer: CloseEventInit); + /** Returns the WebSocket connection close code provided by the server. */ + readonly code: number; + /** Returns the WebSocket connection close reason provided by the server. */ + readonly reason: string; + /** Returns true if the connection closed cleanly; false otherwise. */ + readonly wasClean: boolean; +} +export interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +export declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + readonly data: ArrayBuffer | string; +} +export interface MessageEventInit { + data: ArrayBuffer | string; +} +/** Events providing information related to errors in scripts or in files. */ +export interface ErrorEvent extends Event { + readonly filename: string; + readonly message: string; + readonly lineno: number; + readonly colno: number; + readonly error: any; +} +export type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +export declare class WebSocket extends EventTarget<WebSocketEventMap> { + constructor(url: string, protocols?: string[] | string); + accept(): void; + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + static readonly READY_STATE_CONNECTING: number; + static readonly READY_STATE_OPEN: number; + static readonly READY_STATE_CLOSING: number; + static readonly READY_STATE_CLOSED: number; + /** Returns the state of the WebSocket object's connection. It can have the values described below. */ + readonly readyState: number; + /** Returns the URL that was used to establish the WebSocket connection. */ + readonly url: string | null; + /** Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. */ + readonly protocol: string | null; + /** Returns the extensions selected by the server, if any. */ + readonly extensions: string | null; +} +export declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +export interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise<void>; + close(): Promise<void>; + startTls(options?: TlsOptions): Socket; +} +export interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; +} +export interface SocketAddress { + hostname: string; + port: number; +} +export interface TlsOptions { + expectedServerHostname?: string; +} +export interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | "left" + | "right" + | "top" + | "bottom" + | "center" + | "auto" + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +export interface BasicImageTransformationsGravityCoordinates { + x: number; + y: number; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +export interface RequestInitCfProperties extends Record<string, unknown> { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record<string, number>; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +export interface RequestInitCfPropertiesImageDraw + extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +export interface RequestInitCfPropertiesImage + extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in <img srcset>. + */ + dpr?: number; + /** + * An object with four properties {left, top, right, bottom} that specify + * a number of pixels to cut off on each side. Allows removal of borders + * or cutting out a specific fragment of an image. Trimming is performed + * before resizing or rotation. Takes dpr into account. + */ + trim?: { + left?: number; + top?: number; + right?: number; + bottom?: number; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +export interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +export type IncomingRequestCfProperties<HostMetadata = unknown> = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +export interface IncomingRequestCfPropertiesBase + extends Record<string, unknown> { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * 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. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +export interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * 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). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * 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. + */ + staticResource: boolean; + /** + * 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). + */ + detectionIds: number[]; +} +export interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +export interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +export interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise< + HostMetadata +> { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata: HostMetadata; +} +export interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +export interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +export interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * 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. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +export interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude<CertVerificationStatus, "NONE">; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +export interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +export type CertVerificationStatus = + /** Authentication succeeded */ + | "SUCCESS" + /** No certificate was presented */ + | "NONE" + /** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" + /** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" + /** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" + /** Failed because the certificate is expired */ + | "FAILED:certificate has expired" + /** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +export 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 */ +/** ISO 3166-1 Alpha-2 codes */ +export 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"; +/** The 2-letter continent codes Cloudflare uses */ +export type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +export type CfProperties<HostMetadata = unknown> = + | IncomingRequestCfProperties<HostMetadata> + | RequestInitCfProperties; +export interface D1Result<T = unknown> { + results: T[]; + success: true; + meta: any; + error?: never; +} +export interface D1ExecResult { + count: number; + duration: number; +} +export declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + dump(): Promise<ArrayBuffer>; + batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; + exec(query: string): Promise<D1ExecResult>; +} +export declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first<T = unknown>(colName: string): Promise<T | null>; + first<T = Record<string, unknown>>(): Promise<T | null>; + run<T = Record<string, unknown>>(): Promise<D1Result<T>>; + all<T = Record<string, unknown>>(): Promise<D1Result<T>>; + raw<T = unknown[]>(): Promise<T[]>; +} +/** + * An email message that can be sent from a Worker. + */ +export interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +export interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise<void>; +} +/** + * A binding that allows a Worker to send email messages. + */ +export interface SendEmail { + send(message: EmailMessage): Promise<void>; +} +export declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +export type EmailExportedHandler<Env = unknown> = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext +) => void | Promise<void>; +export interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: string; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +export type Params<P extends string = any> = Record<P, string | string[]>; +export type EventContext<Env, P extends string, Data> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; +}; +export type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record<string, unknown> = Record<string, unknown> +> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>; +export type EventPluginContext<Env, P extends string, Data, PluginArgs> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise<any>) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise<Response>; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params<P>; + data: Data; + pluginArgs: PluginArgs; +}; +export type 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>; +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +export interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +export interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Additional information to associate with a vector. + */ +export type VectorizeVectorMetadata = + | string + | number + | boolean + | string[] + | Record<string, string | number | boolean | string[]>; +export type VectorFloatArray = Float32Array | Float64Array; +export interface VectorizeError { + code?: number; + error: string; +} +/** + * A pre-configured list of known models. + * These can be supplied in place of configuring explicit dimensions. + */ +export type VectorizePreset = + | "openapi-text-embedding-ada-002" + | "workers-ai/bge-small-en" + | "cohere/embed-multilingual-v2.0"; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +export type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +export interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnVectors?: boolean; +} +/** + * Information about the configuration of an index. + */ +export type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: VectorizePreset; + }; +/** + * Metadata about an existing index. + */ +export interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +export interface VectorizeVector { + /** 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. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the binding. Includes the values of the other fields and potentially additional details. */ + metadata?: Record<string, VectorizeVectorMetadata>; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +export interface VectorizeMatch { + /** 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. */ + vectorId: string; + /** The score or rank for similarity, when returned as a result */ + score: number; + /** Vector data for the match. Included only if the user specified they want it returned (via {@link VectorizeQueryOptions}). */ + vector?: VectorizeVector; +} +/** + * A set of vector {@link VectorizeMatch} for a particular query. + */ +export interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + */ +export interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +export declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise<VectorizeIndexDetails>; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options: VectorizeQueryOptions + ): Promise<VectorizeMatches>; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise<VectorizeVector[]>; +} +export interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +export interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +export interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions + ): Fetcher; +} diff --git a/node_modules/@cloudflare/workers-types/package.json b/node_modules/@cloudflare/workers-types/package.json new file mode 100644 index 0000000..c20d5af --- /dev/null +++ b/node_modules/@cloudflare/workers-types/package.json @@ -0,0 +1,11 @@ +{ + "name": "@cloudflare/workers-types", + "description": "TypeScript typings for Cloudflare Workers", + "repository": { + "type": "git", + "url": "https://github.com/cloudflare/workerd" + }, + "author": "Cloudflare Workers DevProd Team <workers-devprod@cloudflare.com> (https://workers.cloudflare.com)", + "license": "MIT OR Apache-2.0", + "version": "4.20230914.0" +} |
